commit 4bde3b176a9915a45c6a04df233086dbdc700b30 Author: Scifi9902 <44736675+Scifi9902@users.noreply.github.com> Date: Mon Oct 12 13:57:05 2026 -0300 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4dd012d --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/target/ +/.idea/ +*.iml +*/target/ +*/dependency-reduced-pom.xml +/Enchantments/out/ +*/out/ +/Factions/modules/Legacy/target/ +/Factions/modules/FactionsLegacy/target/ diff --git a/.lib/CoreProtect_2.12.0.jar b/.lib/CoreProtect_2.12.0.jar new file mode 100644 index 0000000..1d259fc Binary files /dev/null and b/.lib/CoreProtect_2.12.0.jar differ diff --git a/.lib/EssentialsX-2.19.7.jar b/.lib/EssentialsX-2.19.7.jar new file mode 100644 index 0000000..9b58453 Binary files /dev/null and b/.lib/EssentialsX-2.19.7.jar differ diff --git a/.lib/FactionsKore-1.3.431.jar b/.lib/FactionsKore-1.3.431.jar new file mode 100644 index 0000000..2c6efeb Binary files /dev/null and b/.lib/FactionsKore-1.3.431.jar differ diff --git a/.lib/FactionsKore-1.3.62.1.jar b/.lib/FactionsKore-1.3.62.1.jar new file mode 100644 index 0000000..c3de61e Binary files /dev/null and b/.lib/FactionsKore-1.3.62.1.jar differ diff --git a/.lib/TAB.v3.1.2.jar b/.lib/TAB.v3.1.2.jar new file mode 100644 index 0000000..6d31e06 Binary files /dev/null and b/.lib/TAB.v3.1.2.jar differ diff --git a/.lib/WineSpigot-V1.4.4.3.jar b/.lib/WineSpigot-V1.4.4.3.jar new file mode 100644 index 0000000..bb7fb4f Binary files /dev/null and b/.lib/WineSpigot-V1.4.4.3.jar differ diff --git a/.lib/WineSpigot-V1.7.4.2.jar b/.lib/WineSpigot-V1.7.4.2.jar new file mode 100644 index 0000000..7c54521 Binary files /dev/null and b/.lib/WineSpigot-V1.7.4.2.jar differ diff --git a/AdminArmor/pom.xml b/AdminArmor/pom.xml new file mode 100644 index 0000000..3eb0c90 --- /dev/null +++ b/AdminArmor/pom.xml @@ -0,0 +1,54 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + AdminArmor + + + 8 + 8 + + + + + + net.crankedpvp + Utils + + + net.crankedpvp + Armor + + + net.crankedpvp + Enchants + + + net.crankedpvp + Masks + + + net.crankedpvp + Pets + + + net.crankedpvp + AdminWeapons + + + net.crankedpvp + StarItems + + + net.crankedpvp + HolyWhitescrolls + + + \ No newline at end of file diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/AdminArmorAPI.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/AdminArmorAPI.java new file mode 100644 index 0000000..036b0d0 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/AdminArmorAPI.java @@ -0,0 +1,12 @@ +package net.crankedpvp.adminarmor; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.struct.ArmorSet; + +public class AdminArmorAPI { + + public static ArmorSet getArmorSetFromID(String string) { + return CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID(string); + } + +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/AdminArmorPlugin.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/AdminArmorPlugin.java new file mode 100644 index 0000000..5509ca6 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/AdminArmorPlugin.java @@ -0,0 +1,52 @@ +package net.crankedpvp.adminarmor; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.adminarmor.commands.AdminArmorCommand; +import net.crankedpvp.adminarmor.inventory.AdminArmorInventory; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.AdminArmorRegister; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Arrays; +import java.util.stream.Collectors; + +public class AdminArmorPlugin extends JavaPlugin { + + @Getter + private static AdminArmorPlugin instance; + @Getter + private AdminArmorRegister adminArmorRegister; + @Getter + private CommandManager commandManager; + + @Getter + private AdminArmorInventory adminArmorInventory; + + @Override + public void onEnable() { + instance = this; + this.adminArmorRegister = new AdminArmorRegister(this); + this.adminArmorRegister.initialize(); + + this.commandManager = new CommandManager(this); + this.registerCommandCompletion(); + this.commandManager.register(new AdminArmorCommand(this)); + + this.adminArmorInventory = new AdminArmorInventory(); + + } + + + @Override + public void onDisable() { + + } + + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#adminarmor", input -> this.adminArmorRegister.getAdminArmor().stream().map(AdminArmor::getID).collect(Collectors.toList())); + this.commandManager.getCompletionHandler().register("#boolean", input -> Arrays.asList("true", "false")); + } + +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/cadia/BloodBoundCuirass.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/cadia/BloodBoundCuirass.java new file mode 100644 index 0000000..a6f95a7 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/cadia/BloodBoundCuirass.java @@ -0,0 +1,79 @@ +package net.crankedpvp.adminarmor.adminarmor.cadia; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class BloodBoundCuirass extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "BloodBoundCuirass"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_CHESTPLATE; + } + + @Override + public String getDisplayName() { + return "&4&kii&r &c&lBlood-Bound Cuirass &4&kii&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&4War is &c&l&nCRUELTY&r&4. There is no point", + "&4trying to reform it. The crueler it is,", + "&4the sooner it will be over..." + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("equalizer"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("leviathan"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/cosmic/CosmicTasteTheRainbow.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/cosmic/CosmicTasteTheRainbow.java new file mode 100644 index 0000000..d361fb3 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/cosmic/CosmicTasteTheRainbow.java @@ -0,0 +1,78 @@ +package net.crankedpvp.adminarmor.adminarmor.cosmic; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CosmicTasteTheRainbow extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Taste The Rainbow"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_LEGGINGS; + } + + @Override + public String getDisplayName() { + return "&f&l~-=&4&lT&c&la&6&ls&e<&a&le &2&lThe Ra&b&li&9&ln&1&lb&5&lo&d&lw&f&l=-~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&fYes, it's &c&l&nB&6&l&nR&e&l&nO&a&l&nK&b&l&nE&d&l&nN&5&l&n!&r &fWanna &9CRY?", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("obsidianshield"), 1); + put(enchantRegister.getEnchantmentFromID("divineenlighted"), 1); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("phantom"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/AbyssWalkingSabatons.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/AbyssWalkingSabatons.java new file mode 100644 index 0000000..2a2a5e0 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/AbyssWalkingSabatons.java @@ -0,0 +1,80 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AbyssWalkingSabatons extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Abyss Walking Sabatons"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public String getDisplayName() { + return "&d&kii&r &f&lAbyss Walking Sabatons &d&kii&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&fShoes that allow the wearer to walk", + "&fon the ocean floor and summon creatures", + "&ffrom the deep to do their bidding." + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("abyss"), 4); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + //return AdminArmorAPI.getArmorSetFromID("rover"); + return AdminArmorAPI.getArmorSetFromID("yijki"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/BuffedBard.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/BuffedBard.java new file mode 100644 index 0000000..7f3ee1b --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/BuffedBard.java @@ -0,0 +1,81 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class BuffedBard extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Buffed Bard"; + } + + @Override + public Material getMaterial() { + return Material.GOLD_BOOTS; + } + + @Override + public String getDisplayName() { + return "&e&kii&r &6&lBuffed Bard &e&kii&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&fBard sucks.. so you need me!" + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("abyss"), 4); + put(enchantRegister.getEnchantmentFromID("divineenlighted"), 2); + put(enchantRegister.getEnchantmentFromID("polymorphicmetaphysical"), 2); + put(enchantRegister.getEnchantmentFromID("etherealdodge"), 1); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + //return AdminArmorAPI.getArmorSetFromID("rover"); + return AdminArmorAPI.getArmorSetFromID("bard"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/CaptainsDreadHelm.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/CaptainsDreadHelm.java new file mode 100644 index 0000000..7ef1781 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/CaptainsDreadHelm.java @@ -0,0 +1,83 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CaptainsDreadHelm extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + + @Override + public String getName() { + return "Captains Dread Helm"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HELMET; + } + + @Override + public String getDisplayName() { + return "&4&kii&r &c&lCaptains Dread Helm &4&kii&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&cA helmet made from the timbers of a cursed", + "&cship, granting the wearer the power to", + "&ccommand the winds and waves." + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("drunk"), 4); + put(enchantRegister.getEnchantmentFromID("enlighted"), 3); + put(enchantRegister.getEnchantmentFromID("implants"), 3); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return false; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + //return AdminArmorAPI.getArmorSetFromID("pirate"); + return AdminArmorAPI.getArmorSetFromID("phantom"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/DevilsHeart.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/DevilsHeart.java new file mode 100644 index 0000000..2cc90ce --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/DevilsHeart.java @@ -0,0 +1,82 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DevilsHeart extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + + @Override + public String getName() { + return "The Devils Heart"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_CHESTPLATE; + } + + @Override + public String getDisplayName() { + return "&f&l<&c&l❤ &4&lThe Devil's Heart &c&l❤&f&l>"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&cA legendary object of unsurpassed power and mystery.", + "&cAn isolated archaeological outpost has suddenly", + "&cstopped responding to repeated requests for information" + + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("fat"), 6); + //put(enchantRegister.getEnchantmentFromID("mirror"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("draco"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/EternityBoundCrown.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/EternityBoundCrown.java new file mode 100644 index 0000000..c1fd30d --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/EternityBoundCrown.java @@ -0,0 +1,79 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class EternityBoundCrown extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Eternity Bound Crown"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HELMET; + } + + @Override + public String getDisplayName() { + return "&5&kii&r &d&lEternity Bound Crown &5&kii&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&dA headgear bound with ancient magic that", + "&dgrants the wearer eternal life and", + "&dprotection against death." + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + //put(enchantRegister.getEnchantmentFromID("cursedmark"), 6); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("wraith"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/HoodOfDarkSouls.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/HoodOfDarkSouls.java new file mode 100644 index 0000000..386b81f --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/HoodOfDarkSouls.java @@ -0,0 +1,93 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HoodOfDarkSouls extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + + @Override + public String getName() { + return "Hood Of Dark Souls"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HELMET; + } + + @Override + public String getDisplayName() { + return "&f&kii&r &4&l&oHood&r &c&lof &4&l&nDark Souls&r &f&kii&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&4You start to feel dizzy as Dark Souls", + "&4play tricks on your mind...,", + "&4You were told this wouldn't be easy,", + "&4and now you &l&nSUFFER&r &4the consequences." + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("divineenlighted"), 1); + + put(enchantRegister.getEnchantmentFromID("drunk"), 4); + put(enchantRegister.getEnchantmentFromID("deathgod"), 3); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("implants"), 3); + + put(enchantRegister.getEnchantmentFromID("endershift"), 3); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 11; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("reaper"); + //return AdminArmorAPI.getArmorSetFromID("diablo"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/NemesisAndTheFallen.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/NemesisAndTheFallen.java new file mode 100644 index 0000000..1d92c65 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/NemesisAndTheFallen.java @@ -0,0 +1,81 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class NemesisAndTheFallen extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + + @Override + public String getName() { + return "Nemesis And The Fallen"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public String getDisplayName() { + return "&f&kii&r &5&lNemesis &f&land the &d&lFallen &f&kii&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&dYou shall &5dig &dyour own &5grave", + "&dDeath is uncertain, follow those who &5&olurk", + "&dWalk the silent steps,", + "&dand let them see &4&lhell..." + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("abyss"), 4); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("wraith"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/SnowflakeSlippers.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/SnowflakeSlippers.java new file mode 100644 index 0000000..536fdfc --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/SnowflakeSlippers.java @@ -0,0 +1,88 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SnowflakeSlippers extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Snowflake Slippers"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&b❆&f&ki&r &b&lSnowflake Slippers &f&ki&r&b❆&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&bFor someone who thinks they are from a", + "&bmovie, they think they are Elsa..", + "&bIn reality they are not, but just as powerful." + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("springs"), 2); + put(enchantRegister.getEnchantmentFromID("rocketescape"), 3); + put(enchantRegister.getEnchantmentFromID("frozen"), 3); + put(enchantRegister.getEnchantmentFromID("hardened"), 3); + put(enchantRegister.getEnchantmentFromID("stormcaller"), 4); + put(enchantRegister.getEnchantmentFromID("cactus"), 2); + put(enchantRegister.getEnchantmentFromID("voodoo"), 6); + put(enchantRegister.getEnchantmentFromID("wither"), 5); + put(enchantRegister.getEnchantmentFromID("poisoned"), 4); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return false; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + //return AdminArmorAPI.getArmorSetFromID("rover"); + return AdminArmorAPI.getArmorSetFromID("yeti"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/StarForgedChausses.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/StarForgedChausses.java new file mode 100644 index 0000000..28592d3 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/StarForgedChausses.java @@ -0,0 +1,82 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StarForgedChausses extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Star Forged Chausses"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_LEGGINGS; + } + + @Override + public String getDisplayName() { + return "&6&kii&r &e&lStar Forged Chausses &6&kii&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&eLeg armor forged from the hearts of dying stars", + "ðat grant the wearer the power to manipulate", + "&egravity and shoot beams of intense &b&l&nENERGY." + ); + } + + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("lucky"), 10); + put(enchantRegister.getEnchantmentFromID("obsidianshield"), 1); + put(enchantRegister.getEnchantmentFromID("anticactus"), 1); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + //return AdminArmorAPI.getArmorSetFromID("fortune"); + return AdminArmorAPI.getArmorSetFromID("dragon"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/Tarnhelm.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/Tarnhelm.java new file mode 100644 index 0000000..3810558 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/Tarnhelm.java @@ -0,0 +1,79 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Tarnhelm extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Tarnhelm"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HELMET; + } + + @Override + public String getDisplayName() { + return "&b&l~&9&l-== &b&l&oTarn&3&l&ohelm &9&l==-&b&l~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&fA helmet seemingly supplying the wearer", "&fwith somewhat &5magical &fpowers... Equip it!", "&c&oI dare you..."); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("implants"), 3); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("deathgod"), 3); + put(enchantRegister.getEnchantmentFromID("drunk"), 4); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("yijki"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/TasteTheRainbow.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/TasteTheRainbow.java new file mode 100644 index 0000000..c4168c0 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/current/TasteTheRainbow.java @@ -0,0 +1,78 @@ +package net.crankedpvp.adminarmor.adminarmor.current; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TasteTheRainbow extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Taste The Rainbow"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_LEGGINGS; + } + + @Override + public String getDisplayName() { + return "&f&l~-=&4&lT&c&la&6&ls&e<&a&le &2&lThe Ra&b&li&9&ln&1&lb&5&lo&d&lw&f&l=-~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&fYes, it's &c&l&nB&6&l&nR&e&l&nO&a&l&nK&b&l&nE&d&l&nN&5&l&n!&r &fWanna &9CRY?", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("obsidianshield"), 1); + put(enchantRegister.getEnchantmentFromID("divineenlighted"), 1); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("phantom"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/AddictionPants.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/AddictionPants.java new file mode 100644 index 0000000..9d10694 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/AddictionPants.java @@ -0,0 +1,82 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AddictionPants extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Addiction Pants"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_LEGGINGS; + } + + @Override + public String getDisplayName() { + return "&f&l<=&5&l~==&d&l--&f&l-&d&lA&5&ld&d&ld&5&li&d&lc&5<&d&li&5&lo&d&ln &5&lP&d&la&5&ln&d<&5&ls&f&l-&d&l--&5&l==~&f&l=>"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&dAn addicted gambler will only dig", "&dthemselves a deeper grave the more", "&dthat they gamble..."); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("divineenlighted"), 3); + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("anticactus"), 2); + put(enchantRegister.getEnchantmentFromID("voodoo"), 6); + put(enchantRegister.getEnchantmentFromID("obsidianshield"), 1); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 12; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.PROTECTION_FALL, 5); + put(org.bukkit.enchantments.Enchantment.PROTECTION_EXPLOSIONS, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("gambler"); + } +} \ No newline at end of file diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/AgniMani.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/AgniMani.java new file mode 100644 index 0000000..9cca251 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/AgniMani.java @@ -0,0 +1,79 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +public class AgniMani extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + + @Override + public String getName() { + return "Agni Mani"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public String getDisplayName() { + return "&8~&3-=&b=[ &3&lA&b&lg&3&ln&b&li &3&l& &b&lM&f&la&b&ln&f&li &b]=&3=-&8~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&bDo you not hear me CALLING?", "&bI suggest you answer me, now.", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("springs"), 2); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("polymorphicmetaphysical"), 1); + put(enchantRegister.getEnchantmentFromID("hardened"), 3); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return false; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("sacred"); + } +} \ No newline at end of file diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/CargoPants.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/CargoPants.java new file mode 100644 index 0000000..6cdfefe --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/CargoPants.java @@ -0,0 +1,79 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CargoPants extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Cargo Pants"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_LEGGINGS; + } + + @Override + public String getDisplayName() { + return "&2&l~==&a&l--&f&l-&2&lCargo &a&lPants&f&l-&a&l--&2&l==~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&aAlthough they seem innocent, what secret", "&apower may these leggings hold?", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("divineenlighted"), 1); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("cactus"), 2); + put(enchantRegister.getEnchantmentFromID("voodoo"), 6); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("agares"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/CloakOfInvisibility.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/CloakOfInvisibility.java new file mode 100644 index 0000000..67856ab --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/CloakOfInvisibility.java @@ -0,0 +1,79 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CloakOfInvisibility extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Cloak Of Invisibility"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_CHESTPLATE; + } + + @Override + public String getDisplayName() { + return "&4&l~-&7&l&o==&4&lCloak of &8&l&mInvisibility&7&l&o==&4&l-~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&7&oI &c&osolemnly &7&oswear that I am &c&o&mup to no good.", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("deathbringer"), 3); + put(enchantRegister.getEnchantmentFromID("overload"), 3); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("leadership"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return false; + } + + @Override + public int getArmorOrbLevel() { + return 11; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("nightmare"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/Jester.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/Jester.java new file mode 100644 index 0000000..132cd13 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/Jester.java @@ -0,0 +1,74 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Jester extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Jester"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HELMET; + } + + @Override + public String getDisplayName() { + return "&8~=&6=-&e- &6&lJ&e&le&6&ls&e<&6&le&e&lr &6&l666 &e-&6-=&8=~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&6The juggernaut has not shown all", "&6of it's immersive power yet...", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 6); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("juggernaut"); + } +} \ No newline at end of file diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/MarkOfDeath.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/MarkOfDeath.java new file mode 100644 index 0000000..882cc26 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/MarkOfDeath.java @@ -0,0 +1,75 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MarkOfDeath extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Mark Of Death"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HELMET; + } + + @Override + public String getDisplayName() { + return "&f&l<&8~=&c=-&4- &4&l&oMark of &nDEATH&r &4-&c-=&8=~&f&l>"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&4Embrace the power.. suffer" , "&4the consequences...", "&4I behold the power of evil."); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("planetarydeathbringer"), 3); + put(enchantRegister.getEnchantmentFromID("divineenlighted"), 3); + put(enchantRegister.getEnchantmentFromID("godlyoverload"), 1); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 12; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("lucifer"); + } +} \ No newline at end of file diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/MrCrux.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/MrCrux.java new file mode 100644 index 0000000..1915143 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/MrCrux.java @@ -0,0 +1,79 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MrCrux extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Mr Crux"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_LEGGINGS; + } + + @Override + public String getDisplayName() { + return "&3~=-&b-[ &b&lMr. &3&lCrux &b]-&3-=~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&3It is YOUR time...", "&3Don't get upset over Mr Crux :)", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("soulhardened"), 1); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("cactus"), 2); + put(enchantRegister.getEnchantmentFromID("voodoo"), 6); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("assassin"); + } +} \ No newline at end of file diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/ReaperWings.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/ReaperWings.java new file mode 100644 index 0000000..b9b2b54 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/ReaperWings.java @@ -0,0 +1,81 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ReaperWings extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Reaper Wings"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_CHESTPLATE; + } + + @Override + public String getDisplayName() { + return "&4✦&c==- &4&lReaper's Wings &c-==&4✦"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&4Do you dare to &nchallenge&r &4me", + "&4above the safety of the ground?", + ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("planetarydeathbringer"), 1); + put(enchantRegister.getEnchantmentFromID("overload"), 3); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("leadership"), 5); + put(enchantRegister.getEnchantmentFromID("wither"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("reaper"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/RocketBoots.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/RocketBoots.java new file mode 100644 index 0000000..76731c7 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/RocketBoots.java @@ -0,0 +1,80 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RocketBoots extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Rocket Boots"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public String getDisplayName() { + return "&5&l~=-&d&l- &5&lRocket &d&lBoots -&5&l=~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&5The only way is up...", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("gears"), 3); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("metaphysical"), 4); + put(enchantRegister.getEnchantmentFromID("etherealdodge"), 1); + put(enchantRegister.getEnchantmentFromID("hardened"), 3); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return false; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("spectre"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TasteTheRainbow.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TasteTheRainbow.java new file mode 100644 index 0000000..743f2d9 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TasteTheRainbow.java @@ -0,0 +1,78 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TasteTheRainbow extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Taste The Rainbow"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HELMET; + } + + @Override + public String getDisplayName() { + return "&f&l~-=&4&lT&c&la&6&ls&e<&a&le &2&lThe Ra&b&li&9&ln&1&lb&5&lo&d&lw&f&l=-~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&fYes, it's &c&l&nB&6&l&nR&e&l&nO&a&l&nK&b&l&nE&d&l&nN&5&l&n!&r &fWanna &9CRY?", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("implants"), 3); + put(enchantRegister.getEnchantmentFromID("divineenlighted"), 1); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("lucid"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TiaraOfBliss.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TiaraOfBliss.java new file mode 100644 index 0000000..40abc18 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TiaraOfBliss.java @@ -0,0 +1,77 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TiaraOfBliss extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Tiara of Bliss"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HELMET; + } + + @Override + public String getDisplayName() { + return "&f&l~&e&l==&6&l-[ &e&lTiara &f&lof &e&lBliss &6&l]-&e&l==&f&l~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&7&oShe &e&oshines &7&oin the &b&osky &7&olike no other.", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("enlighted"), 3); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("tank"), 4); + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + }}; + } + + @Override + public boolean isWhitescrolled() { + return false; + } + + @Override + public boolean isHolyWhitescrolled() { + return false; + } + + @Override + public int getArmorOrbLevel() { + return 0; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("spirit"); + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TuxedoClad.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TuxedoClad.java new file mode 100644 index 0000000..a36000f --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/adminarmor/old/TuxedoClad.java @@ -0,0 +1,76 @@ +package net.crankedpvp.adminarmor.adminarmor.old; + +import net.crankedpvp.adminarmor.AdminArmorAPI; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.adminarmor.struct.CustomEnchantments; +import net.crankedpvp.adminarmor.struct.VanillaEnchantments; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TuxedoClad extends AdminArmor implements CustomEnchantments, VanillaEnchantments { + @Override + public String getName() { + return "Tuxedo Clad"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_CHESTPLATE; + } + + @Override + public String getDisplayName() { + return "&8~=&c=-&4- &c&lTuxedo Clad &4-&c-=&8=~"; + } + + @Override + public List getLore() { + return Arrays.asList("", "&cKnowledge is stronger than memory.." , "&cand we should not trust the weaker...", ""); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("valor"), 5); + put(enchantRegister.getEnchantmentFromID("angelic"), 5); + put(enchantRegister.getEnchantmentFromID("armored"), 4); + put(enchantRegister.getEnchantmentFromID("tank"), 4); + }}; + } + + @Override + public boolean isWhitescrolled() { + return true; + } + + @Override + public boolean isHolyWhitescrolled() { + return true; + } + + @Override + public int getArmorOrbLevel() { + return 10; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return AdminArmorAPI.getArmorSetFromID("draco"); + } +} \ No newline at end of file diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/commands/AdminArmorCommand.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/commands/AdminArmorCommand.java new file mode 100644 index 0000000..a9372ed --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/commands/AdminArmorCommand.java @@ -0,0 +1,40 @@ +package net.crankedpvp.adminarmor.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.adminarmor.AdminArmorPlugin; +import net.crankedpvp.adminarmor.inventory.AdminArmorInventory; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("adminarmor") +@Alias({"aarmor", "cam"}) +public class AdminArmorCommand extends CommandBase { + + private final AdminArmorPlugin plugin; + public AdminArmorCommand(AdminArmorPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getAdminArmorInventory().getUI().open(player); + } + + @SubCommand("give") + @Permission("cranked.admin") + public void giveCommand(final CommandSender commandSender, @Completion("#adminarmor") final String adminArmorString, @Optional @Completion("#players")Player player) { + if(player == null) { + if(!(commandSender instanceof Player)) return; + player = (Player) commandSender; + } + + AdminArmor adminArmor = this.plugin.getAdminArmorRegister().getAdminArmorFromID(adminArmorString); + PlayerUtils.giveOrDropProtectedItem(player, adminArmor.buildItem(), 5); + player.sendMessage(CC.translate("&aYou have received the " + adminArmor.getDisplayName() + "&r &aadmin armor")); + + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/inventory/AdminArmorInventory.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/inventory/AdminArmorInventory.java new file mode 100644 index 0000000..6552384 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/inventory/AdminArmorInventory.java @@ -0,0 +1,59 @@ +package net.crankedpvp.adminarmor.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.adminarmor.AdminArmorPlugin; +import net.crankedpvp.adminarmor.struct.AdminArmor; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Collection; + +public class AdminArmorInventory { + private final Gui adminArmorInventory; + + public Gui getUI() { + return this.adminArmorInventory; + } + + Collection adminArmor = AdminArmorPlugin.getInstance().getAdminArmorRegister().getAdminArmor(); + + public AdminArmorInventory() { + this.adminArmorInventory = new Gui(6, "Cranked Admin Armor"); + this.adminArmorInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.adminArmorInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.adminArmorInventory.updateItem(6, 5, new GuiItem(createExitItem(), event -> event.getWhoClicked().closeInventory())); + this.adminArmorInventory.updateItem(1, 5, new GuiItem(createInformationItem())); + + for(AdminArmor adminArmor : this.adminArmor) { + this.adminArmorInventory.addItem(new GuiItem(adminArmor.buildItem(), event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) event.getWhoClicked().getInventory().addItem(event.getCurrentItem()); + })); + } + } + + private ItemStack createExitItem() { + ItemStack item = new ItemStack(Material.BED); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cExit Admin Armor menu")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createInformationItem() { + return new ItemBuilder(Material.BOOK, "&a&lCranked Admin Armor", "") + .colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(""); + item.setItemMeta(meta); + return item; + } +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/AdminArmor.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/AdminArmor.java new file mode 100644 index 0000000..d927f35 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/AdminArmor.java @@ -0,0 +1,68 @@ +package net.crankedpvp.adminarmor.struct; + +import lombok.Getter; +import net.crankedpvp.adminarmor.AdminArmorPlugin; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.holywhitescrolls.HolyWhitescrollAPI; +import org.bukkit.Material; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Locale; + +public abstract class AdminArmor implements Listener { + + + @Getter + private final DamageHandler damageHandler; + @Getter + private final AdminArmorPlugin adminArmorPlugin; + + public AdminArmor() { + this.damageHandler = CrankedUtils.instance.getDamageHandler(); + this.adminArmorPlugin = AdminArmorPlugin.getInstance(); + } + + public abstract String getName(); + public abstract Material getMaterial(); + public abstract String getDisplayName(); + public abstract List getLore(); + + public String getID() { return this.getName().toLowerCase(Locale.ROOT).replace(" ", ""); } + + public ItemStack buildItem() { + ItemBuilder itemBuilder = new ItemBuilder(getMaterial(), getDisplayName()); + ItemStack itemStack = itemBuilder.colorize().build(); + if(this instanceof CustomEnchantments) + if(((CustomEnchantments)this).getArmorSet() != null) + itemStack = ((CustomEnchantments)this).getArmorSet().applyData(itemStack); + ItemBuilder newItemBuilder = new ItemBuilder(itemStack); + newItemBuilder.addLore(getLore()); + ItemStack newItemStack = newItemBuilder.colorize().build(); + if(this instanceof VanillaEnchantments) newItemStack.addUnsafeEnchantments(((VanillaEnchantments) this).getVanillaEnchantments()); + if(this instanceof CustomEnchantments) newItemStack = this.addCustomEnchantments(newItemStack); + return newItemStack; + } + + private ItemStack addCustomEnchantments(ItemStack itemStack) { + CustomEnchantments customEnchantments = (CustomEnchantments)this; + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + enchantedItemBuilder.addEnchantments(((CustomEnchantments) this).getCustomEnchantments()); + enchantedItemBuilder.sortEnchantLore().addEnchantAmountToName(); + + if(customEnchantments.getArmorOrbLevel() > 9) { + enchantedItemBuilder.setSlots(customEnchantments.getArmorOrbLevel()); + enchantedItemBuilder.updateSlotsLore(customEnchantments.getArmorOrbLevel()); + } + if(customEnchantments.isWhitescrolled()) enchantedItemBuilder.setProtected(true); + ItemStack finalItemStack = enchantedItemBuilder.build(); + if(customEnchantments.isHolyWhitescrolled()) return HolyWhitescrollAPI.addHolyWhitescrollToItem(finalItemStack); + return finalItemStack; + } + + +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/AdminArmorRegister.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/AdminArmorRegister.java new file mode 100644 index 0000000..fbafc53 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/AdminArmorRegister.java @@ -0,0 +1,115 @@ +package net.crankedpvp.adminarmor.struct; + +import com.google.common.collect.Maps; +import lombok.Getter; +import net.crankedpvp.adminarmor.AdminArmorPlugin; +import net.crankedpvp.adminarmor.adminarmor.cosmic.CosmicTasteTheRainbow; +import net.crankedpvp.adminarmor.adminarmor.current.*; +import net.crankedpvp.adminarmor.adminarmor.old.CloakOfInvisibility; +import net.crankedpvp.adminarmor.adminarmor.old.MrCrux; +import net.crankedpvp.adminarmor.adminarmor.old.ReaperWings; +import net.crankedpvp.adminarmor.adminarmor.old.TuxedoClad; +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; + +import java.util.Collection; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; + +public class AdminArmorRegister { + + private AdminArmorPlugin plugin; + private Map adminArmor; + @Getter + private Map cachedPlayers; + public AdminArmorRegister(AdminArmorPlugin plugin) { + this.plugin = plugin; + this.adminArmor = Maps.newConcurrentMap(); + this.cachedPlayers = Maps.newConcurrentMap(); + } + + public void initialize() { + this.registerAll( + new CosmicTasteTheRainbow() + ); + /* + this.registerAll(new TasteTheRainbow(), new Tarnhelm(), new TuxedoClad(), new ReaperWings(), new MrCrux(), new CloakOfInvisibility()); + this.registerAll(new AbyssWalkingSabatons(), new CaptainsDreadHelm(), new DevilsHeart(), new EternityBoundCrown(), new HoodOfDarkSouls(), + new NemesisAndTheFallen(), new StarForgedChausses(), new SnowflakeSlippers(), new BuffedBard()); + /* + old cranked + this.registerAll( + new AddictionPants(), + new AgniMani(), + new CargoPants(), + new CloakOfInvisibility(), + new Jester(), + new MarkOfDeath(), + new MrCrux(), + new ReaperWings(), + new RocketBoots(), + new TasteTheRainbow(), + new TiaraOfBliss(), + new TuxedoClad() + ); + + */ + } + + public void registerAll(AdminArmor... adminArmors) { + for (AdminArmor adminArmor : adminArmors) { + this.register(adminArmor); + } + } + + public void register(AdminArmor adminArmor) { + try { + this.adminArmor.put(adminArmor.getID(), adminArmor); + this.plugin.getServer().getPluginManager().registerEvents(adminArmor, this.plugin); + this.plugin.getLogger().info("Successfully registered admin armor: " + adminArmor.getID()); + } catch (Exception e) { + this.plugin.getLogger().warning("Failed to register admin armor: " + adminArmor.getID()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.adminArmor.clear(); + } + + public void unregister(AdminArmor adminArmor) { + this.adminArmor.remove(adminArmor.getID()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isAdminArmor(String name) { + return (this.getAdminArmorFromID(name) != null); + } + + public AdminArmor getAdminArmorFromID(String id) { + Validate.notNull(id); + Validate.notEmpty(id); + return this.adminArmor.get(id.toLowerCase()); + } + + public AdminArmor getAdminArmorFromName(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + name = this.getAdminArmorIDFromName(name); + return this.adminArmor.get(name.toLowerCase()); + } + + public String getAdminArmorIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getAdminArmor() { + return Collections.unmodifiableCollection(this.adminArmor.values()); + } + +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/CustomEnchantments.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/CustomEnchantments.java new file mode 100644 index 0000000..1fcbac8 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/CustomEnchantments.java @@ -0,0 +1,14 @@ +package net.crankedpvp.adminarmor.struct; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; + +import java.util.Map; + +public interface CustomEnchantments { + Map getCustomEnchantments(); + boolean isWhitescrolled(); + boolean isHolyWhitescrolled(); + int getArmorOrbLevel(); + ArmorSet getArmorSet(); +} diff --git a/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/VanillaEnchantments.java b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/VanillaEnchantments.java new file mode 100644 index 0000000..31eb0d1 --- /dev/null +++ b/AdminArmor/src/main/java/net/crankedpvp/adminarmor/struct/VanillaEnchantments.java @@ -0,0 +1,9 @@ +package net.crankedpvp.adminarmor.struct; + +import org.bukkit.enchantments.Enchantment; + +import java.util.Map; + +public interface VanillaEnchantments { + Map getVanillaEnchantments(); +} diff --git a/AdminArmor/src/main/resources/plugin.yml b/AdminArmor/src/main/resources/plugin.yml new file mode 100644 index 0000000..df0f29a --- /dev/null +++ b/AdminArmor/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedAdminArmor +main: net.crankedpvp.adminarmor.AdminArmorPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedArmor \ No newline at end of file diff --git a/AdminItems/pom.xml b/AdminItems/pom.xml new file mode 100644 index 0000000..46914ee --- /dev/null +++ b/AdminItems/pom.xml @@ -0,0 +1,30 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + AdminItems + + + 8 + 8 + + + + + + net.crankedpvp + Utils + + + com.massivecraft + Factions + + + \ No newline at end of file diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/AdminItemsPlugin.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/AdminItemsPlugin.java new file mode 100644 index 0000000..0789b58 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/AdminItemsPlugin.java @@ -0,0 +1,71 @@ +package net.crankedpvp.adminitems; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; + +import net.crankedpvp.adminitems.commands.AdminItemCommand; +import net.crankedpvp.adminitems.language.LanguageHandler; + +import net.crankedpvp.adminitems.managers.AdminItemAbilityManager; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.adminitems.struct.AdminItemRegister; +import net.crankedpvp.adminitems.struct.config.AdminItemConfigManager; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.stream.Collectors; + +@Getter +public class AdminItemsPlugin extends JavaPlugin { + + @Getter + public static AdminItemsPlugin instance; + public LanguageHandler languageHandler; + private AdminItemRegister adminItemRegister; + private CommandManager commandManager; + private AdminItemConfigManager petConfigManager; + private AdminItemAbilityManager abilityManager; + + @Override + public void onEnable() { + instance = this; + + this.abilityManager = new AdminItemAbilityManager(); + + + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + + this.adminItemRegister = new AdminItemRegister(); + this.adminItemRegister.initialize(); + + this.petConfigManager = new AdminItemConfigManager(this); + this.petConfigManager.setupFiles(); + + this.commandManager = new CommandManager(this); + this.registerCommandParameters(); + this.registerCommandCompletion(); + this.commandManager.register(new AdminItemCommand(this)); + + + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(AdminItem.class, argument -> { + AdminItem pet = this.adminItemRegister.getAdminItemFromID(this.adminItemRegister.getAdminItemIDFromName(String.valueOf(argument))); + return new TypeResult(pet, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#adminItems", input -> { + return this.adminItemRegister.getAdminItems().stream().map(AdminItem::getID).collect(Collectors.toList()); + }); + } + + @Override + public void onDisable() { + instance = null; + } +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/CrankedAdminItemsAPI.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/CrankedAdminItemsAPI.java new file mode 100644 index 0000000..9589a06 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/CrankedAdminItemsAPI.java @@ -0,0 +1,88 @@ +package net.crankedpvp.adminitems; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.adminitems.language.Language; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.adminitems.struct.AdminItemRegister; +import net.crankedpvp.adminitems.struct.Throwable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class CrankedAdminItemsAPI { + + public static boolean isAdminItem(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + + if (!nbtItem.hasKey("cosmicType")) return false; + return nbtItem.getString("cosmicType").equals("adminItem"); + } + + public static AdminItem getAdminItemFromItem(ItemStack itemStack) { + NBTItem nbtItem = new NBTItem(itemStack); + + NBTCompound compound = nbtItem.getCompound("cosmicData"); + String adminItemType = compound.getString("adminItemType"); + + return AdminItemRegister.getInstance().getAdminItemFromID(adminItemType); + } + + public static int getUsesFromFromItem(ItemStack itemStack) { + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound compound = nbtItem.getCompound("cosmicData"); + return compound.getInteger("adminItemUses"); + } + + + + public static boolean canUseAdminItem(Player player, ItemStack itemStack, String cooldownID, AdminItem adminItem) { + if (!CrankedAdminItemsAPI.getAdminItemFromItem(itemStack).getID().equals(adminItem.getID())) { + return false; + } + if (itemStack.getAmount() > 1) { + Language.USE_STACKED_ADMIN_ITEM.send(player); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 10f, 1.1f); + if (adminItem instanceof Throwable) { + int amount = itemStack.getAmount(); + int uses = CrankedAdminItemsAPI.getUsesFromFromItem(itemStack); + + ItemStack item = adminItem.getItem(uses).clone(); + item.setAmount(amount); + player.setItemInHand(item); + } + return false; + } + if (CooldownUtils.isCooldownActive(player, cooldownID)) { + player.sendMessage(CC.translate(Language.ADMIN_ITEM_ABILITY_COOLDOWN.getMessage().replace("%time%", CooldownUtils.getFormattedCooldown(player, cooldownID)))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 10f, 1.1f); + if (adminItem instanceof Throwable) { + int uses = CrankedAdminItemsAPI.getUsesFromFromItem(itemStack); + player.setItemInHand(adminItem.getItem(uses)); + } + return false; + } + + + return true; + } + + + public static void decreaseUses(Player player, AdminItem adminItem) { + int uses = CrankedAdminItemsAPI.getUsesFromFromItem(player.getItemInHand()); + if (uses != -1) { + if (uses - 1 == 0) { + player.setItemInHand(null); + } else { + player.setItemInHand(adminItem.getItem(uses-1)); + } + } + + } + +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/commands/AdminItemCommand.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/commands/AdminItemCommand.java new file mode 100644 index 0000000..bbc4707 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/commands/AdminItemCommand.java @@ -0,0 +1,63 @@ +package net.crankedpvp.adminitems.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; + +import net.crankedpvp.adminitems.AdminItemsPlugin; +import net.crankedpvp.adminitems.language.Language; +import net.crankedpvp.adminitems.language.LanguageHandler; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.adminitems.struct.config.AdminItemConfigManager; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("cai") +public class AdminItemCommand extends CommandBase { + + private final LanguageHandler languageHandler; + private final AdminItemConfigManager adminItemConfigManager; + + public AdminItemCommand(AdminItemsPlugin plugin) { + this.languageHandler = plugin.getLanguageHandler(); + this.adminItemConfigManager = plugin.getPetConfigManager(); + } + + @Default + @Permission("cranked.admin") + public void mainCommand(CommandSender sender) { + Language.ADMIN_COMMAND_HELP.send(sender); + } + + @SubCommand("item") + @WrongUsage("&cUsage: /cp item [player]") + @Permission("cranked.admin") + public void itemCommand(CommandSender sender, @Completion("#adminItems") AdminItem adminItem, Integer uses ,@Completion("#players") @Optional Player player) { + if (adminItem == null) { + Language.INVALID_ADMIN_ITEM.send(sender); + return; + } + + if (player != null) { + player.getInventory().addItem(adminItem.getItem(uses)); + return; + } + + if (sender instanceof Player) { + ((Player) sender).getInventory().addItem(adminItem.getItem(uses)); + } + } + + @SubCommand("reload") + @WrongUsage("&cUsage: /cai reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + this.languageHandler.load(); + this.adminItemConfigManager.reloadFiles(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } +} \ No newline at end of file diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/cooldowns/AbilityCooldown.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/cooldowns/AbilityCooldown.java new file mode 100644 index 0000000..9fbd1d1 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/cooldowns/AbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.adminitems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class AbilityCooldown extends CurrentCooldown { + public AbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/events/AdminItemUseEvent.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/events/AdminItemUseEvent.java new file mode 100644 index 0000000..6bd0b6a --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/events/AdminItemUseEvent.java @@ -0,0 +1,31 @@ +package net.crankedpvp.adminitems.events; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.crankedutils.events.ArmorEquipEvent; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerInteractEvent; + +@Getter +public class AdminItemUseEvent extends Event implements Cancellable { + + @Setter + private boolean cancelled; + private final Player player; + private final AdminItem adminItem; + private final PlayerInteractEvent playerInteractEvent; + private final HandlerList handlers; + + public AdminItemUseEvent(Player player, AdminItem adminItem, PlayerInteractEvent event) { + this.player = player; + this.adminItem = adminItem; + this.playerInteractEvent = event; + this.cancelled = false; + this.handlers = new HandlerList(); + } + +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/items/GrappleHook.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/items/GrappleHook.java new file mode 100644 index 0000000..e336a1e --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/items/GrappleHook.java @@ -0,0 +1,157 @@ +package net.crankedpvp.adminitems.items; + +import net.crankedpvp.adminitems.CrankedAdminItemsAPI; +import net.crankedpvp.adminitems.cooldowns.AbilityCooldown; +import net.crankedpvp.adminitems.language.Language; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.adminitems.struct.Interactable; +import net.crankedpvp.adminitems.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.ProjectileLaunchEvent; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class GrappleHook extends AdminItem implements Interactable { + + @ConfigValue() + private int cooldown = 10; + + private final HashMap grapple = new HashMap<>(); + + + @Override + public String getName() { + return "GrappleHook"; + } + + @Override + public String getDisplayName() { + return "&b&lGrapple Hook"; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&7Grapple yourself across the world", + "&7and pull other enemies towards you.", + "&7There is a " + cooldown + " seconds cooldown", + "&7between every grapple use." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oEscape from all your problems with", + "&7&othe grappler hook. Escape from reality.", + "&7&oand start a new adventure on cranked." + ); + } + + + @Override + public ChatColor getColor() { + return ChatColor.AQUA; + } + + @Override + public Material getMaterial() { + return Material.FISHING_ROD; + } + + @Override + public String getCooldownID() { + return "grappleHook"; + } + + @EventHandler + public void onGrappleLaunch(ProjectileLaunchEvent e) { + if (!(e.getEntity().getShooter() instanceof Player)) { + return; + } + final Player shooter = (Player) e.getEntity().getShooter(); + if (!CrankedAdminItemsAPI.isAdminItem(shooter.getItemInHand())) { + return; + } + if (CrankedAdminItemsAPI.getAdminItemFromItem(shooter.getItemInHand()) != this) { + return; + } + if(shooter.getWorld().getName().equals("world_nether")) { + e.setCancelled(true); + Language.GRAPPLED_CANNOT_USE_IN_WORLD.send(shooter); + return; + } + this.grapple.put(shooter, e.getEntity().getVelocity()); + } + + @EventHandler + public void onPlayerFish(PlayerFishEvent e) { + final ItemStack item = e.getPlayer().getItemInHand(); + if (!CrankedAdminItemsAPI.isAdminItem(item)) return; + + if (!CrankedAdminItemsAPI.canUseAdminItem(e.getPlayer(), item, getCooldownID(), this)) { + return; + } + + if(e.getPlayer().getWorld().getName().equals("world_nether")) { + e.setCancelled(true); + Language.GRAPPLED_CANNOT_USE_IN_WORLD.send(e.getPlayer()); + return; + } + + if (e.getState() == PlayerFishEvent.State.FISHING) return; + final Player p = e.getPlayer(); + if (!this.grapple.containsKey(p)) { + return; + } + + if (e.getCaught() instanceof Player) { + final Location loc = e.getCaught().getLocation(); + final Location hookLoc = p.getLocation(); + final double dis = loc.distance(hookLoc); + Vector direction = e.getCaught().getLocation().toVector().subtract(p.getLocation().toVector()).normalize(); + final double Y = (1.0 + 0.12 * dis) * (hookLoc.getY() - loc.getY()) / dis - -0.04 * dis; + direction.setY(Y); + direction.setX(direction.getX() * -1 * (0.11 * dis)); + direction.setZ(direction.getZ() * -1 * (0.11 * dis)); + e.getCaught().setVelocity(direction); + p.sendMessage(CC.translate(Language.GRAPPLED_ENEMY.getMessage()).replace("%enemy%", e.getCaught().getName())); + e.getCaught().sendMessage(CC.translate(Language.GRAPPLED_BY_PLAYER.getMessage()).replace("%player%", p.getName())); + + } else { + final double distance = p.getLocation().distance(e.getHook().getLocation()); + final Location loc = p.getLocation(); + final Location hookLoc = e.getHook().getLocation(); + final double dis = loc.distance(hookLoc); + final double X = (1.0 + 0.24 * dis) * (hookLoc.getX() - loc.getX()) / dis; + final double Y = (1.0 + 0.12 * dis) * (hookLoc.getY() - loc.getY()) / dis - -0.04 * dis; + final double Z = (1.0 + 0.24 * dis) * (hookLoc.getZ() - loc.getZ()) / dis; + final Vector v = p.getVelocity(); + v.setX(X); + v.setY(Y); + v.setZ(Z); + p.setVelocity(v); + p.setVelocity(this.grapple.get(p).multiply(distance * 0.3).setY((distance * 0.1 > 1.0) ? 1.0 : ((p.getLocation().getPitch() < -70.0f) ? 1.25 : ((p.getLocation().getPitch() < -50.0f) ? 1.125 : 1.0)))); + Language.GRAPPLED.send(p); + } + this.grapple.remove(p); + item.setDurability((short) 0); + p.setItemInHand(item); + CrankedAdminItemsAPI.decreaseUses(p, this); + CooldownUtils.registerCooldown(p, new AbilityCooldown(getCooldownID(), cooldown)); + } + +} + + diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/items/SwitcherBall.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/items/SwitcherBall.java new file mode 100644 index 0000000..4a230db --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/items/SwitcherBall.java @@ -0,0 +1,158 @@ +package net.crankedpvp.adminitems.items; + +import net.crankedpvp.adminitems.AdminItemsPlugin; +import net.crankedpvp.adminitems.CrankedAdminItemsAPI; +import net.crankedpvp.adminitems.cooldowns.AbilityCooldown; +import net.crankedpvp.adminitems.language.Language; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.adminitems.struct.Throwable; +import net.crankedpvp.adminitems.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.apache.commons.codec.language.bm.Lang; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +import java.util.*; +import java.util.concurrent.*; + +import org.bukkit.inventory.*; +import org.bukkit.event.*; +import org.bukkit.event.entity.*; +import org.bukkit.entity.*; +import org.bukkit.*; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class SwitcherBall extends AdminItem implements Throwable { + + @ConfigValue() + private int cooldown = 60; + + private Map snowballPlayers = new HashMap<>(); + + + @Override + public String getName() { + return "SwitcherBall"; + } + + @Override + public String getDisplayName() { + return "&d&lSwitcher Ball"; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&7Upon hit, your location will be switched", + "&7with the person you hit with the ball.", + "&7There is a 60 seconds cooldown", + "&7between every switcher ball use." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oEver wanted to know how it is", + "&7&oto step in someone else's shoes?" + ); + } + + + @Override + public ChatColor getColor() { + return ChatColor.LIGHT_PURPLE; + } + + @Override + public Material getMaterial() { + return Material.SNOW_BALL; + } + + @Override + public String getCooldownID() { + return "switcherBall"; + } + + + @EventHandler + public void onPlayerLaunchEgg(ProjectileLaunchEvent e) { + if (!(e.getEntity() instanceof Snowball)) { + return; + } + if (!(e.getEntity().getShooter() instanceof Player)) { + return; + } + final Player shooter = (Player) e.getEntity().getShooter(); + if (!CrankedAdminItemsAPI.isAdminItem(shooter.getItemInHand())) { + return; + } + + if (!CrankedAdminItemsAPI.canUseAdminItem(shooter, shooter.getItemInHand(), getCooldownID(), this)) { + return; + } + + this.snowballPlayers.put(e.getEntity().getUniqueId(), ((Player) e.getEntity().getShooter()).getPlayer()); + } + + + @EventHandler + public void onPlayerHitBySnowball(EntityDamageByEntityEvent e) { + if (!(e.getEntity() instanceof Player)) { + return; + } + if (!(e.getDamager() instanceof Snowball)) { + return; + } + final Player hit = (Player) e.getEntity(); + final Entity damager = e.getDamager(); + final Snowball snowball = (Snowball) damager; + if (!(snowball.getShooter() instanceof Player)) { + return; + } + final Player shooter = (Player) snowball.getShooter(); + if (!this.snowballPlayers.containsKey(snowball.getUniqueId())) { + return; + } + + if (this.snowballPlayers.get(snowball.getUniqueId()) != shooter) { + return; + } + + if (!WorldGuardUtils.canPvPInRegion(shooter.getLocation()) || !WorldGuardUtils.canPvPInRegion(hit.getLocation())) return; + + + this.snowballPlayers.remove(snowball.getUniqueId()); + final Location loc = shooter.getLocation(); + shooter.teleport(hit); + hit.teleport(loc); + shooter.sendMessage(CC.translate(Language.SWITCHERED.getMessage().replace("%shot%", hit.getName()))); + hit.sendMessage(CC.translate(Language.SWITCHERED_BY_PLAYER.getMessage().replace("%player%", shooter.getName()))); + CooldownUtils.registerCooldown(shooter, new AbilityCooldown(getCooldownID(), cooldown)); + + } + + @EventHandler + public void onHit(ProjectileHitEvent event) { + if (event.getEntity() instanceof Snowball) { + if (snowballPlayers.containsKey(event.getEntity().getUniqueId())) { + Player shooter = snowballPlayers.get(event.getEntity().getUniqueId()); + Language.SWITCHER_HIT_NONE.send(shooter); + //shooter.setItemInHand(AdminItemsPlugin.getInstance().getAdminItemRegister().getAdminItemFromID("SwitcherBall").getItem(1)); + snowballPlayers.remove(event.getEntity().getUniqueId()); + } + } + + + } + + +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/items/TimeTraveler.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/items/TimeTraveler.java new file mode 100644 index 0000000..1097881 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/items/TimeTraveler.java @@ -0,0 +1,135 @@ +package net.crankedpvp.adminitems.items; + +import com.gmail.filoghost.holographicdisplays.api.Hologram; +import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import net.crankedpvp.adminitems.AdminItemsPlugin; +import net.crankedpvp.adminitems.CrankedAdminItemsAPI; +import net.crankedpvp.adminitems.cooldowns.AbilityCooldown; +import net.crankedpvp.adminitems.language.Language; +import net.crankedpvp.adminitems.managers.AdminItemAbilityManager; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.adminitems.struct.Interactable; +import net.crankedpvp.adminitems.struct.annotations.ConfigValue; +import net.crankedpvp.adminitems.tasks.TimeTravelerTask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.Arrays; +import java.util.List; + +public class TimeTraveler extends AdminItem implements Interactable { + + private AdminItemAbilityManager abilityManager = AdminItemsPlugin.getInstance().getAbilityManager(); + + @ConfigValue() + private int time = 30; + + @ConfigValue() + private int cooldown = 120; + + + @Override + public String getName() { + return "TimeTraveler"; + } + + @Override + public String getDisplayName() { + return "&5&lTime Traveler"; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&7Upon use, your current location will be", + "&7saved and after &f" + time + "&7 seconds you will", + "&7be teleported back to that location." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oMany people claim they have seen the", + "&7&othe past but never seen the future.", + "&7&oTime Travelers are everywhere and nowhere." + ); + } + + + + @Override + public ChatColor getColor() { + return ChatColor.DARK_PURPLE; + } + + @Override + public Material getMaterial() { + return Material.WATCH; + } + + @Override + public String getCooldownID() { + return "timeTraveler"; + } + + + @EventHandler + public void onPlayerInteractWithAdminItem(PlayerInteractEvent event) { + if (!CrankedAdminItemsAPI.isAdminItem(event.getItem())) return; + + if (!CrankedAdminItemsAPI.canUseAdminItem(event.getPlayer(), event.getItem(), getCooldownID(), this)) { + return; + } + + procOnClickAbility(event.getPlayer()); + + } + + + public void procOnClickAbility(Player player) { + + final Location spawnLocation = player.getEyeLocation(); + CooldownUtils.registerCooldown(player, new AbilityCooldown(getCooldownID(), cooldown)); + Hologram hologram = HologramsAPI.createHologram(AdminItemsPlugin.getInstance(), spawnLocation.clone()); + hologram.appendTextLine(CC.translate("&d&l✰ &5&lTime Travelling &d&l✰")); + hologram.appendTextLine(CC.translate("&d&l * &fTime: &d" + 0 + "s &fleft")); + hologram.appendTextLine(CC.translate("&d&l * &fTraveler: &d" + player.getName())); + player.sendMessage(CC.translate(Language.TIME_TRAVEL_USED.getMessage().replace("%time%", String.valueOf(time)))); + CrankedAdminItemsAPI.decreaseUses(player, this); + + TimeTravelerTask timeTravelerTask = new TimeTravelerTask(this.time, hologram, player, spawnLocation); + timeTravelerTask.runTaskTimer(AdminItemsPlugin.getInstance(), 0L, 20L); + + abilityManager.getTimeTravellers().put(player.getUniqueId(), timeTravelerTask); + + + } + + @EventHandler + public void onDeath(PlayerDeathEvent event) { + if (abilityManager.getTimeTravellers().containsKey(event.getEntity().getUniqueId())) { + TimeTravelerTask timeTravelerTask = (TimeTravelerTask) abilityManager.getTimeTravellers().get(event.getEntity().getUniqueId()); + Language.TIME_TRAVEL_DIED.send(event.getEntity()); + timeTravelerTask.getHologram().delete(); + timeTravelerTask.cancel(); + abilityManager.getTimeTravellers().remove(event.getEntity().getUniqueId()); + } + } + + @EventHandler + public void onTeleportBeforeTimeTraveler(PlayerTeleportEvent event) { + if (event.getPlayer() == null) return; + if (event.getCause() == null) return; + if (event.getCause() == PlayerTeleportEvent.TeleportCause.ENDER_PEARL) return; + if (!this.abilityManager.getTimeTravellers().containsKey(event.getPlayer().getUniqueId())) return; + this.abilityManager.getTimeTravellers().remove(event.getPlayer().getUniqueId()); + Language.TIME_TRAVEL_CANCELED_BECAUSE_TELEPORT.send(event.getPlayer()); + } +} \ No newline at end of file diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/items/TrapBlocker.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/items/TrapBlocker.java new file mode 100644 index 0000000..96c34b2 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/items/TrapBlocker.java @@ -0,0 +1,188 @@ +package net.crankedpvp.adminitems.items; + +import net.crankedpvp.adminitems.AdminItemsPlugin; +import net.crankedpvp.adminitems.CrankedAdminItemsAPI; +import net.crankedpvp.adminitems.cooldowns.AbilityCooldown; +import net.crankedpvp.adminitems.language.Language; +import net.crankedpvp.adminitems.managers.AdminItemAbilityManager; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.adminitems.struct.Interactable; +import net.crankedpvp.adminitems.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.util.*; + +public class TrapBlocker extends AdminItem implements Interactable { + + private final AdminItemAbilityManager abilityManager = AdminItemsPlugin.getInstance().getAbilityManager(); + + + @ConfigValue() + private int radius = 16; + + @ConfigValue() + private int time = 10; + + @ConfigValue() + private int cooldown = 60; + + + @Override + public String getName() { + return "TrapBlocker"; + } + + @Override + public String getDisplayName() { + return "&c&lTrap Blocker"; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&7Upon use, people in a &f" + radius + "x" + radius + "&7 radius", + "&7will no longer be able to:", + "&7open doors, place or break blocks", + "&7for a duration of &f" + time + "&7 seconds." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oThose who have been trapped", + "&7&oin life know how it is to escape", + "&7&ofrom it's darkest dreams." + ); + } + + + @Override + public ChatColor getColor() { + return ChatColor.RED; + } + + @Override + public Material getMaterial() { + return Material.STICK; + } + + @Override + public String getCooldownID() { + return "trapBlocker"; + } + + public void procOnClickAbility(Player player) { + List nearbyPlayers = PVPUtils.getNearbyEnemyPlayersExceptPlayer(player, radius); + List trapBlockedPossibleList = new ArrayList<>(); + for (Player enemy : nearbyPlayers) { + final UUID uuid = enemy.getUniqueId(); + if (CooldownUtils.isCooldownActive(enemy, getCooldownID())) { + String cd = CooldownUtils.getFormattedCooldown(enemy, getCooldownID()); + String msg = Language.TRAP_BLOCKER_ENEMY_ON_COOLDOWN.getMessage().replace("%time%", cd); + msg = msg.replace("%enemy%", enemy.getName()); + player.sendMessage(CC.translate(msg)); + } else { + trapBlockedPossibleList.add(uuid); + } + } + if (trapBlockedPossibleList.isEmpty()) { + int uses = CrankedAdminItemsAPI.getUsesFromFromItem(player.getItemInHand()); + player.setItemInHand(super.getItem(uses)); + Language.TRAP_BLOCKER_NO_NEARBY.send(player); + return; + } + + StringBuilder listFormatted = new StringBuilder(new StringBuilder()); + for (UUID uuid : trapBlockedPossibleList) { + Player enemy = Bukkit.getPlayer(uuid); + if (enemy == null) continue; + abilityManager.trapBlock(uuid); + Bukkit.getScheduler().runTaskLaterAsynchronously(AdminItemsPlugin.getInstance(), ()-> { + Language.TRAP_BLOCKER_ENDED.send(Bukkit.getPlayer(uuid)); + abilityManager.getTrapBlockered().remove(uuid); + }, time* 20L); + CooldownUtils.registerCooldown(enemy, new AbilityCooldown(getCooldownID(), cooldown)); + String msg = Language.TRAP_BLOCKED_BY.getMessage().replace("%time%", Integer.toString(this.time)); + msg = msg.replace("%enemy%", player.getName()); + enemy.sendMessage(CC.translate(msg)); + listFormatted.append(enemy.getName()).append(", "); + listFormatted = new StringBuilder(listFormatted.substring(0, listFormatted.length() - 2)); + + } + + String msgPlayer = Language.TRAP_BLOCKED.getMessage().replace("%blockedList%", listFormatted.toString()); + msgPlayer = msgPlayer.replace("%amount%", Integer.toString(trapBlockedPossibleList.size())); + player.sendMessage(CC.translate(msgPlayer)); + CrankedAdminItemsAPI.decreaseUses(player, this); + + } + + @EventHandler + public void onPlayerInteractWithAdminItem(PlayerInteractEvent event) { + if (!CrankedAdminItemsAPI.isAdminItem(event.getItem())) return; + if (!CrankedAdminItemsAPI.canUseAdminItem(event.getPlayer(), event.getItem(), getCooldownID(), this)) { + return; + } + procOnClickAbility(event.getPlayer()); + } + + @EventHandler + public void onBuild(BlockPlaceEvent event) { + if (abilityManager.isTrapBlockered(event.getPlayer().getUniqueId())) { + Language.TRAP_BLOCKER_CANNOT_INTERACT.send(event.getPlayer()); + event.setCancelled(true); + } + } + + @EventHandler + public void onLogout(PlayerQuitEvent event) { + if (abilityManager.isTrapBlockered(event.getPlayer().getUniqueId())) { + abilityManager.getTrapBlockered().remove(event.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void onKick(PlayerKickEvent event) { + if (abilityManager.isTrapBlockered(event.getPlayer().getUniqueId())) { + abilityManager.getTrapBlockered().remove(event.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void onDeath(PlayerDeathEvent event) { + if (abilityManager.isTrapBlockered(event.getEntity().getUniqueId())) { + abilityManager.getTrapBlockered().remove(event.getEntity().getUniqueId()); + } + } + + @EventHandler + public void onBreak(BlockBreakEvent event) { + if (abilityManager.isTrapBlockered(event.getPlayer().getUniqueId())) { + Language.TRAP_BLOCKER_CANNOT_INTERACT.send(event.getPlayer()); + + event.setCancelled(true); + } + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if (event.getClickedBlock() == null) return; + if (!event.getClickedBlock().getType().name().endsWith("_DOOR")) return; + if (abilityManager.isTrapBlockered(event.getPlayer().getUniqueId())) { + Language.TRAP_BLOCKER_CANNOT_INTERACT.send(event.getPlayer()); + event.setCancelled(true); + } + } +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/language/Language.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/language/Language.java new file mode 100644 index 0000000..1202036 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/language/Language.java @@ -0,0 +1,118 @@ +package net.crankedpvp.adminitems.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + ADMIN_COMMAND_HELP, + INVALID_ADMIN_ITEM, + ADMIN_RELOADING, + USE_STACKED_ADMIN_ITEM, + TRAP_BLOCKER_CANNOT_INTERACT, + TRAP_BLOCKER_ENEMY_ON_COOLDOWN, + TRAP_BLOCKED_BY, + TRAP_BLOCKED, + TRAP_BLOCKER_NO_NEARBY, + TRAP_BLOCKER_ENDED, + TIME_TRAVEL_DIED, + TIME_TRAVEL_TIME, + TIME_TRAVEL_USED, + TIME_TRAVEL_ENDED, + TIME_TRAVEL_CANCELED_BECAUSE_TELEPORT, + GRAPPLED, + GRAPPLED_BY_PLAYER, + GRAPPLED_ENEMY, + GRAPPLED_CANNOT_USE_IN_WORLD, + SWITCHERED, + SWITCHER_HIT_NONE, + SWITCHERED_BY_PLAYER, + ADMIN_ITEM_ABILITY_COOLDOWN, + ADMIN_RELOADED, + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return value != null ? value : this.name(); + } + + public String getValue(UnaryOperator function) { + return value != null ? function.apply(value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(getValue(function)); + } + +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/language/LanguageHandler.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/language/LanguageHandler.java new file mode 100644 index 0000000..9f54a82 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.adminitems.language; + +import net.crankedpvp.adminitems.AdminItemsPlugin; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final AdminItemsPlugin plugin; + + public LanguageHandler(AdminItemsPlugin plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/managers/AdminItemAbilityManager.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/managers/AdminItemAbilityManager.java new file mode 100644 index 0000000..4ae40ff --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/managers/AdminItemAbilityManager.java @@ -0,0 +1,27 @@ +package net.crankedpvp.adminitems.managers; + +import lombok.Getter; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.*; + +@Getter +public class AdminItemAbilityManager { + private List trapBlockered; + private Map timeTravellers; + public AdminItemAbilityManager() { + this.trapBlockered = new ArrayList<>(); + this.timeTravellers = new HashMap<>(); + } + + + + public boolean isTrapBlockered(UUID uuid) { + return trapBlockered.contains(uuid); + } + + public boolean trapBlock(UUID uuid) { + return trapBlockered.add(uuid); + } + +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/AdminItem.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/AdminItem.java new file mode 100644 index 0000000..cbb576e --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/AdminItem.java @@ -0,0 +1,57 @@ +package net.crankedpvp.adminitems.struct; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Locale; + +public abstract class AdminItem implements Listener { + + public abstract String getName(); + + public abstract String getDisplayName(); + + public abstract List getPerks(); + + public abstract List getLore(); + + public abstract ChatColor getColor(); + + public abstract Material getMaterial(); + + public abstract String getCooldownID(); + + + public String getID() { + return this.getName().toLowerCase(Locale.ROOT).replace(" ", ""); + } + + public ItemStack getItem(int uses) { + ItemStack item = new ItemBuilder(getMaterial()).setName(this.getDisplayName()) + .addLore(this.getLore()) + .addLore("") + .addLore(this.getColor() + "&l" + "Ability") + .addLore(this.getPerks()) + .addLore("") + .addLore(this.getColor() + "&l" + "Uses") + .addLore("&f" +(uses == -1? "Unlimited": Integer.toString(uses))) + .colorize() + .setGlowing() + .build(); + NBTItem wrapper = new NBTItem(item); + wrapper.setString("cosmicType", "adminItem"); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + cosmicData.setString("adminItemType", this.getID()); + cosmicData.setInteger("adminItemUses", uses); + return wrapper.getItem(); + } +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/AdminItemRegister.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/AdminItemRegister.java new file mode 100644 index 0000000..6671d6a --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/AdminItemRegister.java @@ -0,0 +1,89 @@ +package net.crankedpvp.adminitems.struct; + +import lombok.Getter; +import net.crankedpvp.adminitems.AdminItemsPlugin; +import net.crankedpvp.adminitems.items.GrappleHook; +import net.crankedpvp.adminitems.items.SwitcherBall; +import net.crankedpvp.adminitems.items.TimeTraveler; +import net.crankedpvp.adminitems.items.TrapBlocker; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; + +import java.util.*; + +public class AdminItemRegister { + + @Getter + private static AdminItemRegister instance; + private final Map adminItems; + + + public AdminItemRegister() { + instance = this; + this.adminItems = new HashMap<>(); + } + + public void initialize() { + this.registerAll( + new TrapBlocker(), + new TimeTraveler(), + new GrappleHook(), + new SwitcherBall() + ); + } + + public void registerAll(AdminItem... Adminitems) { + for (AdminItem adminItem : Adminitems) { + this.register(adminItem); + } + } + + public void register(AdminItem adminItem) { + try { + this.adminItems.put(adminItem.getID(), adminItem); + AdminItemsPlugin.getInstance().getServer().getPluginManager().registerEvents(adminItem, AdminItemsPlugin.getInstance()); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register admin item " + adminItem.getID()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.adminItems.clear(); + } + + public void unregister(AdminItem adminItem) { + this.adminItems.remove(adminItem.getID()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isAdminItem(String name) { + return (this.getAdminItemFromID(name) != null); + } + + public AdminItem getAdminItemFromID(String id) { + Validate.notNull(id); + Validate.notEmpty(id); + return this.adminItems.get(id.toLowerCase()); + } + + public AdminItem getAdminItemFromName(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + name = this.getAdminItemIDFromName(name); + return this.adminItems.get(name.toLowerCase()); + } + + public String getAdminItemIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getAdminItems() { + return Collections.unmodifiableCollection(this.adminItems.values()); + } + +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/Interactable.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/Interactable.java new file mode 100644 index 0000000..3871d68 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/Interactable.java @@ -0,0 +1,4 @@ +package net.crankedpvp.adminitems.struct; + +public interface Interactable { +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/Throwable.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/Throwable.java new file mode 100644 index 0000000..43f2100 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/Throwable.java @@ -0,0 +1,5 @@ +package net.crankedpvp.adminitems.struct; + +public interface Throwable { + +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/annotations/ConfigValue.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/annotations/ConfigValue.java new file mode 100644 index 0000000..e647e69 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/annotations/ConfigValue.java @@ -0,0 +1,19 @@ +package net.crankedpvp.adminitems.struct.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * don't forget to not make the field final when using this annotation + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigValue { + + String path() default "adminitem."; + String name() default ""; + +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/config/AdminItemConfig.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/config/AdminItemConfig.java new file mode 100644 index 0000000..ef55809 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/config/AdminItemConfig.java @@ -0,0 +1,119 @@ +package net.crankedpvp.adminitems.struct.config; + +import lombok.AccessLevel; +import lombok.Getter; + +import net.crankedpvp.adminitems.AdminItemsPlugin; +import net.crankedpvp.adminitems.struct.AdminItem; +import net.crankedpvp.adminitems.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; + +@Getter +public class AdminItemConfig { + + @Getter(value = AccessLevel.PRIVATE) + private final AdminItemsPlugin plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + private final AdminItem adminItem; + + public AdminItemConfig(AdminItemsPlugin plugin, String path, AdminItem adminItem) { + this.plugin = plugin; + this.path = path; + this.adminItem = adminItem; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public void setupConfigFile() { + this.createDefaultFile(); + this.config = YamlConfiguration.loadConfiguration(configFile); + + this.loadVariables(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path); + e.printStackTrace(); + } + return false; + } + + public void createDefaultFile() { + if (!configFile.exists()) { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path); + e.printStackTrace(); + } + } + } + + public void reloadConfig() { + config = YamlConfiguration.loadConfiguration(configFile); + this.loadVariables(); + } + + public void loadConfigFromDisk() { + try { + config.load(configFile); + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path); + e.printStackTrace(); + } + } + + public void loadVariables() { + boolean needSave = false; + for (Field field : this.adminItem.getClass().getDeclaredFields()) { + + try { + field.setAccessible(true); + + if (field.isAnnotationPresent(ConfigValue.class)) { + ConfigValue annotationValue = field.getAnnotation(ConfigValue.class); + + String name = annotationValue.name().equals("") ? field.getName() : annotationValue.name(); + + String path = annotationValue.path().endsWith(".") ? annotationValue.path() : annotationValue.path() + "."; + + if (!this.config.contains(path + name)) { + this.config.set(path + name, field.get(this.adminItem)); + needSave = true; + continue; + } + + Object fieldValue = this.config.get(path + name); + + if (fieldValue instanceof String) fieldValue = CC.translate((String) fieldValue); + + field.set(this.adminItem, fieldValue); + } + } catch (IllegalAccessException | NullPointerException | IllegalArgumentException e) { + Bukkit.getConsoleSender().sendMessage(CC.translate("&c[CrankedAdminItems] - Error invalid config value for adminItem " + adminItem.getName())); + } + } + if (needSave) { + saveConfig(); + reloadConfig(); + } + } +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/config/AdminItemConfigManager.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/config/AdminItemConfigManager.java new file mode 100644 index 0000000..2115e9c --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/struct/config/AdminItemConfigManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.adminitems.struct.config; + +import lombok.Getter; +import net.crankedpvp.adminitems.AdminItemsPlugin; +import net.crankedpvp.adminitems.struct.AdminItem; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class AdminItemConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public AdminItemConfigManager(AdminItemsPlugin plugin) { + for (AdminItem adminItem : plugin.getAdminItemRegister().getAdminItems()) { + AdminItemConfig adminItemConfig = new AdminItemConfig(plugin, "adminitems/" + adminItem.getID() + ".yml", adminItem); + configs.put(adminItem, adminItemConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AdminItemConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AdminItemConfig::reloadConfig); + } + + public AdminItemConfig getAbstractConfig(AdminItem pet) { + return configs.get(pet); + } + + public FileConfiguration getConfig(AdminItem pet) { + return getAbstractConfig(pet).getConfig(); + } +} diff --git a/AdminItems/src/main/java/net/crankedpvp/adminitems/tasks/TimeTravelerTask.java b/AdminItems/src/main/java/net/crankedpvp/adminitems/tasks/TimeTravelerTask.java new file mode 100644 index 0000000..b1b02b7 --- /dev/null +++ b/AdminItems/src/main/java/net/crankedpvp/adminitems/tasks/TimeTravelerTask.java @@ -0,0 +1,87 @@ +package net.crankedpvp.adminitems.tasks; + +import com.gmail.filoghost.holographicdisplays.api.Hologram; +import com.gmail.filoghost.holographicdisplays.api.line.TextLine; +import lombok.Getter; +import net.crankedpvp.adminitems.AdminItemsPlugin; +import net.crankedpvp.adminitems.language.Language; +import net.crankedpvp.adminitems.managers.AdminItemAbilityManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.ChunkUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; + +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.scheduler.BukkitRunnable; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +@Getter +public class TimeTravelerTask extends BukkitRunnable { + private AdminItemAbilityManager abilityManager = AdminItemsPlugin.getInstance().getAbilityManager(); + private int duration; + private Hologram hologram; + private Player player; + private Location spawnLocation; + private ParticleBuilder particle; + + public TimeTravelerTask(int duration, Hologram hologram, Player player, Location spawnLocation) { + this.duration = duration; + this.hologram = hologram; + this.player = player; + this.spawnLocation = spawnLocation; + this.particle = new ParticleBuilder(ParticleEffect.PORTAL, player.getLocation()) + .setAmount(200) + .setOffsetY(1.5f) + .setOffsetX(1.5f) + .setOffsetZ(1.5f) + .setSpeed(0.05f); + } + + @Override + public void run() { + if (player == null) { + hologram.delete(); + abilityManager.getTimeTravellers().remove(player.getUniqueId()); + this.cancel(); + return; + } + + if (!player.isOnline()) { + hologram.delete(); + abilityManager.getTimeTravellers().remove(player.getUniqueId()); + this.cancel(); + return; + } + + if (spawnLocation.getWorld() != player.getWorld()) { + hologram.delete(); + abilityManager.getTimeTravellers().remove(player.getUniqueId()); + this.cancel(); + return; + } + + if (duration == 0) { + Language.TIME_TRAVEL_ENDED.send(player); + player.teleport(spawnLocation, PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.playSound(player.getLocation(), Sound.PORTAL_TRIGGER, 10f, 1.4f); + hologram.delete(); + abilityManager.getTimeTravellers().remove(player.getUniqueId()); + this.cancel(); + return; + } + + updateHologram(CC.translate("&d&l * &fTime: &d" + duration + "s &7left")); + this.particle.setLocation(player.getLocation()).display(PVPUtils.getNearbyPlayers(player, 30)); + player.sendMessage(CC.translate(Language.TIME_TRAVEL_TIME.getMessage().replace("%time%", String.valueOf(duration)))); + duration--; + + } + + private void updateHologram(String newText) { + final TextLine textLine = (TextLine)this.hologram.getLine(1); + textLine.setText(newText); + } +} \ No newline at end of file diff --git a/AdminItems/src/main/resources/language.yml b/AdminItems/src/main/resources/language.yml new file mode 100644 index 0000000..513f708 --- /dev/null +++ b/AdminItems/src/main/resources/language.yml @@ -0,0 +1,35 @@ +INVALID_ADMIN_ITEM: "&c&l(!)&c Invalid admin item name." +USE_STACKED_ADMIN_ITEM: "&3&lAdmin Items &8➥ &7You cannot use stacked admin items." +ADMIN_COMMAND_HELP: + - "&8--- &3Cranked &fAdminItems &8---" + - "&3/cai &fitem &7 [player]" + + +ADMIN_RELOADING: "&3&l(!) &7Reloading configs now..." +ADMIN_RELOADED: "&3&l(!) &7Reloaded configs and other cool stuff. Took &3%took%ms&7." + +ADMIN_ITEM_ABILITY_COOLDOWN: "&3&lAdmin Items &8➥ &7You cannot use this ability for another &f%time&7." + +TRAP_BLOCKER_CANNOT_INTERACT: "&c&lTRAP BLOCKER:&c You cannot do this while being trap blocked!" +TRAP_BLOCKER_ENEMY_ON_COOLDOWN: "&c&lTRAP BLOCKER:&c %enemy% is still on trap blocker cooldown for %time%!" +TRAP_BLOCKED_BY: "&c&lTRAP BLOCKER:&c You have been trap blocked by &7%enemy%&c for &7%time%&c. &cWhile trap blocked you can no longer build, break blocks or open doors." +TRAP_BLOCKED: "&c&lTRAP BLOCKER:&c You have trap blocked &7%amount% &cenemies: &7%blockedList%&c." +TRAP_BLOCKER_NO_NEARBY: "&c&lTRAP BLOCKER:&c No valid targets have been found!" +TRAP_BLOCKER_ENDED: "&c&lTRAP BLOCKER:&c You are no longer trap blocked!" + +TIME_TRAVEL_DIED: "&5&lTIME TRAVELER:&5 Since you died you will no longer be teleported to your previous location." +TIME_TRAVEL_TIME: "&5&lTIME TRAVELER:&5 You will teleported back to your previous location in &7%time% seconds&5." +TIME_TRAVEL_USED: "&5&lTIME TRAVELER:&5 You have used a time traveler, you will be teleported back in &7%time% seconds&5." +TIME_TRAVEL_ENDED: "&5&lTIME TRAVELER:&5 You have been teleported back to your previous location!" +TIME_TRAVEL_CANCELED_BECAUSE_TELEPORT: "&5&lTIME TRAVELER:&5 Your time traveler was canceled!" + +GRAPPLED_ENEMY: "&b&lGRAPPLING HOOK:&b You have grappled &7%enemy% &btowards you!" +GRAPPLED_BY_PLAYER: "&b&lGRAPPLING HOOK:&b You have been grappled towards %player%&b!" +GRAPPLED: "&b&lGRAPPLING HOOK: &bYou have grappled away!" +GRAPPLED_CANNOT_USE_IN_WORLD: "&b&lGRAPPLING HOOK: &bYou cannot use grappling hooks in this world" + +SWITCHERED: "&d&lSWITCHER BALL: &dYou have switched positions with &7%shot%!" +SWITCHERED_BY_PLAYER: "&d&lSWITCHER BALL: &dYou have been hit with a switcher ball by &7%player%&d!" +SWITCHER_HIT_NONE: "&d&lSWITCHER BALL: &dYou didn't hit a player while using the switcher ball!" + + diff --git a/AdminItems/src/main/resources/plugin.yml b/AdminItems/src/main/resources/plugin.yml new file mode 100644 index 0000000..71c631c --- /dev/null +++ b/AdminItems/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedAdminItems +main: net.crankedpvp.adminitems.AdminItemsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/AdminWeapons/pom.xml b/AdminWeapons/pom.xml new file mode 100644 index 0000000..f9d60fd --- /dev/null +++ b/AdminWeapons/pom.xml @@ -0,0 +1,38 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + AdminWeapons + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + Enchants + + + net.crankedpvp + HolyWhitescrolls + + + net.crankedpvp + Armor + + + + \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/AdminWeaponsAPI.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/AdminWeaponsAPI.java new file mode 100644 index 0000000..a961968 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/AdminWeaponsAPI.java @@ -0,0 +1,45 @@ +package net.crankedpvp.adminweapons; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class AdminWeaponsAPI { + + private static boolean isPlayerHoldingAdminWeapon(Player player) { + ItemStack itemStack = player.getItemInHand(); + if(itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + if(!nbtItem.hasKey("cosmicType")) return false; + NBTCompound nbtCompound = nbtItem.getCompound("cosmicData"); + if(nbtCompound == null) return false; + return nbtCompound.hasKey("adminWeaponType"); + } + + public static AdminWeapon getPlayersHeldAdminWeapon(Player player) { + if(!isPlayerHoldingAdminWeapon(player)) return null; + ItemStack itemStack = player.getItemInHand(); + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound nbtCompound = nbtItem.getCompound("cosmicData"); + if(!AdminWeaponsPlugin.getInstance().getAdminWeaponRegister().isAdminWeapon(nbtCompound.getString("adminWeaponType"))) return null; + return AdminWeaponsPlugin.getInstance().getAdminWeaponRegister().getAdminWeaponFromID(nbtCompound.getString("adminWeaponType")); + } + + public static boolean hasAdminWeaponEquipped(Player player, String adminWeaponString) { + AdminWeapon playersWeapon = getPlayersHeldAdminWeapon(player); + if(playersWeapon == null) return false; + AdminWeapon adminWeapon = AdminWeaponsPlugin.getInstance().getAdminWeaponRegister().getAdminWeaponFromID(adminWeaponString); + if(adminWeapon == null) return false; + return playersWeapon == adminWeapon; + } + + public static ArmorSet getArmorSetFromID(String string) { + return CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID(string); + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/AdminWeaponsPlugin.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/AdminWeaponsPlugin.java new file mode 100644 index 0000000..c23bb10 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/AdminWeaponsPlugin.java @@ -0,0 +1,70 @@ +package net.crankedpvp.adminweapons; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.adminweapons.commands.AdminWeaponsCommand; +import net.crankedpvp.adminweapons.inventory.AdminWeaponsInventory; +import net.crankedpvp.adminweapons.listeners.HookListener; +import net.crankedpvp.adminweapons.listeners.PlayerListener; +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.AdminWeaponRegister; +import net.crankedpvp.adminweapons.struct.config.AdminWeaponsConfigManager; +import net.crankedpvp.adminweapons.struct.config.ConfigManager; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Arrays; +import java.util.stream.Collectors; + +public class AdminWeaponsPlugin extends JavaPlugin { + + @Getter + private static AdminWeaponsPlugin instance; + @Getter + private AdminWeaponRegister adminWeaponRegister; + @Getter + private CommandManager commandManager; + @Getter + private AdminWeaponsConfigManager adminWeaponsConfigManager; + @Getter + private ConfigManager configManager; + + @Getter + private AdminWeaponsInventory adminWeaponsInventory; + + @Override + public void onEnable() { + instance = this; + this.adminWeaponRegister = new AdminWeaponRegister(this); + this.adminWeaponRegister.initialize(); + + this.configManager = new ConfigManager(this); + this.configManager.setupFiles(); + + this.adminWeaponsConfigManager = new AdminWeaponsConfigManager(this); + this.adminWeaponsConfigManager.setupFiles(); + + this.commandManager = new CommandManager(this); + this.registerCommandCompletion(); + this.commandManager.register(new AdminWeaponsCommand(this)); + this.registerListeners(this.getServer().getPluginManager()); + + this.adminWeaponsInventory = new AdminWeaponsInventory(); + } + + @Override + public void onDisable() { + + } + + private void registerListeners(PluginManager pluginManager) { + pluginManager.registerEvents(new PlayerListener(this), this); + pluginManager.registerEvents(new HookListener(this), this); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#adminweapons", input -> this.adminWeaponRegister.getAdminWeapons().stream().map(AdminWeapon::getID).collect(Collectors.toList())); + this.commandManager.getCompletionHandler().register("#boolean", input -> Arrays.asList("true", "false")); + } + +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/DivineAxeRhitta.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/DivineAxeRhitta.java new file mode 100644 index 0000000..d8efdf5 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/DivineAxeRhitta.java @@ -0,0 +1,77 @@ +package net.crankedpvp.adminweapons.adminweapons.cadia.axes; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.*; + +public class DivineAxeRhitta extends AdminWeapon implements IArmorSet, ICustomEnchantments, ICustomItems, IVanillaEnchantments { + @Override + public String getName() { + return "Divine Axe Rhitta"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&c&ki&r&6&l&n\\DivineAxe&e&l&nRhitta/&r&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&6A giant ornamental axe with a blade", + "&6shaped like a crescent moon. Known as", + "&6a &e&l&nSacred Treasure&r &6that was in the", + "&6possession of the &e&l&nLion's Sin of Pride&r&6!" + ); + } + + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("inferno"); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("lockdown"), 5); + put(enchantRegister.getEnchantmentFromID("soultrap"), 3); + put(enchantRegister.getEnchantmentFromID("divineimmolation"), 4); + put(enchantRegister.getEnchantmentFromID("silence"), 4); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 0; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/HellRaiser.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/HellRaiser.java new file mode 100644 index 0000000..338997c --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/HellRaiser.java @@ -0,0 +1,85 @@ +package net.crankedpvp.adminweapons.adminweapons.cadia.axes; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.*; + +public class HellRaiser extends AdminWeapon implements IArmorSet, ICustomEnchantments, ICustomItems, IVanillaEnchantments { + @Override + public String getName() { + return "Hell Raiser"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&f&ki&c&l&nHELL&r&f&l☢&4&l&nRAISER&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&cThose who wield this &4&l&nDEMONIC&r &caxe that", + "&cwas once help by the &4&l&nKING&r &cof hell,", + "&cbecome powered with &4&l&nFURY&r&c!" + ); + } + + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("koth"); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("internal"), 6); + put(enchantRegister.getEnchantmentFromID("enrage"), 5); + put(enchantRegister.getEnchantmentFromID("enforcer"), 5); + + + put(enchantRegister.getEnchantmentFromID("crushing"), 5); + put(enchantRegister.getEnchantmentFromID("execute"), 5); + put(enchantRegister.getEnchantmentFromID("insanity"), 8); + put(enchantRegister.getEnchantmentFromID("rage"), 6); + put(enchantRegister.getEnchantmentFromID("silence"), 4); + + put(enchantRegister.getEnchantmentFromID("dualwield"), 3); + put(enchantRegister.getEnchantmentFromID("eradicate"), 3); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/Leviathan.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/Leviathan.java new file mode 100644 index 0000000..0b0e260 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/Leviathan.java @@ -0,0 +1,88 @@ +package net.crankedpvp.adminweapons.adminweapons.cadia.axes; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Leviathan extends AdminWeapon implements IArmorSet, ICustomEnchantments, ICustomItems, IVanillaEnchantments { + @Override + public String getName() { + return "Leviathan"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&3&l&nL&b&l&ne&3&l&nv&b&l&ni&3&l&na&b&l&nt&3&l&nh&b&l&na&3&l&nn&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&bThe two-handed war axe used by &9&l&nGODS&r", + "&bof &9&l&nWAR&r &bruling all warriors!" + ); + } + + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("leviathan"); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("internal"), 6); + + put(enchantRegister.getEnchantmentFromID("crushing"), 5); + put(enchantRegister.getEnchantmentFromID("execute"), 5); + put(enchantRegister.getEnchantmentFromID("insanity"), 8); + put(enchantRegister.getEnchantmentFromID("rage"), 6); + put(enchantRegister.getEnchantmentFromID("silence"), 4); + + put(enchantRegister.getEnchantmentFromID("dualwield"), 3); + put(enchantRegister.getEnchantmentFromID("eradicate"), 3); + put(enchantRegister.getEnchantmentFromID("petrify"), 6); + put(enchantRegister.getEnchantmentFromID("purge"), 6); + + put(enchantRegister.getEnchantmentFromID("deathcurse"), 4); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(Enchantment.DAMAGE_ALL, 6); + put(Enchantment.DURABILITY, 10); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 11; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/PeaceKeeper.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/PeaceKeeper.java new file mode 100644 index 0000000..c8bf538 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/axes/PeaceKeeper.java @@ -0,0 +1,85 @@ +package net.crankedpvp.adminweapons.adminweapons.cadia.axes; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.*; + +public class PeaceKeeper extends AdminWeapon implements IArmorSet, ICustomEnchantments, ICustomItems, IVanillaEnchantments { + @Override + public String getName() { + return "Peace Keeper"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&f&ki&d&l&nPEACE&r&f&l☯&5&l&nKEEPER&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&dThe duty of the wielder of this axe is", + "&dto maintain &5&l&nPEACE&r &dand &5&l&nBALANCE&r &dall", + "&dacross the seas!" + ); + } + + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("orc"); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("internal"), 6); + + put(enchantRegister.getEnchantmentFromID("crushing"), 5); + put(enchantRegister.getEnchantmentFromID("execute"), 5); + put(enchantRegister.getEnchantmentFromID("rage"), 6); + put(enchantRegister.getEnchantmentFromID("silence"), 4); + put(enchantRegister.getEnchantmentFromID("lifesteal"), 5); + + put(enchantRegister.getEnchantmentFromID("dualwield"), 3); + put(enchantRegister.getEnchantmentFromID("eradicate"), 3); + put(enchantRegister.getEnchantmentFromID("doublestrike"), 3); + + put(enchantRegister.getEnchantmentFromID("bleed"), 7); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/Ace.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/Ace.java new file mode 100644 index 0000000..052e6ea --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/Ace.java @@ -0,0 +1,87 @@ +package net.crankedpvp.adminweapons.adminweapons.cadia.swords; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Ace extends AdminWeapon implements IArmorSet, IVanillaEnchantments, ICustomEnchantments, ICustomItems { + @Override + public String getName() { + return "Ace"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&l~&b&lAce&f&l~"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&bA mythic &f&l&nROVER &bblade that uses the power", + "&bof dark lightning energy in bursts that is", + "&bthat is feared by the most &f&l&nDEADLIEST &bof pirates!" + ); + } + + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("rover"); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("divineimmolation"), 4); + put(enchantRegister.getEnchantmentFromID("lockdown"), 4); + + put(enchantRegister.getEnchantmentFromID("crushing"), 5); + put(enchantRegister.getEnchantmentFromID("execute"), 5); + put(enchantRegister.getEnchantmentFromID("lifesteal"), 6); + put(enchantRegister.getEnchantmentFromID("rage"), 6); + put(enchantRegister.getEnchantmentFromID("silence"), 4); + + put(enchantRegister.getEnchantmentFromID("doublestrike"), 3); + put(enchantRegister.getEnchantmentFromID("eradicate"), 3); + put(enchantRegister.getEnchantmentFromID("purge"), 6); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/Amnesia.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/Amnesia.java new file mode 100644 index 0000000..a2a924a --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/Amnesia.java @@ -0,0 +1,89 @@ +package net.crankedpvp.adminweapons.adminweapons.cadia.swords; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Amnesia extends AdminWeapon implements IArmorSet, ICustomEnchantments, ICustomItems, IVanillaEnchantments { + @Override + public String getName() { + return "Amnesia"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&3&l≈&9&lAmnesia&3&l≈"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&fA sword that has the ability to &9&l&nMENTALLY", + "&fattack whoever dares to go against it's", + "&9&l&nBRUTAL &fconsequences!" + ); + } + + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("koth"); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("enrage"), 5); + + put(enchantRegister.getEnchantmentFromID("divineimmolation"), 4); + put(enchantRegister.getEnchantmentFromID("soultrap"), 3); + + put(enchantRegister.getEnchantmentFromID("silence"), 4); + put(enchantRegister.getEnchantmentFromID("rage"), 6); + put(enchantRegister.getEnchantmentFromID("execute"), 5); + put(enchantRegister.getEnchantmentFromID("crushing"), 5); + put(enchantRegister.getEnchantmentFromID("insanity"), 8); + + put(enchantRegister.getEnchantmentFromID("doublestrike"), 3); + put(enchantRegister.getEnchantmentFromID("eradicate"), 3); + put(enchantRegister.getEnchantmentFromID("purge"), 4); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/SwordOfTriton.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/SwordOfTriton.java new file mode 100644 index 0000000..8a8a0f4 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/SwordOfTriton.java @@ -0,0 +1,89 @@ +package net.crankedpvp.adminweapons.adminweapons.cadia.swords; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SwordOfTriton extends AdminWeapon implements IArmorSet, ICustomEnchantments, ICustomItems, IVanillaEnchantments { + + @Override + public String getName() { + return "Sword Of Triton"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&b&l\\&nSword of&3&l&n Triton&r&3&l/"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&bA &9&lLEGENDARY &bbroadsword that holds a strengthened", + "&bpower to those that wield it. Widely known to be held", + "&bby pirates such as &8&lBlackbeard &b& &5&lHector Barbossa&b!" + ); + } + + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("pirate"); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("divineimmolation"), 4); + + put(enchantRegister.getEnchantmentFromID("rage"), 6); + put(enchantRegister.getEnchantmentFromID("crushing"), 5); + put(enchantRegister.getEnchantmentFromID("lifesteal"), 5); + put(enchantRegister.getEnchantmentFromID("silence"), 4); + + put(enchantRegister.getEnchantmentFromID("petrify"), 5); + put(enchantRegister.getEnchantmentFromID("purge"), 4); + put(enchantRegister.getEnchantmentFromID("eradicate"), 3); + + put(enchantRegister.getEnchantmentFromID("iceaspect"), 4); + put(enchantRegister.getEnchantmentFromID("deathcurse"), 4); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(Enchantment.DAMAGE_ALL, 5); + put(Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/TotsukaBlade.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/TotsukaBlade.java new file mode 100644 index 0000000..d0006de --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cadia/swords/TotsukaBlade.java @@ -0,0 +1,89 @@ +package net.crankedpvp.adminweapons.adminweapons.cadia.swords; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TotsukaBlade extends AdminWeapon implements IArmorSet, ICustomEnchantments, ICustomItems, IVanillaEnchantments { + + @Override + public String getName() { + return "Totsuka Blade"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&d&l&n\\Totsuka &5&l&nBlade/"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&dFinally unveiled, the &5&l&nSACRED &d&l&nSWORD, &dsaid to", + "&dhave &5&l&nSEALED &dthose who tried to oppose", + "&dit's superior powers of &5&l&nENTRAPMENT!" + ); + } + + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("wraith"); + } + + @Override + public Map getCustomEnchantments() { + EnchantRegister enchantRegister = EnchantRegister.getInstance(); + return new HashMap() {{ + put(enchantRegister.getEnchantmentFromID("halloweenify"), 4); + put(enchantRegister.getEnchantmentFromID("enforcer"), 5); + + put(enchantRegister.getEnchantmentFromID("divineimmolation"), 4); + + put(enchantRegister.getEnchantmentFromID("crushing"), 5); + put(enchantRegister.getEnchantmentFromID("lifesteal"), 5); + put(enchantRegister.getEnchantmentFromID("rage"), 6); + put(enchantRegister.getEnchantmentFromID("silence"), 4); + put(enchantRegister.getEnchantmentFromID("trickshot"), 6); + + put(enchantRegister.getEnchantmentFromID("eradicate"), 3); + put(enchantRegister.getEnchantmentFromID("purge"), 4); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(Enchantment.DAMAGE_ALL, 5); + put(Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cosmic/TimeSplitter.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cosmic/TimeSplitter.java new file mode 100644 index 0000000..aef1922 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/cosmic/TimeSplitter.java @@ -0,0 +1,81 @@ +package net.crankedpvp.adminweapons.adminweapons.cosmic; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import org.bukkit.Color; +import org.bukkit.Material; +import java.util.List; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.enchantments.Enchantment; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class TimeSplitter extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, IArmorSet, IHeroic, Weighable { + + @Override + public String getName() { + return "Time Splitter"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return CC.translate("&5&lTime Splitter"); + } + + @Override + public List getLore() { + return Arrays.asList( + ); + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return false; + } + + @Override + public boolean equipHolyWhiteScroll() { + return false; + } + + @Override + public int equipWeaponOrb() { + return 0; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("traveler"); + } + + @Override + public int getWeight() { + return 1; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/BlackMirror.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/BlackMirror.java new file mode 100644 index 0000000..28de2f6 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/BlackMirror.java @@ -0,0 +1,88 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class BlackMirror extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, IArmorSet, Weighable { + + @Override + public String getName() { + return "Black Mirror"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return CC.translateAlternating("Black Mirror", "&7&l&o", "&8&l&o"); + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&7&oMirror mirror, on the wall..", + "&7&oWho's most likely to &c&odie &7&oin this &8&obrawl&7&o?" + ); + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + put(Enchantment.FIRE_ASPECT, 1); + }}; + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("deepbleed"), 2); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return false; + } + + @Override + public int equipWeaponOrb() { + return 10; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("nightmare"); + } + + @Override + public int getWeight() { + return 14; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Deathraze.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Deathraze.java new file mode 100644 index 0000000..56a154e --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Deathraze.java @@ -0,0 +1,122 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.cooldowns.AbilityCooldown; +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.ICustomItems; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Deathraze extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, Weighable { + + @Override + public String getName() { + return "Death Raze"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&b✦&f&ki&r &b&lD&3&le&b&la&3<&b&lh &3&lR&b&la&3&lz&b&le &f&ki&r&b✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&3Abilities:", + " &f• Deal +10% damage to enemies wielding swords", + " &f• +7.5% Holy white scroll negation", + //" &f• Thunderous Striking Ability", + "", + "&3A weapon of mass destruction", + "&3that razes its opponents to the ground.", + "&3Wield only with &nbravery&r&3." + + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + Player vic = (Player) victim; + this.tryProcAbility(attacker, vic); + if(vic.getItemInHand() == null) return; + if(vic.getItemInHand().getType() == Material.AIR) return; + if(!vic.getItemInHand().getType().name().endsWith("_SWORD")) return; + super.getDamageHandler().increaseDamage(10, event, this.getName() + " Wielding Sword"); + } + } + + private void tryProcAbility(Player attacker, Player victim) { + if(Math.random() > 0.01) return; + if(CooldownUtils.isCooldownActive(attacker, "deathrazelightning")) return; + CooldownUtils.registerCooldown(attacker, new AbilityCooldown("deathrazelightning", 60)); + victim.getWorld().strikeLightning(victim.getLocation()); + victim.damage(1D); + attacker.sendMessage(CC.translate("&b&lD&3&le&b&la&3<&b&lh &3&lR&b&la&3&lz&b&le &8➥ &eThunderous striking emits upon your foes")); + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("antigank"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("devour"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 9); + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("cleave"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("bleed"), 6); + + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return false; + } + + @Override + public int equipWeaponOrb() { + return 10; + } + + @Override + public int getWeight() { + return 5; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Duskbane.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Duskbane.java new file mode 100644 index 0000000..e6e0fb7 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Duskbane.java @@ -0,0 +1,93 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Duskbane extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, IArmorSet, Weighable { + + @Override + public String getName() { + return "Duskbane"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&8&l~&3&l=&f&l- " + CC.translateAlternating("Duskbane", "&3&l&o", "&b&l&o") + " &f&l-&3&l=&8&l~"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&7&oA lethal &3&oassassins blade &7&othat strikes &c&ofear &7&ointo", + "&7&othe hearts of even the most &f&oformidable &7&oadversaries.", + "&7&oThis &c&oenigmatic &7&oweapon ensures a &f&oswift &7&oand &f&osilent", + "&7&odispatch of any target amongst the &4&owarzone&7&o..." + ); + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("shadowassassin"), 1); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("assassin"); + } + + @Override + public int getWeight() { + return 11; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Excalibur.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Excalibur.java new file mode 100644 index 0000000..ac53157 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Excalibur.java @@ -0,0 +1,103 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Excalibur extends AdminWeapon implements IArmorSet, IHook, IHeroic, Weighable, ICustomItems, ICustomEnchantments, IVanillaEnchantments { + + @Override + public String getName() { + return "Excalibur"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HOE; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&4✦&f&ki&r &c&l&oExcalibur &f&ki&r&4✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&cThe legendary sword of &4King Arthur", + "&cIt is attributed with magical powers", + "&cand associated with the rightful", + "&csovereignty of &4Britain." + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("shadowassassin"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("deepbleed"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + put(org.bukkit.enchantments.Enchantment.FIRE_ASPECT, 3); + }}; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("draco"); + } + + @Override + public int getWeight() { + return 30; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 12; + } + +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Hellforge.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Hellforge.java new file mode 100644 index 0000000..e542f31 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Hellforge.java @@ -0,0 +1,79 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Hellforge extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, Weighable { + + @Override + public String getName() { + return "Hellforge"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&4✦&f&ki&r &4&lH&c&lE&4&lL&c&lL&4&lF&c&lO&4&lR&c&lG&4&lE &f&ki&r&4✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&4Abilities:", + " &f• Deal +10% damage while submerged in lava", + " &f• +15% Chance to negate enemy holy white scrolls", + "", + "&4The power of this axe deteriorates all", + "&4of those around it. It's power is immense.", + "&4It cannot, and will not, be stopped." + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + if(attacker.getLocation().getBlock().isLiquid()) + super.getDamageHandler().increaseDamage(10, event, this.getName() + " Lava"); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public int getWeight() { + return 8; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Igniscale.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Igniscale.java new file mode 100644 index 0000000..d21e443 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Igniscale.java @@ -0,0 +1,95 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Igniscale extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, IArmorSet, Weighable { + + @Override + public String getName() { + return "Igniscale"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&8&l~&6&l=&e&l- " + CC.translateAlternating("Igniscale", "&e&l&o", "&6&l&o") + " &e&l-&6&l=&8&l~"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&7&oWhat is more important? &a&omoney&7&o, &d&opower&7&o,", + "&b&oknowledge&7&o, &c&ostrength&7&o, or being by the", + "&7&oside of an actual &e&odragon&7&o..", + "", + "&7&oMaybe you &f&othink &7&othat you are &6&opowerful&7&o.", + "&7&oBut in &f&oreality &7&oyou are just protected...", + "&7&oThe &e&odragon &7&ois by your side, but the &4&odevil &7&ois not." + ); + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("devour"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("bleed"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("cleave"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("dragon"); + } + + @Override + public int getWeight() { + return 10; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Kaladanda.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Kaladanda.java new file mode 100644 index 0000000..96bc714 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Kaladanda.java @@ -0,0 +1,96 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.ICustomItems; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Kaladanda extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, Weighable { + + @Override + public String getName() { + return "Kaladanda"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&c&l&oK&8&l&oa&c&l&ol&8&l&oa&c&l&od&8&l&oa&c&l&on&8&l&od&c&l&oa"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&7&oOnly the &f&ostrongest &7&oplayers wield the", + "&7&ofamous " + CC.translateAlternating("Kaladanda", "&c&o", "&8&o") + " &7&oas it is known as", + "&7&oa rare &c&oritualized &7&oweapon used to take", + "&7&odown &2&omutated &7&obosses and &e&ocorrupt &7&ofactions.", + "" + ); + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + }}; + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("insomnia"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("inversion"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("dominate"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("assassin"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("block"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("poison"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("trap"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 4); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 0; + } + + @Override + public int getWeight() { + return 6; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Kusangi.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Kusangi.java new file mode 100644 index 0000000..a7302d3 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Kusangi.java @@ -0,0 +1,92 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Kusangi extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, IArmorSet, Weighable { + + @Override + public String getName() { + return "Kusangi"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&8&l~&7&l-&8&l== &4&l&oK&7&l&ousang&4&l&oi &8&l==&7&l-&8&l~"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&fThe wrath of the creator", + "&fCold, hidden, dead, barren", + "&fSurely you jest, you careless fool", + "&fIf you think you can better the likes of &4&l&n&oPURE EVIL!&r" + ); + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("assassin"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("trap"), 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return false; + } + + @Override + public int equipWeaponOrb() { + return 10; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("yijki"); + } + + @Override + public int getWeight() { + return 4; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Purifier.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Purifier.java new file mode 100644 index 0000000..efbf692 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Purifier.java @@ -0,0 +1,92 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Purifier extends AdminWeapon implements ICustomEnchantments, IVanillaEnchantments, Weighable { + + @Override + public String getName() { + return "Purifier"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&6✦&f&ki&r &6&lP&e&lU&6&lR&e&lI&6&lF&e&lI&6&lE&e&lR &f&ki&r&6✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&6Abilities:", + " &f• Deal +10% damage to all enemies", + " &f• Deal +5% damage to enemies wielding axes", + //" &f• Infernal Ability", + "", + "&6The return of Tyranny calls for the return of the purifier.", + "&6A blade of anguish and destruction that", + "&6ravages through those who oppress..." + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, this.getName()); + Player victimPlayer = (Player)victim; + ItemStack itemStack = victimPlayer.getItemInHand(); + if(itemStack == null) return; + if(!itemStack.getType().name().endsWith("_AXE")) return; + super.getDamageHandler().increaseDamage(5, event, this.getName() + " Axe"); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("iceaspect"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 7); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + put(org.bukkit.enchantments.Enchantment.FIRE_ASPECT, 3); + }}; + } + + @Override + public int getWeight() { + return 7; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/SavageHook.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/SavageHook.java new file mode 100644 index 0000000..bf96aed --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/SavageHook.java @@ -0,0 +1,102 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SavageHook extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, IArmorSet, IHeroic, IHook, Weighable { + + @Override + public String getName() { + return "SavageHook"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HOE; + } + + @Override + public String getDisplayName() { + return CC.translateAlternating("Savage Hook", "&f&l&o", "&c&l&o"); + } + + @Override + public List getLore() { + return Arrays.asList( + "", + CC.translateAlternating("Only the goat can use this weapon", "&f&o", "&c&o"), + CC.translateAlternating("as it was hand-crafted to be as", "&f&o", "&c&o"), + CC.translateAlternating("powerful as possible, yet only liftable", "&f&o", "&c&o"), + CC.translateAlternating("by savage, just like thors hammer...", "&f&o", "&c&o"), + "" + ); + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 10); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 5); + }}; + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("deepbleed"), 10); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 10); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 10); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 10); + put(EnchantRegister.getInstance().getEnchantmentFromID("devour"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("inversion"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("shadowassassin"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("block"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("dominate"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 5); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 25; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("koth"); + } + + @Override + public int getWeight() { + return 99; + } + +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Shigenjo.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Shigenjo.java new file mode 100644 index 0000000..66387be --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Shigenjo.java @@ -0,0 +1,74 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Shigenjo extends AdminWeapon implements ICustomEnchantments, IVanillaEnchantments, Weighable { + + @Override + public String getName() { + return "Shigenjo"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&b✦&f&ki&r &b&lS&f&lh&b&li&f&lg&b&le&f&ln&b&lj&f&lo &f&ki&r&b✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&bAbilities:", + " &f• Deal +15% damage while behind your enemy", + " &f• +15% Chance to negate enemy holy white scrolls", + "", + "&bA hasty spy once wielded this weapon..", + "&bHe diligently conquered no mans land", + "&bwith his ability to disguise in plain sight" + ); + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("inversion"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("dominate"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 7); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public int getWeight() { + return 9; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Trixary.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Trixary.java new file mode 100644 index 0000000..ecb3ce6 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/current/Trixary.java @@ -0,0 +1,95 @@ +package net.crankedpvp.adminweapons.adminweapons.current; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Trixary extends AdminWeapon implements ICustomEnchantments, IVanillaEnchantments, Weighable { + + @Override + public String getName() { + return "Trixary"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&d✦&f&ki&r &5&lT&d&lr&5&li&d&lx&5&la&d&lr&5&ly &f&ki&r&d✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&5Abilities:", + " &f• Deal +10% damage while submerged in water", + " &f• Deal +5% damage to players wielding swords", + "", + "&5The trixary has &nsurfaced&r &5again..", + "&5It's power runs deep through your blood", + "&5as you are struck by it's glazing edge." + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + if(attacker.getLocation().getBlock().isLiquid()) + super.getDamageHandler().increaseDamage(10, event, this.getName() + " Water"); + Player victimPlayer = (Player)victim; + ItemStack itemStack = victimPlayer.getItemInHand(); + if(itemStack == null) return; + if(!itemStack.getType().name().endsWith("_SWORD")) return; + super.getDamageHandler().increaseDamage(5, event, this.getName() + " Sword"); + } + } + + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("devour"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("bleed"), 6); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public int getWeight() { + return 1; + } + + /* + @Override + public ArmorSet getArmorSet() { + return AdminWeaponsAPI.getArmorSetFromID("nightmare"); + } + */ +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Kazeshini.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Kazeshini.java new file mode 100644 index 0000000..4ac8f9c --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Kazeshini.java @@ -0,0 +1,109 @@ +package net.crankedpvp.adminweapons.adminweapons.madebyretards; + +import net.crankedpvp.adminweapons.cooldowns.AbilityCooldown; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Kazeshini extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, IHook, ICustomItems, IArmorSet, IHeroic, Weighable { + + @Override + public String getName() { + return "Kazeshini"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HOE; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&c&lヂ&f&ki&r &c&l&nK&f&l&na&c&l&nz&f&l&ne&c&l&ns&f&l&nh&c&l&ni&f&l&nn&c&l&ni&r &f&ki&r&c&lヂ&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + " &4• &f+12.5% Silence Duration", + " &4• &f+12.5% Reaper Hell Trap Chance", + " &4• &f3% Reaper's Hellrage Ability", + "", + "&7&oWhat was once known as the &c\'wind of death\'", + "&7&oIs returning with a &f&onew name. &77oWill it be as", + "&c&opowerful &7&oas it was before? Who knows, but &c&oimmortals", + "&7&osay that it sounds as &4deadly &cas it is..." + + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + if(Math.random() > 0.03) return; + if(CooldownUtils.isCooldownActive(attacker, "hellrageability")) return; + CooldownUtils.registerCooldown(attacker, new AbilityCooldown("hellrageability", 90)); + PotionEffectUtils.addPotionEffect(attacker, PotionEffectType.INCREASE_DAMAGE, 4, "HellrageAbility", 5); + attacker.sendMessage(CC.translate("&4&lHellrage &8" + Arrow.arrow() + " &eYour &4hellrage &eability has given you &cStrength IV")); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 9); + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 5); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + put(org.bukkit.enchantments.Enchantment.FIRE_ASPECT, 2); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 12; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("reaper"); + } + + @Override + public int getWeight() { + return 25; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Mugenjin.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Mugenjin.java new file mode 100644 index 0000000..ff19b3a --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Mugenjin.java @@ -0,0 +1,109 @@ +package net.crankedpvp.adminweapons.adminweapons.madebyretards; + +import net.crankedpvp.adminweapons.cooldowns.AbilityCooldown; +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Mugenjin extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, IArmorSet, Weighable { + + @Override + public String getName() { + return "Mugenjin"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&d&lホ&f&ki&r &d&lM&f&lu&d&lg&f&le&d&ln&d&l&f&lj&d&li&f&ln &f&ki&r&d&lホ&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + " &d• &fAbyss slashing ability.", + "", + "&dMugenjin, also known as \"the call from the abyss\"", + "&dopens a rift in the abyss dealing major damage. " + + ); + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("deepbleed"), 1); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 4); + + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + if(CooldownUtils.isCooldownActive(attacker, "mugenjin")) return; + if(Math.random() > 0.02) return; + CooldownUtils.registerCooldown(attacker, new AbilityCooldown("mugenjin", 60)); + super.getDamageHandler().increaseDamage(15, event, this.getName() + " Abyss Slash"); + + Location location = victim.getLocation(); + victim.getWorld().strikeLightning(location); + this.getAdminWeaponsPlugin().getServer().getScheduler().runTaskLater(this.getAdminWeaponsPlugin(), () -> PVPUtils.strikeLightningCircle(location), 30L); + } + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return false; + } + + @Override + public int equipWeaponOrb() { + return 10; + } + + @Override + public ArmorSet getArmorSet() { + return ArmorSetRegister.getInstance().getArmorSetFromID("wraith"); + } + + @Override + public int getWeight() { + return 15; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Nagamaki.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Nagamaki.java new file mode 100644 index 0000000..1fb2811 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Nagamaki.java @@ -0,0 +1,94 @@ +package net.crankedpvp.adminweapons.adminweapons.madebyretards; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.ICustomItems; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Nagamaki extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, Weighable { + + @Override + public String getName() { + return "Nagamaki"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&6&l❃&f&ki&r &6&lN&e&la&6&lg&e&la&6&lm&e&la&6&lk&e&li &f&ki&r&6&l❃&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&7&oA sword with an exceptionally long handle", + "&7&ousually about as long as the blade", + "&7&othe name refers to the length of the handle wrapping...", + "", + "&6Abilites:", + "&6• &fDeal +10% damage to enemies", + "&6• &fEnemies deal 5% less damage to you", + "", + "&6the &e&lNagamaki &6was used as an infantry weapon, frequently used against cavalry", + "&6use this sword to sweep the battlefield and emerge as the &e&lvictor&6..." + + ); + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("dominate"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 4); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return false; + } + + @Override + public int equipWeaponOrb() { + return 9; + } + + @Override + public int getWeight() { + return 3; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Seppuku.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Seppuku.java new file mode 100644 index 0000000..9268507 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Seppuku.java @@ -0,0 +1,110 @@ +package net.crankedpvp.adminweapons.adminweapons.madebyretards; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.ICustomItems; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Seppuku extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, Weighable { + + @Override + public String getName() { + return "Seppuku"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&4❃&f&ki&r &4&lSeppuku &f&ki&r&4❃&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&4Abilities:", + " &f• Deal +7.5% damage to enemies wielding swords", + " &f• +15% Critical Strike Damage", + "", + "&4Samurai's who held their pride in war", + "&4committed the act known as \"Seppuku\", will you", + "&4fight to the death or commit Seppuku?" + + ); + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("dominate"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("deepwounds"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("insomnia"), 7); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + Player vic = (Player) victim; + if(PVPUtils.isCritical(attacker))super.getDamageHandler().increaseDamage(15, event, this.getName() + " Critical"); + if(vic.getItemInHand() == null) return; + if(vic.getItemInHand().getType() == Material.AIR) return; + if(!vic.getItemInHand().getType().name().endsWith("_SWORD")) return; + super.getDamageHandler().increaseDamage(7.5, event, this.getName() + " Wielding Sword"); + } + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return false; + } + + @Override + public int equipWeaponOrb() { + return 10; + } + + @Override + public int getWeight() { + return 2; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Yorukaze.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Yorukaze.java new file mode 100644 index 0000000..87b21bc --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/madebyretards/Yorukaze.java @@ -0,0 +1,103 @@ +package net.crankedpvp.adminweapons.adminweapons.madebyretards; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.ICustomItems; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Yorukaze extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, Weighable { + + @Override + public String getName() { + return "Yorukaze"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&3❃&f&ki&r &3&l&nY&f&l&no&3&l&nr&f&l&nu&3&l&nk&f&l&na&3&l&nz&f&l&ne&r &f&ki&r&3❃&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&7&oThe ghostly night wind calls...", + "&7&oImbued in this sword is the ability", + "&7&oto silence your foes for eternity.", + "", + "&3Abilites:", + " &3• &fDeal +10% damage to enemies", + " &3• &f+15% Silence Proc Chance", + " &3• &f+25% Silence Duration", + "", + "&3The blade known as Yorukaze is imbued with a", + "&3nightly wind that sweeps all foes ahead of it.." + + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + Player vic = (Player) victim; + super.getDamageHandler().increaseDamage(10, event, this.getName()); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("bleed"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("insomnia"), 7); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return false; + } + + @Override + public int equipWeaponOrb() { + return 0; + } + + @Override + public int getWeight() { + return 13; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ChristmasHook.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ChristmasHook.java new file mode 100644 index 0000000..f1eea3d --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ChristmasHook.java @@ -0,0 +1,93 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ChristmasHook extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, ICustomItems, IHook { + + @Override + public String getName() { + return "Christmas Hook"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HOE; + } + + @Override + public String getDisplayName() { + return "&8&l~=&c&l=-&f&l- &c&lC&f&lh&c&lr&f&li&c&ls&f<&c&lm&f&la&c&ls &f&lH&c&lo&f&lo&c&lk &f&l-&c&l-=&8&l=~"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&bAbilities:", + " &f• Deal +8.5% more outgoing damage to enemies", + " &f• Take -4.5% less incoming damage from enemies", + " &f• +35% Holy white scroll negation", + "" + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(7.5, event, "Christmas Hook"); + } + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(4.5, event, "Christmas Hook"); + } + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 8); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 11; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/DiamondHook.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/DiamondHook.java new file mode 100644 index 0000000..62fbcdc --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/DiamondHook.java @@ -0,0 +1,63 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.IHook; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DiamondHook extends AdminWeapon implements IVanillaEnchantments, IHook { + + @Override + public String getName() { + return "The Diamond Hook"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HOE; + } + + @Override + public String getDisplayName() { + return "&8⪼ &b&lThe Diamond Hook &8⪻"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&bAbilities:", + " &f• Deal 10% more armor durability damage", + " &f• Deal 5% more damage to enemies wielding swords", + "" + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + Player victimPlayer = ((Player) victim); + ItemStack itemStack = victimPlayer.getItemInHand(); + if(itemStack == null || itemStack.getType() == Material.AIR) return; + if(itemStack.getType().name().endsWith("_SWORD")) + super.getDamageHandler().increaseDamage(5, event, "Diamond Hook"); + } + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ElementalExcalibur.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ElementalExcalibur.java new file mode 100644 index 0000000..9f734ab --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ElementalExcalibur.java @@ -0,0 +1,89 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ElementalExcalibur extends AdminWeapon implements ICustomEnchantments, IVanillaEnchantments { + + @Override + public String getName() { + return "Elemental Excalibur"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&4✦&f&ki&r &c&l&oElemental &4&l&oExcalibur &f&ki&r&4✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&4Abilities:", + " &f• +7.5% Outgoing damage to enemy players", + " &f• -1.5% Incoming damage from enemy players", + " &f• +1 Divine Immolation range", + " &f• +3.5% Outgoing Rage Damage", + "", + "&cThe legendary sword of &4King Arthur", + "&cIt is attributed with magical powers", + "&cand associated with the rightful", + "&csovereignty of &4Britain." + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(7.5, event, this.getName()); + } + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(1.5, event, this.getName()); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("bleed"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + put(org.bukkit.enchantments.Enchantment.FIRE_ASPECT, 2); + }}; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/Hofund.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/Hofund.java new file mode 100644 index 0000000..527d104 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/Hofund.java @@ -0,0 +1,76 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Hofund extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments { + + @Override + public String getName() { + return "Hofund"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&3✦&f&ki&r &b&lH&3&lo&b&lf&3&lu&b&ln&3&ld &f&ki&r&3✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&3Abilities:", + " &f• -7.5% Incoming Damage", + " &f• Absorb Ability", + "", + "&3Heimdall has &bfallen&r", + "&3are you worthy enough to wield his sword", + "&3and protect the &bbifrost bridge" + ); + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(7.5D, event, this.getName()); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("paralyze"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/NanoblackReaper.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/NanoblackReaper.java new file mode 100644 index 0000000..c666cda --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/NanoblackReaper.java @@ -0,0 +1,81 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class NanoblackReaper extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments { + + @Override + public String getName() { + return "Nanoblack Reaper"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&5✦&f&ki&r &5&lN&d&la&5&ln&d&lo&5&lb&d&ll&5&la&d&lc&5&lk &8&lReaper &f&ki&r&5✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&5Abilities:", + " &f• +7.5% Outgoing rage damage", + " &f• -3.5% Incoming damage from enemies", + " &f• +6.5% Holy white scroll negation chance", + "", + "&5She smothered them in her &chatred", + "&5Unleash a &bstorm &5of &dnanoblack &5energy blades", + "&5A good critique will find a &cflaw&5 in", + "&5things that you may think are &dperfect" + + ); + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(3.5, event, this.getName()); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 2); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("devour"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("antigank"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("cleave"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("bleed"), 6); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/Retribution.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/Retribution.java new file mode 100644 index 0000000..b3d93e5 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/Retribution.java @@ -0,0 +1,80 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Retribution extends AdminWeapon implements ICustomEnchantments, IVanillaEnchantments { + + @Override + public String getName() { + return "Retribution"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&4✦&f&ki&r &c&lR&e&le&c<&e&lr&c&li&e&lb&c&lu&e<&c&li&e&lo&c&ln &f&ki&r&4✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&cAbilities:", + " &f• +5% Outgoing damage to enemy players", + " &f• +10% Chance to negate enemy holy white scrolls", + "", + "&cThe punishment you receive from this", + "&csword is significant. It's vengeance", + "&cbrings you fear. Be aware.." + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, this.getName()); + } + } + + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("solitude"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("insomnia"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 7); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + }}; + } + +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ShuangGou.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ShuangGou.java new file mode 100644 index 0000000..06f7f98 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/ShuangGou.java @@ -0,0 +1,88 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ShuangGou extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, IHook, ICustomItems { + + @Override + public String getName() { + return "Shuang Gou"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HOE; + } + + @Override + public String getDisplayName() { + return "&4&l=&c&l-&f&l- &c&lS&f&lh&c&lu&f&la&c&ln&f&lg &c&lG&f&lo&c&lu &f&l-&c&l-&4&l="; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&cAbilities:", + " &f• -25% Incoming Silence Duration", + " &f• +35% Chance to negate enemy holy white scrolls", + " &f• +3.5% Outgoing Damage to enemy players", + "", + "&cQian kun ri yue dao..", + "&cA limitless hook-sword combo.", + "&cPrepare for &4death &cif you see me", + "", + "&cI am always watching you :)", + "&7&ozzzzz..." + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(3.5, event, "Shuang Gou"); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 7); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + put(org.bukkit.enchantments.Enchantment.FIRE_ASPECT, 2); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 10; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/WitchsForgery.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/WitchsForgery.java new file mode 100644 index 0000000..7cc044f --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/WitchsForgery.java @@ -0,0 +1,86 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.*; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class WitchsForgery extends AdminWeapon implements IVanillaEnchantments, ICustomEnchantments, IHook, ICustomItems { + + @Override + public String getName() { + return "Witchs Forgery"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_HOE; + } + + @Override + public String getDisplayName() { + return "&f&l<&5&l=&d&l-&f&l- &d&lW&5&li&d<&5&lc&d&lh&5&l'&d&ls &5&lF&d&lo&5&lr&d&lg&5&le&d&lr&5&ly &f&l-&d&l-&5&l=&f&l>"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&5Abilities:", + " &f• +7% Outgoing Damage to enemy players", + " &f• +100% Chance to negate enemy holy white scrolls", + " &f• +100% Chance to block phoenix ability", + "", + "&dThe witch awaits you...", + "&dWhat did you do to upset her?", + "&dExpect the unexpected, good luck." + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(7, event, "Witch Forgery"); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("deepbleed"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 9); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 5); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + put(org.bukkit.enchantments.Enchantment.FIRE_ASPECT, 2); + }}; + } + + @Override + public boolean equipWhiteScroll() { + return true; + } + + @Override + public boolean equipHolyWhiteScroll() { + return true; + } + + @Override + public int equipWeaponOrb() { + return 12; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/YinYangAxe.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/YinYangAxe.java new file mode 100644 index 0000000..adab8c4 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/YinYangAxe.java @@ -0,0 +1,94 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class YinYangAxe extends AdminWeapon implements ICustomEnchantments, IVanillaEnchantments { + + @Override + public String getName() { + return "Yin Yang Axe"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_AXE; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&5✦&f&ki&r &d&lY&5&li&d&ln &f&l& &5&lY&d&la&5&ln&d&lg &f&ki&r&5✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&5Abilities:", + " &f• +6% Outgoing damage to enemy players", + " &f• -9% Incoming damage from players wielding swords", + " &f• Yin & Yang Mark Ability", + "", + "&dTwo halves that together &5complete &dwholeness", + "&dAs both sides chase eachother.. attemping to balance", + "&dand fix the equilibrium of life.", + "&dBlessings.. &5Taijitu" + + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(6, event, this.getName()); + } + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + Player attackingPlayer = ((Player) attacker); + + ItemStack itemStack = attackingPlayer.getItemInHand(); + if(itemStack == null || itemStack.getType() == Material.AIR) return; + if(itemStack.getType().name().endsWith("_SWORD")) super.getDamageHandler().reduceDamage(9, event, "Yin Yang Axe"); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("insanity"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("devour"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("antigank"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("barbarian"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("cleave"), 7); + put(EnchantRegister.getInstance().getEnchantmentFromID("bleed"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 2); + put(org.bukkit.enchantments.Enchantment.FIRE_ASPECT, 2); + }}; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/YinYangSword.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/YinYangSword.java new file mode 100644 index 0000000..3e75d80 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/adminweapons/old/YinYangSword.java @@ -0,0 +1,94 @@ +package net.crankedpvp.adminweapons.adminweapons.old; + +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.ICustomEnchantments; +import net.crankedpvp.adminweapons.struct.IVanillaEnchantments; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class YinYangSword extends AdminWeapon implements ICustomEnchantments, IVanillaEnchantments { + + @Override + public String getName() { + return "Yin Yang Sword"; + } + + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } + + @Override + public String getDisplayName() { + return "&f&ki&r&5✦&f&ki&r &d&lY&5&li&d&ln &f&l& &5&lY&d&la&5&ln&d&lg &f&ki&r&5✦&f&ki&r"; + } + + @Override + public List getLore() { + return Arrays.asList( + "", + "&5Abilities:", + " &f• +6% Outgoing damage to enemy players", + " &f• -9% Incoming damage from players wielding axes", + " &f• Yin & Yang Mark Ability", + "", + "&dTwo halves that together &5complete &dwholeness", + "&dAs both sides chase eachother.. attemping to balance", + "&dand fix the equilibrium of life.", + "&dBlessings.. &5Taijitu" + + ); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(6, event, this.getName()); + } + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + Player attackingPlayer = ((Player) attacker); + + ItemStack itemStack = attackingPlayer.getItemInHand(); + if(itemStack == null || itemStack.getType() == Material.AIR) return; + if(itemStack.getType().name().endsWith("_AXE")) super.getDamageHandler().reduceDamage(9, event, "Yin Yang Sword"); + } + } + + @Override + public Map getCustomEnchantments() { + return new HashMap() {{ + put(EnchantRegister.getInstance().getEnchantmentFromID("divineimmolation"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("execute"), 8); + put(EnchantRegister.getInstance().getEnchantmentFromID("rage"), 6); + put(EnchantRegister.getInstance().getEnchantmentFromID("doublestrike"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("devour"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("lifesteal"), 5); + put(EnchantRegister.getInstance().getEnchantmentFromID("silence"), 4); + put(EnchantRegister.getInstance().getEnchantmentFromID("enrage"), 3); + put(EnchantRegister.getInstance().getEnchantmentFromID("inversion"), 4); + }}; + } + + @Override + public Map getVanillaEnchantments() { + return new HashMap() {{ + put(org.bukkit.enchantments.Enchantment.DAMAGE_ALL, 6); + put(org.bukkit.enchantments.Enchantment.DURABILITY, 2); + put(org.bukkit.enchantments.Enchantment.FIRE_ASPECT, 2); + }}; + } +} \ No newline at end of file diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/commands/AdminWeaponsCommand.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/commands/AdminWeaponsCommand.java new file mode 100644 index 0000000..ef3bd16 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/commands/AdminWeaponsCommand.java @@ -0,0 +1,74 @@ +package net.crankedpvp.adminweapons.commands; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.AdminWeaponsPlugin; +import net.crankedpvp.adminweapons.inventory.AdminWeaponsInventory; +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.IArmorSet; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Command("adminweapons") +@Alias({"adminweapon", "caw"}) +public class AdminWeaponsCommand extends CommandBase { + + private final AdminWeaponsPlugin plugin; + public AdminWeaponsCommand(AdminWeaponsPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getAdminWeaponsInventory().getUI().open(player); + } + + @SubCommand("give") + @Permission("cranked.admin") + public void giveCommand(final CommandSender commandSender, @Completion("#adminweapons") final String adminWeaponString, @Optional @Completion("#players")Player player) { + if(player == null) { + if(!(commandSender instanceof Player)) return; + player = (Player) commandSender; + } + + AdminWeapon adminWeapon = this.plugin.getAdminWeaponRegister().getAdminWeaponFromID(adminWeaponString); + PlayerUtils.giveOrDropProtectedItem(player, adminWeapon.buildItem(), 5); + player.sendMessage(CC.translate("&aYou have received an " + adminWeapon.getDisplayName() + "&r &aadmin weapon")); + + } + + @SubCommand("fixdata") + @Permission("cranked.admin") + public void fixDataCommand(final Player player) { + AdminWeapon adminWeapon = AdminWeaponsAPI.getPlayersHeldAdminWeapon(player); + if(!(adminWeapon instanceof IArmorSet)) { + player.sendMessage(CC.translate("&cThis item cannot be fixed")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + return; + } + NBTItem nbtItem = new NBTItem(player.getItemInHand()); + NBTCompound cosmicDataForArmorSet = nbtItem.getOrCreateCompound("cosmicData"); + cosmicDataForArmorSet.setString("weaponType", ((IArmorSet) adminWeapon).getArmorSet().getID()); + nbtItem.setString("weaponType", ((IArmorSet) adminWeapon).getArmorSet().getID()); + player.setItemInHand(nbtItem.getItem()); + player.sendMessage(CC.translate("&aYou have successfully fixed this weapon")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0f, 2.0f); + + } + + @SubCommand("reload") + @Permission("cranked.admin") + public void reloadCommand(final CommandSender commandSender) { + this.plugin.getConfigManager().reloadFiles(); + this.plugin.getAdminWeaponsConfigManager().reloadFiles(); + commandSender.sendMessage(CC.translate("&aReloaded")); + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/cooldowns/AbilityCooldown.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/cooldowns/AbilityCooldown.java new file mode 100644 index 0000000..514f5cc --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/cooldowns/AbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.adminweapons.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class AbilityCooldown extends CurrentCooldown { + public AbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/inventory/AdminWeaponsInventory.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/inventory/AdminWeaponsInventory.java new file mode 100644 index 0000000..e2d653e --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/inventory/AdminWeaponsInventory.java @@ -0,0 +1,76 @@ +package net.crankedpvp.adminweapons.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.adminweapons.AdminWeaponsPlugin; +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; + +public class AdminWeaponsInventory { + private final Gui adminWeaponsInventory; + + public Gui getUI() { + return this.adminWeaponsInventory; + } + + Collection adminWeapons = AdminWeaponsPlugin.getInstance().getAdminWeaponRegister().getAdminWeapons(); + + public AdminWeaponsInventory() { + this.adminWeaponsInventory = new Gui(6, "Cranked Admin Weapons"); + this.adminWeaponsInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.adminWeaponsInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.adminWeaponsInventory.updateItem(6, 5, new GuiItem(createExitItem(), event -> event.getWhoClicked().closeInventory())); + this.adminWeaponsInventory.updateItem(1, 5, new GuiItem(createInformationItem())); + + List adminWeaponList = new ArrayList<>(this.adminWeapons); + adminWeaponList.sort(Comparator.comparing(adminWeapon -> { + if(!(adminWeapon instanceof Weighable)) return 0; + return ((Weighable) adminWeapon).getWeight(); + })); + + for(AdminWeapon adminWeapon : adminWeaponList) { + if(!(adminWeapon instanceof Weighable)) continue; + this.adminWeaponsInventory.addItem(new GuiItem(adminWeapon.buildItem(), event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) event.getWhoClicked().getInventory().addItem(adminWeapon.buildItem()); + })); + } + } + + private ItemStack createExitItem() { + ItemStack item = new ItemStack(Material.BED); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cExit Admin Weapons menu")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createInformationItem() { + return new ItemBuilder(Material.BOOK, "&a&lCranked Admin Weapons", + "&7Admin weapons are special weapons", + "&7hand-crafted by the best warriors.", + "", + "&7Each weapon has it's own effects and", + "&7abilities, and also may have over-leveled", + "&7enchantments.") + .colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(""); + item.setItemMeta(meta); + return item; + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/listeners/HookListener.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/listeners/HookListener.java new file mode 100644 index 0000000..b53e1f8 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/listeners/HookListener.java @@ -0,0 +1,62 @@ +package net.crankedpvp.adminweapons.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.adminweapons.AdminWeaponsPlugin; +import net.crankedpvp.adminweapons.struct.config.ConfigManager; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.HookUtils; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +public class HookListener implements Listener { + + private final ConfigManager configManager; + + public HookListener(AdminWeaponsPlugin plugin) { + this.configManager = plugin.getConfigManager(); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void hookDamageListener(EntityDamageByEntityEvent event) { + if(event.getEntity() == null || !(event.getEntity() instanceof Player)) return; + if(event.getDamager() == null || !(event.getDamager() instanceof Player)) return; + + Player attacker = ((Player) event.getDamager()); + ItemStack itemStack = attacker.getItemInHand(); + if(itemStack == null || !itemStack.getType().name().endsWith("_HOE")) return; + NBTItem nbtItem = new NBTItem(attacker.getItemInHand()); + if(!nbtItem.hasNBTData()) return; + if(!nbtItem.hasKey(HookUtils.NBT_KEY)) return; + if(nbtItem.getString(HookUtils.NBT_KEY).equals(HookUtils.NBT_STRING)) { + CrankedUtils.instance.getDamageHandler().increaseDamage(this.configManager.getConfig(ConfigManager.ConfigFile.SETTINGS).getInt("hook.damage-buff"), event, "Base Hook Damage"); + } + } + + @EventHandler + public void makeSharpVI(EntityDamageByEntityEvent event) { + if(event.getEntity() == null || !(event.getEntity() instanceof Player)) return; + if(event.getDamager() == null || !(event.getDamager() instanceof Player)) return; + + Player attacker = ((Player) event.getDamager()); + ItemStack itemStack = attacker.getItemInHand(); + if(itemStack == null || !itemStack.getType().name().endsWith("_HOE")) return; + NBTItem nbtItem = new NBTItem(attacker.getItemInHand()); + if(!nbtItem.hasNBTData()) return; + if(!nbtItem.hasKey(HookUtils.NBT_KEY)) return; + if(nbtItem.getString(HookUtils.NBT_KEY).equals(HookUtils.NBT_STRING)) { + if (itemStack.getItemMeta().hasEnchant(Enchantment.DAMAGE_ALL)) { + if (itemStack.getEnchantments().get(Enchantment.DAMAGE_ALL) < 6) { + ItemStack sharp6hook = itemStack.clone(); + sharp6hook.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 6); + attacker.setItemInHand(sharp6hook); + attacker.updateInventory(); + } + } + } + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/listeners/PlayerListener.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/listeners/PlayerListener.java new file mode 100644 index 0000000..6bf5809 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/listeners/PlayerListener.java @@ -0,0 +1,47 @@ +package net.crankedpvp.adminweapons.listeners; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.adminweapons.AdminWeaponsPlugin; +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class PlayerListener implements Listener { + + private AdminWeaponsPlugin plugin; + public PlayerListener(AdminWeaponsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.LOW) + public void playerReceiveDamage(EntityDamageByEntityEvent event) { + Entity damager = event.getDamager(); + Entity victim = event.getEntity(); + + if (victim instanceof Player) { + Player player = (Player) victim; + AdminWeapon adminWeapon = AdminWeaponsAPI.getPlayersHeldAdminWeapon(player); + if(adminWeapon == null) return; + if (!WorldGuardUtils.canPvPInRegion(victim.getLocation()) || !WorldGuardUtils.canPvPInRegion(damager.getLocation())) return; + adminWeapon.onIncomingDamage(player, damager, event); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void playerSendDamage(EntityDamageByEntityEvent event) { + Entity damager = event.getDamager(); + Entity victim = event.getEntity(); + if (damager instanceof Player) { + Player player = (Player) damager; + AdminWeapon adminWeapon = AdminWeaponsAPI.getPlayersHeldAdminWeapon(player); + if(adminWeapon == null) return; + if (!WorldGuardUtils.canPvPInRegion(victim.getLocation()) || !WorldGuardUtils.canPvPInRegion(damager.getLocation())) return; + adminWeapon.onOutgoingDamage(player, victim, event); + } + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/AdminWeapon.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/AdminWeapon.java new file mode 100644 index 0000000..3926430 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/AdminWeapon.java @@ -0,0 +1,121 @@ +package net.crankedpvp.adminweapons.struct; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.adminweapons.AdminWeaponsPlugin; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.HookUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.holywhitescrolls.HolyWhitescrollAPI; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Locale; + +public abstract class AdminWeapon implements Listener { + + + @Getter + private final DamageHandler damageHandler; + @Getter + private final AdminWeaponsPlugin adminWeaponsPlugin; + + public AdminWeapon() { + this.damageHandler = CrankedUtils.instance.getDamageHandler(); + this.adminWeaponsPlugin = AdminWeaponsPlugin.getInstance(); + } + + + public abstract String getName(); + + public abstract Material getMaterial(); + + public abstract String getDisplayName(); + + public abstract List getLore(); + + public String getID() { return this.getName().toLowerCase(Locale.ROOT).replace(" ", ""); } + + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) {} + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) {} + + + public ItemStack buildItem() { + ItemBuilder itemBuilder = new ItemBuilder(getMaterial(), getDisplayName()); + if(this instanceof IArmorSet) { + IArmorSet iArmorSet = ((IArmorSet) this); + if(iArmorSet.getArmorSet() != null) { + if(iArmorSet.getArmorSet() instanceof Weapon) { + for(String s : ((Weapon) iArmorSet.getArmorSet()).getWeaponLore()) { + itemBuilder.addLoreLine(s); + } + } + } + } + itemBuilder.addLore(getLore()); + + itemBuilder.setUnbreakable(true); + itemBuilder.addItemFlag(ItemFlag.HIDE_ATTRIBUTES).addItemFlag(ItemFlag.HIDE_UNBREAKABLE); + NBTItem wrapper = new NBTItem(itemBuilder.colorize().build()); + wrapper.setString("cosmicType", "adminWeapon"); + + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + cosmicData.setString("adminWeaponType", this.getID()); + ItemStack itemStack = wrapper.getItem(); + + if(this instanceof ICustomEnchantments) { + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + enchantedItemBuilder.addEnchantments(((ICustomEnchantments) this).getCustomEnchantments()); + enchantedItemBuilder.sortEnchantLore().addEnchantAmountToName(); + itemStack = enchantedItemBuilder.build(); + } + if(this instanceof ICustomItems) { + ICustomItems customItems = (ICustomItems) this; + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + if(customItems.equipWeaponOrb() > 9) { + enchantedItemBuilder.setSlots(customItems.equipWeaponOrb()); + enchantedItemBuilder.updateSlotsLore(customItems.equipWeaponOrb()); + } + if(customItems.equipWhiteScroll()) enchantedItemBuilder.setProtected(true); + itemStack = enchantedItemBuilder.build(); + if(customItems.equipHolyWhiteScroll()) itemStack = HolyWhitescrollAPI.addHolyWhitescrollToItem(itemStack); + } + if(this instanceof IHook && getMaterial().name().endsWith("_HOE")) itemStack = HookUtils.applyHookData(itemStack); + + if(this instanceof IVanillaEnchantments) { + assert itemStack != null; + itemStack.addUnsafeEnchantments(((IVanillaEnchantments) this).getVanillaEnchantments()); + } + if(this instanceof IArmorSet) { + assert itemStack != null; + NBTItem nbtItemForArmorSet = new NBTItem(itemStack); + NBTCompound cosmicDataForArmorSet = nbtItemForArmorSet.getOrCreateCompound("cosmicData"); + cosmicDataForArmorSet.setString("weaponType", ((IArmorSet) this).getArmorSet().getID()); + nbtItemForArmorSet.setString("weaponType", ((IArmorSet) this).getArmorSet().getID()); + itemStack = nbtItemForArmorSet.getItem(); + } + if(this instanceof IHeroic) { + if(this instanceof IHook) { + assert itemStack != null; + itemStack = CrankedArmorAPI.heroifyHook(itemStack); + } else { + itemStack = CrankedArmorAPI.heroifyWeapon(itemStack); + } + } + return itemStack; + } + + +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/AdminWeaponRegister.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/AdminWeaponRegister.java new file mode 100644 index 0000000..a26ca59 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/AdminWeaponRegister.java @@ -0,0 +1,102 @@ +package net.crankedpvp.adminweapons.struct; + +import com.google.common.collect.Maps; +import lombok.Getter; +import net.crankedpvp.adminweapons.AdminWeaponsPlugin; +import net.crankedpvp.adminweapons.adminweapons.cosmic.TimeSplitter; +import net.crankedpvp.adminweapons.adminweapons.current.*; +import net.crankedpvp.adminweapons.adminweapons.madebyretards.*; +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; + +import java.util.Collection; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; + +public class AdminWeaponRegister { + + private final AdminWeaponsPlugin plugin; + private final Map adminWeapons; + @Getter + private final Map cachedPlayers; + public AdminWeaponRegister(AdminWeaponsPlugin plugin) { + this.plugin = plugin; + this.adminWeapons = Maps.newConcurrentMap(); + this.cachedPlayers = Maps.newConcurrentMap(); + } + + public void initialize() { + this.registerAll( + new TimeSplitter() + ); + /* + this.registerAll(new Kaladanda(), new BlackMirror(), new Kusangi()); + this.registerAll(new Shigenjo(), new Purifier(), new Trixary(), new Deathraze(), new Hellforge()); + this.registerAll(new Seppuku(), new Yorukaze(), new Nagamaki()); + this.registerAll(new Igniscale(), new Duskbane()); + //this.register(new Excalibur(), new Mugenjin(), new Kazeshini()); + /* + old + this.registerAll(new ChristmasHook(), new DiamondHook(), new ShuangGou()); + this.registerAll(new Deathraze(), new ElementalExcalibur(), new Hofund(), new Purifier(), new Retribution(), new Shigenjo(), new YinYangSword()); + this.registerAll(new Hellforge(), new NanoblackReaper(), new Trixary(), new WitchsForgery(), new YinYangAxe()); + */ + } + + public void registerAll(AdminWeapon... adminWeapons) { + for (AdminWeapon adminWeapon : adminWeapons) { + this.register(adminWeapon); + } + } + + public void register(AdminWeapon adminWeapon) { + try { + this.adminWeapons.put(adminWeapon.getID(), adminWeapon); + this.plugin.getServer().getPluginManager().registerEvents(adminWeapon, this.plugin); + this.plugin.getLogger().info("Successfully registered admin weapon: " + adminWeapon.getID()); + } catch (Exception e) { + this.plugin.getLogger().warning("Failed to register admin weapon: " + adminWeapon.getID()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.adminWeapons.clear(); + } + + public void unregister(AdminWeapon adminWeapon) { + this.adminWeapons.remove(adminWeapon.getID()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isAdminWeapon(String name) { + return (this.getAdminWeaponFromID(name) != null); + } + + public AdminWeapon getAdminWeaponFromID(String id) { + Validate.notNull(id); + Validate.notEmpty(id); + return this.adminWeapons.get(id.toLowerCase()); + } + + public AdminWeapon getAdminWeaponFromName(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + name = this.getAdminWeaponIDFromName(name); + return this.adminWeapons.get(name.toLowerCase()); + } + + public String getAdminWeaponIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getAdminWeapons() { + return Collections.unmodifiableCollection(this.adminWeapons.values()); + } + +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IArmorSet.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IArmorSet.java new file mode 100644 index 0000000..c4e0f1e --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IArmorSet.java @@ -0,0 +1,7 @@ +package net.crankedpvp.adminweapons.struct; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; + +public interface IArmorSet { + ArmorSet getArmorSet(); +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/ICustomEnchantments.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/ICustomEnchantments.java new file mode 100644 index 0000000..afa6721 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/ICustomEnchantments.java @@ -0,0 +1,8 @@ +package net.crankedpvp.adminweapons.struct; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import java.util.Map; + +public interface ICustomEnchantments { + Map getCustomEnchantments(); +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/ICustomItems.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/ICustomItems.java new file mode 100644 index 0000000..5e655f3 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/ICustomItems.java @@ -0,0 +1,7 @@ +package net.crankedpvp.adminweapons.struct; + +public interface ICustomItems { + boolean equipWhiteScroll(); + boolean equipHolyWhiteScroll(); + int equipWeaponOrb(); +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IHeroic.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IHeroic.java new file mode 100644 index 0000000..df34055 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IHeroic.java @@ -0,0 +1,4 @@ +package net.crankedpvp.adminweapons.struct; + +public interface IHeroic { +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IHook.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IHook.java new file mode 100644 index 0000000..71d7360 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IHook.java @@ -0,0 +1,4 @@ +package net.crankedpvp.adminweapons.struct; + +public interface IHook { +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IVanillaEnchantments.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IVanillaEnchantments.java new file mode 100644 index 0000000..826ccb1 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/IVanillaEnchantments.java @@ -0,0 +1,9 @@ +package net.crankedpvp.adminweapons.struct; + +import org.bukkit.enchantments.Enchantment; + +import java.util.Map; + +public interface IVanillaEnchantments { + Map getVanillaEnchantments(); +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/annotations/ConfigValue.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/annotations/ConfigValue.java new file mode 100644 index 0000000..fa188f5 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/annotations/ConfigValue.java @@ -0,0 +1,19 @@ +package net.crankedpvp.adminweapons.struct.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * don't forget to not make the field final when using this annotation + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigValue { + + String path() default "adminweapon."; + String name() default ""; + +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/AdminWeaponsConfig.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/AdminWeaponsConfig.java new file mode 100644 index 0000000..71590dd --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/AdminWeaponsConfig.java @@ -0,0 +1,119 @@ +package net.crankedpvp.adminweapons.struct.config; + +import lombok.AccessLevel; +import lombok.Getter; +import net.crankedpvp.adminweapons.AdminWeaponsPlugin; +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import net.crankedpvp.adminweapons.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; + +@Getter +public class AdminWeaponsConfig { + + @Getter(value = AccessLevel.PRIVATE) + private final AdminWeaponsPlugin plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + private final AdminWeapon adminWeapon; + + public AdminWeaponsConfig(AdminWeaponsPlugin plugin, String path, AdminWeapon adminWeapon) { + this.plugin = plugin; + this.path = path; + this.adminWeapon = adminWeapon; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public void setupConfigFile() { + this.createDefaultFile(); + this.config = YamlConfiguration.loadConfiguration(configFile); + + this.loadVariables(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path); + e.printStackTrace(); + } + return false; + } + + public void createDefaultFile() { + if (!configFile.exists()) { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path); + e.printStackTrace(); + } + } + } + + public void reloadConfig() { + config = YamlConfiguration.loadConfiguration(configFile); + this.loadVariables(); + } + + public void loadConfigFromDisk() { + try { + config.load(configFile); + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path); + e.printStackTrace(); + } + } + + public void loadVariables() { + boolean needSave = false; + for (Field field : this.adminWeapon.getClass().getDeclaredFields()) { + + try { + field.setAccessible(true); + + if (field.isAnnotationPresent(ConfigValue.class)) { + ConfigValue annotationValue = field.getAnnotation(ConfigValue.class); + + String name = annotationValue.name().equals("") ? field.getName() : annotationValue.name(); + + String path = annotationValue.path().endsWith(".") ? annotationValue.path() : annotationValue.path() + "."; + + if (!this.config.contains(path + name)) { + this.config.set(path + name, field.get(this.adminWeapon)); + needSave = true; + continue; + } + + Object fieldValue = this.config.get(path + name); + + if (fieldValue instanceof String) fieldValue = CC.translate((String) fieldValue); + + field.set(this.adminWeapon, fieldValue); + } + } catch (IllegalAccessException | NullPointerException | IllegalArgumentException e) { + Bukkit.getConsoleSender().sendMessage(CC.translate("&c[CrankedEnchants] - Error invalid config value for enchant" + adminWeapon.getName())); + } + } + if (needSave) { + saveConfig(); + reloadConfig(); + } + } + +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/AdminWeaponsConfigManager.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/AdminWeaponsConfigManager.java new file mode 100644 index 0000000..069d379 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/AdminWeaponsConfigManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.adminweapons.struct.config; + +import lombok.Getter; +import net.crankedpvp.adminweapons.AdminWeaponsPlugin; +import net.crankedpvp.adminweapons.struct.AdminWeapon; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class AdminWeaponsConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public AdminWeaponsConfigManager(AdminWeaponsPlugin plugin) { + for (AdminWeapon adminWeapon : plugin.getAdminWeaponRegister().getAdminWeapons()) { + AdminWeaponsConfig adminWeaponsConfig = new AdminWeaponsConfig(plugin, "weapons/" + adminWeapon.getID() + ".yml", adminWeapon); + configs.put(adminWeapon, adminWeaponsConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AdminWeaponsConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AdminWeaponsConfig::reloadConfig); + } + + public AdminWeaponsConfig getAbstractConfig(AdminWeapon adminWeapon) { + return configs.get(adminWeapon); + } + + public FileConfiguration getConfig(AdminWeapon adminWeapon) { + return getAbstractConfig(adminWeapon).getConfig(); + } +} diff --git a/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/ConfigManager.java b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/ConfigManager.java new file mode 100644 index 0000000..10fa2b7 --- /dev/null +++ b/AdminWeapons/src/main/java/net/crankedpvp/adminweapons/struct/config/ConfigManager.java @@ -0,0 +1,52 @@ +package net.crankedpvp.adminweapons.struct.config; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.crankedpvp.crankedutils.utils.config.AbstractConfig; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; + +public class ConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public ConfigManager(JavaPlugin plugin) { + + for (ConfigFile configFile : ConfigFile.values()) { + AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName()); + configs.put(configFile, abstractConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AbstractConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AbstractConfig::reloadConfig); + } + + public AbstractConfig getAbstractConfig(ConfigFile configFile) { + return configs.get(configFile); + } + + public FileConfiguration getConfig(ConfigFile configFile) { + return getAbstractConfig(configFile).getConfig(); + } + + @Getter + @RequiredArgsConstructor + public enum ConfigFile { + + SETTINGS("settings.yml"), + ; + + private final String fileName; + + } + +} diff --git a/AdminWeapons/src/main/resources/plugin.yml b/AdminWeapons/src/main/resources/plugin.yml new file mode 100644 index 0000000..9b38c03 --- /dev/null +++ b/AdminWeapons/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedAdminWeapons +main: net.crankedpvp.adminweapons.AdminWeaponsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedArmor \ No newline at end of file diff --git a/AdminWeapons/src/main/resources/settings.yml b/AdminWeapons/src/main/resources/settings.yml new file mode 100644 index 0000000..87d4506 --- /dev/null +++ b/AdminWeapons/src/main/resources/settings.yml @@ -0,0 +1,2 @@ +hook: + damage-buff: 20 \ No newline at end of file diff --git a/Arcade/pom.xml b/Arcade/pom.xml new file mode 100644 index 0000000..46d1b8f --- /dev/null +++ b/Arcade/pom.xml @@ -0,0 +1,34 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Arcade + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + Armor + net.crankedpvp + + + net.crankedpvp + Staff + + + + \ No newline at end of file diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/ArcadeAPI.java b/Arcade/src/main/java/net/crankedpvp/arcade/ArcadeAPI.java new file mode 100644 index 0000000..2d60d50 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/ArcadeAPI.java @@ -0,0 +1,33 @@ +package net.crankedpvp.arcade; + +import net.crankedpvp.arcade.struct.ArcadeManager; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.UUID; + +public class ArcadeAPI { + public static String WORLD_NAME = "world_arcade"; + public static String SAFEZONE_REGION_NAME = "arcade_safezone"; + + private static ArcadeManager getArcadeManager() { + ArcadePlugin plugin = ArcadePlugin.getInstance(); + return plugin == null ? null : plugin.getArcadeManager(); + } + + public static boolean canPvP(UUID uuid1, UUID uuid2) { + ArcadeManager arcadeManager = getArcadeManager(); + return arcadeManager != null && arcadeManager.inSameArcadeMatch(uuid1, uuid2); + } + + public static boolean inArcadeWorld(UUID uuid) { + Player player = Bukkit.getPlayer(uuid); + if (player == null) return false; + return player.getWorld().getName().equals(WORLD_NAME); + } + + public static boolean inArcadeMatch(UUID uuid) { + ArcadeManager arcadeManager = getArcadeManager(); + return arcadeManager != null && inArcadeWorld(uuid) && arcadeManager.inArcadeMatch(uuid); + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/ArcadePlugin.java b/Arcade/src/main/java/net/crankedpvp/arcade/ArcadePlugin.java new file mode 100644 index 0000000..40074ae --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/ArcadePlugin.java @@ -0,0 +1,55 @@ +package net.crankedpvp.arcade; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.arcade.commands.ArcadeAdminCommand; +import net.crankedpvp.arcade.commands.ArcadeCommand; +import net.crankedpvp.arcade.language.LanguageHandler; +import net.crankedpvp.arcade.listeners.ArcadeLogicListener; +import net.crankedpvp.arcade.listeners.SignListener; +import net.crankedpvp.arcade.struct.ArcadeManager; +import net.crankedpvp.arcade.tasks.ArcadeHiderTask; +import net.crankedpvp.arcade.tasks.ArcadeRegionChecker; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +@Getter +public class ArcadePlugin extends JavaPlugin { + private ArcadeManager arcadeManager; + private LanguageHandler languageHandler; + private ArcadeRegionChecker arcadeRegionChecker; + private ArcadeHiderTask arcadeHiderTask; + private CommandManager commandManager; + + @Getter + private static ArcadePlugin instance; + public void onEnable() { + instance = this; + if (Bukkit.getWorld(ArcadeAPI.WORLD_NAME) == null) { + getLogger().severe("Required world '" + ArcadeAPI.WORLD_NAME + "' is not loaded; disabling Arcade."); + Bukkit.getPluginManager().disablePlugin(this); + return; + } + this.languageHandler = new LanguageHandler(this); + languageHandler.load(); + this.commandManager = new CommandManager(this); + this.commandManager.register(new ArcadeAdminCommand(this)); + this.commandManager.register(new ArcadeCommand()); + + this.arcadeManager = new ArcadeManager(); + this.arcadeRegionChecker = new ArcadeRegionChecker(); + this.arcadeHiderTask = new ArcadeHiderTask(); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, arcadeRegionChecker, 20L, 10L); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, arcadeHiderTask, 20L, 5L); + PluginUtils.registerListeners(this, new ArcadeLogicListener(this)); + PluginUtils.registerListeners(this, new SignListener()); + + } + + public void onDisable() { + if (arcadeManager != null) arcadeManager.onDisable(); + if (languageHandler != null) languageHandler.save(); + instance = null; + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/commands/ArcadeAdminCommand.java b/Arcade/src/main/java/net/crankedpvp/arcade/commands/ArcadeAdminCommand.java new file mode 100644 index 0000000..aa117ab --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/commands/ArcadeAdminCommand.java @@ -0,0 +1,48 @@ +package net.crankedpvp.arcade.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.annotations.WrongUsage; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.arcade.ArcadePlugin; +import net.crankedpvp.arcade.language.Language; +import net.crankedpvp.arcade.language.LanguageHandler; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +@Command("aarcade") +public class ArcadeAdminCommand extends CommandBase { + + private final LanguageHandler languageHandler; + + public ArcadeAdminCommand(ArcadePlugin plugin) { + this.languageHandler = plugin.getLanguageHandler(); + } + + @SubCommand("reload") + @WrongUsage("&cUsage: /ca reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + this.languageHandler.load(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } + + @SubCommand("fuckup") + @WrongUsage("&cUsage: /ca fuckup") + @Permission("cranked.admin") + public void fuckupCommand(Player sender) { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + for (Player player1 : Bukkit.getOnlinePlayers()) { + if (!player.canSee(player1)) player.showPlayer(player1); + } + } + sender.sendMessage(CC.translate("&cYeahhhh... We fucked up xD")); + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/commands/ArcadeCommand.java b/Arcade/src/main/java/net/crankedpvp/arcade/commands/ArcadeCommand.java new file mode 100644 index 0000000..a291295 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/commands/ArcadeCommand.java @@ -0,0 +1,16 @@ +package net.crankedpvp.arcade.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.arcade.guis.ArcadeGUI; +import org.bukkit.entity.Player; + +@Command("arcade") +public class ArcadeCommand extends CommandBase { + @Default + public void onDefault(Player player) { + ArcadeGUI arcadeGUI = new ArcadeGUI(); + arcadeGUI.getArcadeGui().open(player); + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/cooldowns/GracePeriod.java b/Arcade/src/main/java/net/crankedpvp/arcade/cooldowns/GracePeriod.java new file mode 100644 index 0000000..8aed0b8 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/cooldowns/GracePeriod.java @@ -0,0 +1,9 @@ +package net.crankedpvp.arcade.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class GracePeriod extends CurrentCooldown { + public GracePeriod(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/guis/ArcadeGUI.java b/Arcade/src/main/java/net/crankedpvp/arcade/guis/ArcadeGUI.java new file mode 100644 index 0000000..0a959d0 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/guis/ArcadeGUI.java @@ -0,0 +1,82 @@ +package net.crankedpvp.arcade.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.arcade.ArcadeAPI; +import net.crankedpvp.arcade.ArcadePlugin; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +@Getter +public class ArcadeGUI { + private Gui arcadeGui; + private DyeColor color = DyeColor.WHITE; + + public ArcadeGUI() { + this.arcadeGui = new Gui(1, "Cranked Arcade"); + this.arcadeGui.setDefaultClickAction(event -> event.setCancelled(true)); + + this.arcadeGui.setItem(4, new GuiItem(getArcadeItem(color), event -> { + event.getWhoClicked().closeInventory(); + + ((Player) event.getWhoClicked()).chat("/warp arcade"); + })); + Bukkit.getScheduler().scheduleSyncRepeatingTask(ArcadePlugin.getInstance(), () -> { + color = DyeColor.values()[(color.ordinal() + 1) % DyeColor.values().length]; + + this.arcadeGui.updateItem(4, new GuiItem(getArcadeItem(color), event -> { + event.getWhoClicked().closeInventory(); + ((Player) event.getWhoClicked()).chat("/warp arcade"); + + })); + }, 0L, 10L); + } + + + public ItemStack getArcadeItem(DyeColor color) { + Map setsMap = new HashMap<>(); + ItemBuilder itemBuilder = new ItemBuilder( + Material.STAINED_CLAY, 1, color.getWoolData()) + .setName("&d&lArcade Warp") + .addLoreLine("&7This area is a warp meant") + .addLoreLine("&7only for the warriors who hold") + .addLoreLine("&7the greatest sets of armor on") + .addLoreLine("&7the realm. You must have an armor") + .addLoreLine("&7set equipped to join this warp.") + .addLoreLine("") + .addLoreLine("&dCurrent Info:") + .addLoreLine("&fPlayers: &7" + Bukkit.getWorld(ArcadeAPI.WORLD_NAME).getPlayers().size()) + .addLoreLine("") + .addLoreLine("&dSets:"); + + for (Player player : Bukkit.getWorld(ArcadeAPI.WORLD_NAME).getPlayers()) { + ArmorSet armorSet = CrankedArmorAPI.getCurrentArmorSet(player); + if (armorSet == null) continue; + if (setsMap.containsKey(armorSet)) { + setsMap.put(armorSet, setsMap.get(armorSet) + 1); + } else { + setsMap.put(armorSet, 1); + } + } + + for (Map.Entry sets : setsMap.entrySet()) { + ArmorSet set = sets.getKey(); + int amount = sets.getValue(); + itemBuilder.addLoreLine("&8 ● " + set.getDisplayName() + ": &7" + amount); + } + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&7Click to teleport to the arcade."); + itemBuilder.colorize(); + return itemBuilder.build(); + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/language/Language.java b/Arcade/src/main/java/net/crankedpvp/arcade/language/Language.java new file mode 100644 index 0000000..74748a6 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/language/Language.java @@ -0,0 +1,109 @@ +package net.crankedpvp.arcade.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + CANT_PVP, + MATCH_STARTED_KILLER, + MATCH_STARTED_VICTIM, + MATCH_ENDED, + MATCH_KILLED, + MATCH_STARTED_BROADCAST, + MATCH_KILLED_BROADCAST, + ADMIN_RELOADING, + ADMIN_RELOADED, + GRACE_PERIOD_OTHER, + GRACE_PERIOD, + TELEPORT_NO_SET, + WHITELISTED_COMMANDS, + BLACKLISTED_COMMAND, + + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return value != null ? value : this.name(); + } + + public String getValue(UnaryOperator function) { + return value != null ? function.apply(value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(getValue(function)); + } + +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/language/LanguageHandler.java b/Arcade/src/main/java/net/crankedpvp/arcade/language/LanguageHandler.java new file mode 100644 index 0000000..5b2c012 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.arcade.language; + +import net.crankedpvp.arcade.ArcadePlugin; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final ArcadePlugin plugin; + + public LanguageHandler(ArcadePlugin plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/listeners/ArcadeLogicListener.java b/Arcade/src/main/java/net/crankedpvp/arcade/listeners/ArcadeLogicListener.java new file mode 100644 index 0000000..1d6dd07 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/listeners/ArcadeLogicListener.java @@ -0,0 +1,144 @@ +package net.crankedpvp.arcade.listeners; + +import net.crankedpvp.arcade.ArcadeAPI; +import net.crankedpvp.arcade.ArcadePlugin; +import net.crankedpvp.arcade.cooldowns.GracePeriod; +import net.crankedpvp.arcade.language.Language; +import net.crankedpvp.arcade.struct.ArcadeManager; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.*; + +import java.util.List; + +public class ArcadeLogicListener implements Listener { + private ArcadeManager arcadeManager; + private ArcadePlugin plugin; + + public ArcadeLogicListener(ArcadePlugin plugin) { + this.plugin = plugin; + this.arcadeManager = plugin.getArcadeManager(); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onDamage(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getEntity() instanceof Player && event.getDamager() instanceof Player) { + Player killer = (Player) event.getDamager(); + Player killed = (Player) event.getEntity(); + if (!ArcadeAPI.inArcadeWorld(killer.getUniqueId())) return; + if (!ArcadeAPI.inArcadeWorld(killed.getUniqueId())) return; + if (!ArcadeAPI.inArcadeMatch(killer.getUniqueId()) && !ArcadeAPI.inArcadeMatch(killed.getUniqueId())) { + + if (CooldownUtils.isCooldownActive(killed, "arcadeGracePeriod")) { + killer.sendMessage(CC.translate(Language.GRACE_PERIOD_OTHER.getMessage()).replace("{victim}", killed.getName()).replace("{time}", CooldownUtils.getFormattedCooldown(killed, "arcadeGracePeriod"))); + event.setCancelled(true); + return; + } + + if (CooldownUtils.isCooldownActive(killer, "arcadeGracePeriod")) { + killer.sendMessage(CC.translate(Language.GRACE_PERIOD.getMessage()).replace("{time}", CooldownUtils.getFormattedCooldown(killer, "arcadeGracePeriod"))); + event.setCancelled(true); + return; + } + arcadeManager.startMatch(killer.getUniqueId(), killed.getUniqueId()); + return; + } + + if (!ArcadeAPI.canPvP(killer.getUniqueId(), killed.getUniqueId())) { + killer.sendMessage(CC.translate(Language.CANT_PVP.getMessage().replace("{victim}", killed.getName()))); + event.setCancelled(true); + } + } + } + + + @EventHandler + public void onQuit(PlayerQuitEvent event) { + if (ArcadeAPI.inArcadeMatch(event.getPlayer().getUniqueId())) { + arcadeManager.endMatch(event.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void onKick(PlayerKickEvent event) { + if (ArcadeAPI.inArcadeMatch(event.getPlayer().getUniqueId())) { + arcadeManager.endMatch(event.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void onDeath(PlayerDeathEvent event) { + Player killer = event.getEntity().getKiller(); + if (ArcadeAPI.inArcadeMatch(event.getEntity().getUniqueId())) { + arcadeManager.endMatch(event.getEntity().getUniqueId()); + killer.sendMessage(CC.translate(Language.MATCH_KILLED.getMessage().replace("{victim}", event.getEntity().getName()))); + Bukkit.broadcastMessage(Language.MATCH_KILLED_BROADCAST.getMessage().replace("{killer}", killer.getName()).replace("{killed}", event.getEntity().getName())); + CooldownUtils.registerCooldown(killer, new GracePeriod("arcadeGracePeriod", 30)); + + } + } + + @EventHandler + public void onTeleport(PlayerTeleportEvent event) { + if (!event.getTo().getWorld().getName().equals(ArcadeAPI.WORLD_NAME) && ArcadeAPI.inArcadeMatch(event.getPlayer().getUniqueId())) { + arcadeManager.endMatch(event.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void teleportTo(PlayerTeleportEvent event) { + if (event.getTo().getWorld().getName().equals(ArcadeAPI.WORLD_NAME)) { + if(event.getPlayer().hasPermission("cranked.admin") || StaffPlugin.getInstance().getStaffManager().isPlayerInStaffMode(event.getPlayer())) { + event.getPlayer().setFlying(true); + event.getPlayer().setAllowFlight(true); + return; + } + event.getPlayer().setFlying(false); + event.getPlayer().setAllowFlight(false); + } + } + + @EventHandler + public void teleportToNoSet(PlayerTeleportEvent event) { + if (event.getTo().getWorld().getName().equals(ArcadeAPI.WORLD_NAME) && event.getCause() != PlayerTeleportEvent.TeleportCause.ENDER_PEARL && !event.getPlayer().hasPermission("cranked.admin")) { + if (CrankedArmorAPI.getCurrentArmorSet(event.getPlayer()) == null && !StaffPlugin.getInstance().getStaffManager().isPlayerInStaffMode(event.getPlayer())) { + event.setCancelled(true); + Language.TELEPORT_NO_SET.send(event.getPlayer()); + } + } + } + + @EventHandler + public void onFly(PlayerToggleFlightEvent event) { + if (!event.getPlayer().getWorld().getName().equals(ArcadeAPI.WORLD_NAME)) return; + if (event.getPlayer().hasPermission("cranked.admin")) return; + event.setCancelled(true); + } + + @EventHandler (priority = EventPriority.LOWEST) + public void onCommand(PlayerCommandPreprocessEvent event) { + if (!event.getPlayer().getWorld().getName().equals(ArcadeAPI.WORLD_NAME)) return; + Player player = event.getPlayer(); + if (player.hasPermission("cranked.admin")) return; + if(StaffPlugin.getInstance().getStaffManager().isPlayerInStaffMode(event.getPlayer())) return; + + String command = event.getMessage().replace("/", ""); + List whitelistedCommands = Language.WHITELISTED_COMMANDS.getValuesAsList(); + + if (whitelistedCommands.stream().anyMatch(command::startsWith)) return; + + event.setCancelled(true); + Language.BLACKLISTED_COMMAND.send(player); + } + +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/listeners/SignListener.java b/Arcade/src/main/java/net/crankedpvp/arcade/listeners/SignListener.java new file mode 100644 index 0000000..e590f73 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/listeners/SignListener.java @@ -0,0 +1,72 @@ +package net.crankedpvp.arcade.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import net.md_5.bungee.api.ChatColor; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.block.BlockState; +import org.bukkit.block.Sign; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +public class SignListener implements Listener { + + @EventHandler + public void onSign(SignChangeEvent e) { + int currentLine = 0; + for (String line : e.getLines()) { + if (line.equalsIgnoreCase("[Elevator]") && !e.getPlayer().isOp()) { + e.setCancelled(true); + return; + } + if (line.equalsIgnoreCase("[Elevator]")) { + if (currentLine < 3) { + if (e.getLine(currentLine + 1).equalsIgnoreCase("Up")) { + e.setLine(0, ""); + e.setLine(1, ChatColor.translateAlternateColorCodes('&', "&9[Elevator]")); + e.setLine(2, ChatColor.translateAlternateColorCodes('&', "Up")); + e.setLine(3, ""); + } else { + e.getBlock().breakNaturally(); + e.getPlayer().sendMessage(CC.translate("&cInvalid Direction!")); + } + } + } + currentLine++; + } + } + + @EventHandler + public void onInteract(PlayerInteractEvent e) { + if(e.getAction() != Action.RIGHT_CLICK_BLOCK) return; + + if (e.getClickedBlock() != null) { + if (e.getClickedBlock().getState() instanceof Sign) { + Sign sign = (Sign) e.getClickedBlock().getState(); + + if (sign.getLine(1).equalsIgnoreCase(ChatColor.translateAlternateColorCodes('&', "&9[Elevator]"))) { + boolean teleported = false; + if (sign.getLine(2).equalsIgnoreCase("Up")) { + for (int i = e.getClickedBlock().getY() + 2; i < 256; i++) { + BlockState state = e.getClickedBlock().getWorld().getBlockAt(new Location(e.getClickedBlock().getWorld(), e.getClickedBlock().getX(), i, e.getClickedBlock().getZ())).getState(); + if (state instanceof Sign) { + if (((Sign) state).getLine(1).equalsIgnoreCase(ChatColor.translateAlternateColorCodes('&', "&9[Elevator]"))) { + e.getPlayer().teleport(new Location(state.getWorld(), state.getLocation().getBlockX() + 0.5, state.getLocation().getBlockY(), state.getLocation().getBlockZ() + 0.5, e.getPlayer().getLocation().getYaw(), e.getPlayer().getLocation().getPitch())); + teleported = true; + break; + } + } + } + } + //if(!teleported) e.getPlayer().sendMessage(CC.translate("&cNo Elevator Sign found!")); + } + } + } + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/struct/ArcadeManager.java b/Arcade/src/main/java/net/crankedpvp/arcade/struct/ArcadeManager.java new file mode 100644 index 0000000..3aaade3 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/struct/ArcadeManager.java @@ -0,0 +1,91 @@ +package net.crankedpvp.arcade.struct; + +import lombok.Getter; +import net.crankedpvp.arcade.ArcadeAPI; +import net.crankedpvp.arcade.language.Language; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Getter +public class ArcadeManager { + private List matches; + + public ArcadeManager() { + this.matches = new ArrayList<>(); + } + + public void endMatch(UUID uuid) { + ArcadeMatch arcadeMatch = getArcadeMatch(uuid); + matches.remove(arcadeMatch); + Player player1 = Bukkit.getPlayer(arcadeMatch.getPlayers().getLeft()); + Player player2 = Bukkit.getPlayer(arcadeMatch.getPlayers().getRight()); + if (player1.isOnline()) { + Language.MATCH_ENDED.send(player1); + } + if (player2.isOnline()) { + Language.MATCH_ENDED.send(player2); + } + + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (!player.canSee(player1)) player.showPlayer(player1); + if (!player.canSee(player2)) player.showPlayer(player2); + if(!EssentialsUtils.isVanished(player)) { + if(!player1.canSee(player)) player1.showPlayer(player); + if(!player2.canSee(player)) player2.showPlayer(player); + } + } + + } + + public void startMatch(UUID uuid1, UUID uuid2) { + matches.add(new ArcadeMatch(uuid1, uuid2)); + Player player1 = Bukkit.getPlayer(uuid1); + Player player2 = Bukkit.getPlayer(uuid2); + String msgKiller = Language.MATCH_STARTED_KILLER.getMessage().replace("{victim}", player2.getName()); + String msgVictim = Language.MATCH_STARTED_VICTIM.getMessage().replace("{killer}", player1.getName()); + player1.sendMessage(CC.translate(msgKiller)); + player2.sendMessage(CC.translate(msgVictim)); + for (Player player : Bukkit.getWorld(ArcadeAPI.WORLD_NAME).getPlayers()) { + player.sendMessage(CC.translate(Language.MATCH_STARTED_BROADCAST.getMessage().replace("{player1}", player1.getName()).replace("{player2}", player2.getName()))); + } + + } + + public boolean inArcadeMatch(UUID uuid) { + for (ArcadeMatch arcadeMatch : matches) { + if (arcadeMatch.getPlayers().contains(uuid)) return true; + } + return false; + } + + public boolean inSameArcadeMatch(UUID uuid1, UUID uuid2) { + for (ArcadeMatch arcadeMatch : matches) { + if (arcadeMatch.getPlayers().contains(uuid1)) { + return arcadeMatch.getPlayers().contains(uuid2); + } + } + return false; + } + + public ArcadeMatch getArcadeMatch(UUID uuid) { + for (ArcadeMatch arcadeMatch : matches) { + if (arcadeMatch.getPlayers().contains(uuid)) return arcadeMatch; + } + return null; + } + + public void onDisable() { + for(ArcadeMatch arcadeMatch : matches) { + endMatch(arcadeMatch.getPlayers().getLeft()); + } + matches.clear(); + } + + +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/struct/ArcadeMatch.java b/Arcade/src/main/java/net/crankedpvp/arcade/struct/ArcadeMatch.java new file mode 100644 index 0000000..288c312 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/struct/ArcadeMatch.java @@ -0,0 +1,15 @@ +package net.crankedpvp.arcade.struct; + +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.Pair; + +import java.util.UUID; + +@Getter +public class ArcadeMatch { + private final Pair players; + + public ArcadeMatch(UUID uuid1, UUID uuid2) { + players = new Pair<>(uuid1, uuid2); + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/tasks/ArcadeHiderTask.java b/Arcade/src/main/java/net/crankedpvp/arcade/tasks/ArcadeHiderTask.java new file mode 100644 index 0000000..72ec6d1 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/tasks/ArcadeHiderTask.java @@ -0,0 +1,28 @@ +package net.crankedpvp.arcade.tasks; + +import net.crankedpvp.arcade.ArcadeAPI; +import net.crankedpvp.arcade.ArcadePlugin; +import net.crankedpvp.arcade.struct.ArcadeMatch; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +public class ArcadeHiderTask extends BukkitRunnable { + @Override + public void run() { + for (ArcadeMatch arcadeMatch : ArcadePlugin.getInstance().getArcadeManager().getMatches()) { + Player player1 = Bukkit.getPlayer(arcadeMatch.getPlayers().getLeft()); + Player player2 = Bukkit.getPlayer(arcadeMatch.getPlayers().getRight()); + for (Player player : Bukkit.getWorld(ArcadeAPI.WORLD_NAME).getPlayers()) { + if (player.getUniqueId() == player1.getUniqueId() || player.getUniqueId() == player2.getUniqueId()) + continue; + if (player1.canSee(player)) player1.hidePlayer(player); + if (player2.canSee(player)) player2.hidePlayer(player); + if (player.hasPermission("arcade.see") || StaffPlugin.getInstance().getStaffManager().isPlayerInStaffMode(player)) continue; + if (player.canSee(player1)) player.hidePlayer(player1); + if (player.canSee(player2)) player.hidePlayer(player2); + } + } + } +} diff --git a/Arcade/src/main/java/net/crankedpvp/arcade/tasks/ArcadeRegionChecker.java b/Arcade/src/main/java/net/crankedpvp/arcade/tasks/ArcadeRegionChecker.java new file mode 100644 index 0000000..2f2b579 --- /dev/null +++ b/Arcade/src/main/java/net/crankedpvp/arcade/tasks/ArcadeRegionChecker.java @@ -0,0 +1,27 @@ +package net.crankedpvp.arcade.tasks; + +import net.crankedpvp.arcade.ArcadeAPI; +import net.crankedpvp.arcade.ArcadePlugin; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +public class ArcadeRegionChecker extends BukkitRunnable { + @Override + public void run() { + World world = Bukkit.getWorld(ArcadeAPI.WORLD_NAME); + if (world == null) return; + for (Player player : world.getPlayers()) { + + if (WorldGuardUtils.getRegionName(player.getLocation()).equals(ArcadeAPI.SAFEZONE_REGION_NAME) && ArcadeAPI.inArcadeMatch(player.getUniqueId())) { + ArcadePlugin.getInstance().getArcadeManager().endMatch(player.getUniqueId()); + if (CooldownUtils.isCooldownActive(player, "arcadeGracePeriod")) { + CooldownUtils.removeCooldown(player, "arcadeGracePeriod"); + } + } + } + } +} diff --git a/Arcade/src/main/resources/language.yml b/Arcade/src/main/resources/language.yml new file mode 100644 index 0000000..1675ab7 --- /dev/null +++ b/Arcade/src/main/resources/language.yml @@ -0,0 +1,16 @@ +ADMIN_RELOADING: "&3&l(!) &7Reloading configs now..." +ADMIN_RELOADED: "&3&l(!) &7Reloaded configs and other cool stuff. Took &3%took%ms&7." +CANT_PVP: "&d&lArcade &8➥ &7You cannot attack &d{victim} &7because they/you are in a different arcade match!" +MATCH_STARTED_KILLER: "&d&lArcade &8➥ &7You have started an arcade match against &d{victim}&7!" +MATCH_STARTED_VICTIM: "&d&lArcade &8➥ &d{killer} &7has started an arcade match against you!" +MATCH_ENDED: "&d&lArcade &8➥ &7Your arcade match has ended!" +MATCH_KILLED: "&d&lArcade &8➥ &7You have killed &d{victim} &7during an arcade match!" +MATCH_STARTED_BROADCAST: "&d&lArcade &8➥ &d{player1} &7started an arcade match against &d{player2}" +MATCH_KILLED_BROADCAST: "&d&lArcade &8➥ &d{killer} &7has killed &b{killed} &7in an arcade match! (&f&o/warp arcade&7)" +GRACE_PERIOD: "&d&lArcade &8➥ &7You cannot pvp while on arcade grace period, wait &f{time}&7!" +GRACE_PERIOD_OTHER: "&d&lArcade &8➥ &d{victim} &7is still on arcade grace period for &f{time}&7!" +TELEPORT_NO_SET: "&d&lArcade &8➥ &7You need to wear an armor set to enter the arcade warp!" +BLACKLISTED_COMMAND: "&d&lArcade &8➥ &7You are not allowed to type this command at warp arcade!" +WHITELISTED_COMMANDS: + - "bless" + - "apply" \ No newline at end of file diff --git a/Arcade/src/main/resources/plugin.yml b/Arcade/src/main/resources/plugin.yml new file mode 100644 index 0000000..27928b3 --- /dev/null +++ b/Arcade/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedArcade +main: net.crankedpvp.arcade.ArcadePlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/Armor/pom.xml b/Armor/pom.xml new file mode 100644 index 0000000..79512a2 --- /dev/null +++ b/Armor/pom.xml @@ -0,0 +1,70 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Armor + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + com.massivecraft + Factions + + + net.crankedpvp + Enchants + + + net.crankedpvp + Pets + + + net.crankedpvp + Arcade + + + net.crankedpvp + CagePvP + + + net.crankedpvp + Masks + + + net.crankedpvp + CombatLog + 1.0 + + + net.crankedpvp + StarItems + + + net.crankedpvp + LunarAPI + + + com.golfing.wineSpigot + winespigot + 1.0 + system + ${project.basedir}/../.lib/WineSpigot-V1.4.4.3.jar + + + + \ No newline at end of file diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/CrankedArmor.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/CrankedArmor.java new file mode 100644 index 0000000..713992b --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/CrankedArmor.java @@ -0,0 +1,134 @@ +package net.crankedpvp.crankedarmor; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedarmor.bard.BardEffectRegister; +import net.crankedpvp.crankedarmor.bard.cache.BardResistanceCache; +import net.crankedpvp.crankedarmor.bard.cache.BardStrengthCache; +import net.crankedpvp.crankedarmor.bard.tasks.CheckCachesTask; +import net.crankedpvp.crankedarmor.commands.AdminArmorSetCommand; +import net.crankedpvp.crankedarmor.commands.BardEffectsCommand; +import net.crankedpvp.crankedarmor.commands.DebugArmorSetCommand; +import net.crankedpvp.crankedarmor.commands.HeroicArmorSetCommand; +import net.crankedpvp.crankedarmor.language.LanguageHandler; +import net.crankedpvp.crankedarmor.listeners.*; +import net.crankedpvp.crankedarmor.listeners.bard.BardChangeHeldSlotListener; +import net.crankedpvp.crankedarmor.listeners.bard.BardClickSlotListener; +import net.crankedpvp.crankedarmor.managers.HeadlessAbilityManager; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedarmor.struct.config.ArmorConfigManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Arrays; +import java.util.stream.Collectors; + +@Getter +public class CrankedArmor extends JavaPlugin { + + @Getter + private static CrankedArmor instance; + + private BardEffectRegister bardEffectRegister; + //private MageEffectRegister mageEffectRegister; + private CommandManager commandManager; + private ArmorSetRegister armorSetRegister; + private LanguageHandler languageHandler; + private ArmorConfigManager armorConfigManager; + //private PirateFireEffectTask pirateFireEffectTask; + //private InfernoBleedTask infernoBleedTask; + //private RoverLanternTask roverLanternTask; + private HeadlessAbilityManager headlessAbilityManager; + + private BardStrengthCache bardStrengthCache; + private BardResistanceCache bardResistanceCache; + + @Override + public void onEnable() { + instance = this; + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + this.headlessAbilityManager = new HeadlessAbilityManager(); + this.armorSetRegister = new ArmorSetRegister(); + this.armorSetRegister.initialize(); + + this.bardEffectRegister = new BardEffectRegister(); + this.bardEffectRegister.initialize(); + + //this.mageEffectRegister = new MageEffectRegister(); + //this.mageEffectRegister.initialize(); + + this.armorConfigManager = new ArmorConfigManager(this); + this.armorConfigManager.setupFiles(); + + this.commandManager = new CommandManager(this); + this.registerCommandParameters(); + this.registerCommandCompletion(); + this.commandManager.register(new AdminArmorSetCommand(this)); + this.commandManager.register(new DebugArmorSetCommand()); + this.commandManager.register(new HeroicArmorSetCommand(this)); + this.commandManager.register(new BardEffectsCommand()); + + this.bardStrengthCache = new BardStrengthCache(); + this.bardResistanceCache = new BardResistanceCache(); + //this.commandManager.register(new MageEffectsCommand()); + //this.pirateFireEffectTask = new PirateFireEffectTask(); + //this.infernoBleedTask = new InfernoBleedTask(); + //this.roverLanternTask = new RoverLanternTask(); + + //this.registerTasks(); + + CheckCachesTask checkCachesTask = new CheckCachesTask(this); + checkCachesTask.runTaskTimer(this, 5 * 20L, 20L); + this.registerListeners(); + } + + @Override + public void onDisable() { + instance = null; + } + + private void registerListeners() { + this.getServer().getPluginManager().registerEvents(new PlayerListener(), this); + this.getServer().getPluginManager().registerEvents(new LootboxListener(), this); + this.getServer().getPluginManager().registerEvents(new HeroicUpgradeListener(this), this); + this.getServer().getPluginManager().registerEvents(new HeroicArmorDamageListener(), this); + this.getServer().getPluginManager().registerEvents(new HeroicWeaponDamageListener(), this); + this.getServer().getPluginManager().registerEvents(new AntiHarvesterListener(), this); + this.getServer().getPluginManager().registerEvents(new BardChangeHeldSlotListener(), this); + this.getServer().getPluginManager().registerEvents(new BardClickSlotListener(), this); + this.getServer().getPluginManager().registerEvents(new net.crankedpvp.crankedarmor.bard.listeners.PlayerListener(this), this); + //this.getServer().getPluginManager().registerEvents(new MageClickSlotListener(), this); + this.getServer().getPluginManager().registerEvents(this.headlessAbilityManager, this); + this.getServer().getPluginManager().registerEvents(new WeightedPvPListener(), this); + this.getServer().getPluginManager().registerEvents(new LowerDamageForNoSet(), this); + + + } + + /* + public void registerTasks() { + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, pirateFireEffectTask, 20L, 40L); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, infernoBleedTask, 20L, 20L); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, roverLanternTask, 20L, 1L); + + } + + */ + + + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(ArmorSet.class, argument -> { + ArmorSet armorSet = this.armorSetRegister.getArmorSetFromID(this.armorSetRegister.getArmorIDFromName(String.valueOf(argument))); + return new TypeResult(armorSet, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#sets", input -> this.armorSetRegister.getArmorSets().stream().map(ArmorSet::getID).collect(Collectors.toList())); + this.commandManager.getCompletionHandler().register("#boolean", input -> Arrays.asList("true", "false")); + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/CrankedArmorAPI.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/CrankedArmorAPI.java new file mode 100644 index 0000000..fb334f9 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/CrankedArmorAPI.java @@ -0,0 +1,269 @@ +package net.crankedpvp.crankedarmor; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.cache.ArmorSetCache; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.modifiers.AttributeModifier; +import net.crankedpvp.crankedutils.modifiers.ModifierType; +import net.crankedpvp.crankedutils.utils.Pair; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import net.crankedpvp.crankedutils.utils.cache.CachedPlayer; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.LeatherArmorMeta; + +import java.util.Collections; +import java.util.Objects; + +public class CrankedArmorAPI { + + public static boolean isHeroicArmorUpgrade(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasKey("crankedCustomItem")) return false; + return Objects.equals(nbtItem.getString("crankedCustomItem"), "heroicArmorUpgrade"); + } + + public static boolean isHeroicWeaponUpgrade(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasKey("crankedCustomItem")) return false; + return Objects.equals(nbtItem.getString("crankedCustomItem"), "heroicWeaponUpgrade"); + } + + public static boolean isHeroicHookUpgrade(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasKey("crankedCustomItem")) return false; + return Objects.equals(nbtItem.getString("crankedCustomItem"), "heroicHookUpgrade"); + } + + public static boolean isArmorHeroic(ItemStack itemStack) { + if(!isArmorSet(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getBoolean("heroic"); + } + + public static boolean isWeaponHeroic(ItemStack itemStack) { + if(!ItemUtils.isWeapon(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getBoolean("heroic"); + } + + public static boolean isArmorSet(ItemStack itemStack) { + if(!ItemUtils.isArmor(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound cosmicData = nbtItem.getCompound("cosmicData"); + if(cosmicData == null) return false; + return cosmicData.hasKey("armorSetType"); + } + + public static boolean isWeapon(ItemStack itemStack) { + if(!ItemUtils.isWeapon(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.hasKey("weaponType"); + } + + + + public static ArmorSet getArmorSetFromHeroicArmorUpgrade(ItemStack itemStack) { + if(!isHeroicArmorUpgrade(itemStack)) return null; + NBTItem nbtItem = new NBTItem(itemStack); + return CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID(nbtItem.getString("heroicType")); + } + + public static ArmorSet getArmorSetFromHeroicWeaponUpgrade(ItemStack itemStack) { + if(!isHeroicWeaponUpgrade(itemStack)) return null; + NBTItem nbtItem = new NBTItem(itemStack); + return CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID(nbtItem.getString("heroicType")); + } + + public static ArmorSet getArmorSetFromHeroicHookUpgrade(ItemStack itemStack) { + if(!isHeroicHookUpgrade(itemStack)) return null; + NBTItem nbtItem = new NBTItem(itemStack); + return CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID(nbtItem.getString("heroicType")); + } + + public static ArmorSet getSetTypeOnItem(ItemStack item) { + if (item == null || item.getType() == Material.AIR) + return null; + NBTItem wrapper = new NBTItem(item); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + return cosmicData.hasKey("armorSetType") ? ArmorSetRegister.getInstance().getArmorSetFromID(cosmicData.getString("armorSetType")) : null; + } + + public static boolean hasSetTypeOnItem(ItemStack item) { + if (item == null || item.getType() == Material.AIR) + return false; + NBTItem wrapper = new NBTItem(item); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + return cosmicData.hasKey("armorSetType"); + } + + public static ArmorSet getCurrentArmorSet(Player player) { + CachedPlayer cachedPlayer = CacheManager.getInstance().getCachedPlayer(player); + if (cachedPlayer == null) return null; + ArmorSetCache cache = (ArmorSetCache) cachedPlayer.getCache("armor_set"); + if (cache == null) return null; + return cache.getCurrentArmorSet(); + } + + public static ArmorSet getArmorSetFromWeaponInHand(Player player) { + if(player == null) return null; + if(ItemUtils.isAirOrNull(player.getItemInHand())) return null; + NBTItem nbtItem = new NBTItem(player.getItemInHand()); + NBTCompound nbtCompound = nbtItem.getCompound("cosmicData"); + if(nbtCompound == null) return null; + if(!nbtCompound.hasKey("weaponType")) return null; + return CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID(nbtCompound.getString("weaponType")); + } + + public static ArmorSet getArmorSetFromWeaponTypeOfItem(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return null; + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound nbtCompound = nbtItem.getCompound("cosmicData"); + if(nbtCompound == null) return null; + if(!nbtCompound.hasKey("weaponType")) return null; + return CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID(nbtCompound.getString("weaponType")); + } + + public static void refreshArmorSets(Player player) { + CachedPlayer armorSetPlayer = CrankedUtils.getInstance().getCacheManager().getCachedPlayer(player); + ArmorSetCache cache = (ArmorSetCache) (armorSetPlayer.hasCache("armor_set") ? armorSetPlayer.getCache("armor_set") : armorSetPlayer.registerCache(new ArmorSetCache(player))); + cache.getArmorSets().keySet().forEach(toRemove -> toRemove.onUnequip(player)); + cache.setCurrentArmorSet(null); + cache.getArmorSets().clear(); + + ItemStack[] armor = player.getInventory().getArmorContents(); + + for (ItemStack item : armor) { + if (item == null) continue; + if (item.getType() == Material.AIR) continue; + + if (hasSetTypeOnItem(item)) { + ArmorSet set = getSetTypeOnItem(item); + //cache.removeArmorSet(set); + //set.onUnequip(player); + cache.addArmorSet(set); + //set.onEquip(player); + } + + } + } + + public static boolean isPlayersWeaponSameAsSet(Player player) { + if(getArmorSetFromWeaponInHand(player) == null) return false; + if(getCurrentArmorSet(player) == null) return false; + return Objects.equals(getArmorSetFromWeaponInHand(player), getCurrentArmorSet(player)); + } + + public static int getArmorStrengthFromItem(Material material) { + switch(material) { + case GOLD_HELMET: + case GOLD_BOOTS: + case DIAMOND_HELMET: + case DIAMOND_BOOTS: + return 3; + case DIAMOND_CHESTPLATE: + case GOLD_CHESTPLATE: + case CHAINMAIL_CHESTPLATE: + return 8; + case DIAMOND_LEGGINGS: + case GOLD_LEGGINGS: + case CHAINMAIL_LEGGINGS: + return 6; + default: + return 0; + } + } + + public static ItemStack addWineArmorOverride(ItemStack itemStack, int amount) { + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("wine-armor-override", amount); + return nbtItem.getItem(); + } + + public static ItemStack heroifyArmor(ItemStack oldItemStack, ArmorSet armorSet) { + ItemStack itemStack = oldItemStack.clone(); + if(!(armorSet instanceof Heroic)) return itemStack; + itemStack.setDurability((short) 0); + Material material = itemStack.getType(); + itemStack.setType(Material.getMaterial("LEATHER_" + itemStack.getType().name().split("_")[1])); + LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemStack.getItemMeta().clone(); + leatherArmorMeta.setColor(((Heroic) armorSet).getColor()); + leatherArmorMeta.spigot().setUnbreakable(true); + leatherArmorMeta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE, ItemFlag.HIDE_ATTRIBUTES); + itemStack.setItemMeta(leatherArmorMeta); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setBoolean("heroic", true); + nbtItem.setInteger("wine-armor-override", getArmorStrengthFromItem(material)); + return addLore(nbtItem.getItem()).clone(); + } + + public static ItemStack heroifyWeapon(ItemStack itemStack, ArmorSet armorSet) { + return heroifyWeapon(itemStack); + } + + public static ItemStack heroifyHook(ItemStack itemStack, ArmorSet armorSet) { + return heroifyHook(itemStack); + } + + public static ItemStack heroifyWeapon(ItemStack itemStack) { + itemStack.setDurability((short) 0); + ItemBuilder itemBuilder = new ItemBuilder(itemStack); + itemBuilder.setUnbreakable(true); + itemBuilder.addItemFlag(ItemFlag.HIDE_ATTRIBUTES); + itemBuilder.addItemFlag(ItemFlag.HIDE_UNBREAKABLE); + itemBuilder.setType(Material.getMaterial("GOLD_" + itemStack.getType().name().split("_")[1])); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setBoolean("heroic", true); + ItemStack finalItem = addLore(nbtItem.getItem()); + Pair modifierTypePair = new Pair<>(ModifierType.ATTACK_DAMAGE, 7D); + return AttributeModifier.applyModifications(finalItem, Collections.singletonList(modifierTypePair)).clone(); + } + + public static ItemStack heroifyHook(ItemStack itemStack) { + itemStack.setDurability((short) 0); + ItemBuilder itemBuilder = new ItemBuilder(itemStack); + itemBuilder.setName(itemBuilder.getItemMeta().getDisplayName().replace("Diamond", "Golden")); + itemBuilder.setUnbreakable(true); + itemBuilder.addItemFlag(ItemFlag.HIDE_ATTRIBUTES); + itemBuilder.addItemFlag(ItemFlag.HIDE_UNBREAKABLE); + itemBuilder.setType(Material.getMaterial("GOLD_" + itemStack.getType().name().split("_")[1])); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setBoolean("heroic", true); + ItemStack finalItem = addLore(nbtItem.getItem()); + Pair modifierTypePair = new Pair<>(ModifierType.ATTACK_DAMAGE, 7D); + return AttributeModifier.applyModifications(finalItem, Collections.singletonList(modifierTypePair)).clone(); + } + + private static ItemStack addLore(ItemStack itemStack) { + ItemBuilder itemBuilder = new ItemBuilder(itemStack); + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&4This item is stronger than diamond."); + return itemBuilder.colorize().build(); + } + + public static boolean canUseBardEffects(Player player) { + if(StarItemsAPI.playerHasStarItem(player, "portablebard")) return true; + ArmorSet armorSet = getCurrentArmorSet(player); + if(armorSet == null) return false; + return armorSet.getID().equals("bard"); + } + + public static boolean canUseMageEffects(Player player) { + if(StarItemsAPI.playerHasStarItem(player, "portablemage")) return true; + ArmorSet armorSet = getCurrentArmorSet(player); + if(armorSet == null) return false; + return armorSet.getID().equals("mage"); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/CadiaKothArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/CadiaKothArmorSet.java new file mode 100644 index 0000000..b522c81 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/CadiaKothArmorSet.java @@ -0,0 +1,150 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.struct.*; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Monster; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class CadiaKothArmorSet extends ArmorSet implements Heroic, Weapon, Sword, Axe { + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 10; + + @Override + public String getName() { + return "KOTH"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &f&k;&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH&f&k;&r &f&lCap of the Hill &8«")) + .addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 5) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &f&k;&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH&f&k;&r &f&lShield of the Hill &8«")) + .addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 5) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &f&k;&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH&f&k;&r &f&lTrousers of the Hill &8«")) + .addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 5) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &f&k;&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH&f&k;&r &f&lShoes of the Hill &8«")) + .addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 5) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oAn armorset rewarded to only those")); + lore.add(CC.translate("&7&owho know throughout the pirate realm")); + lore.add(CC.translate("&7&oas Kings!")); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lEffects:")); + lore.add(CC.translate("&f • 50% chance to negate damage from mobs.")); + lore.add(CC.translate("&f • Permanent Speed III.")); + lore.add(CC.translate("&f • Receive " + (int) this.damagePercentDecreaseFromPlayers + "% less damage from players & mobs.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lAbilities:")); + lore.add(CC.translate("&fWhile wearing this set, you are able")); + lore.add(CC.translate("&fto capture outposts much faster!")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Monster) { + if(Math.random() < 0.5) { + super.getDamageHandler().cancelDamage(event, "KothMobEffect"); + } + } + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "KothSet"); + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(15, event, "KothWeaponPlayer"); + } else { + super.getDamageHandler().increaseDamage(20, event, "KothWeaponMobs"); + + } + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 3, "KothSpeed"); + + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "KothSpeed"); + + } + + @Override + public Material getDisplayMaterial() { + return Material.REDSTONE_TORCH_ON; + } + + @Override + public String getDisplayName() { + return "&f&k;&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH&f&k;&r"; + } + + @Override + public String getSwordName() { + return "&8» &f&k;&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH&f&k;&r &f&lPoker &8«"; + } + + @Override + public String getAxeName() { + return "&8» &f&k;&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH&f&k;&r &f&lScraper &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lKoth Effects:")); + lore.add(CC.translate("&f • Deal 15% more damage to players.")); + lore.add(CC.translate("&f • Deal 20% more damage to mobs.")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB( 255, 255, 255 ); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/DiabloArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/DiabloArmorSet.java new file mode 100644 index 0000000..83dcacf --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/DiabloArmorSet.java @@ -0,0 +1,164 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.cooldowns.cadia.DiabloDevourEfectCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedarmor.tasks.DiabloEffectTask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class DiabloArmorSet extends ArmorSet implements Heroic, Weapon, Sword { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 25; + + @ConfigValue + private double hiddenDamagePercentDecreaseFromPlayers = 20; + + @ConfigValue + private double diabloEffectChance = 3; + + @Override + public String getName() { + return "DIABLO"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &4&lDevil Horns &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &4&lChest of Fury &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &4&lFiery Pants of Hell &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &4&lDemon Drip &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oObtained from the depths of hell, the")); + lore.add(CC.translate("&7&ofull loadout of the devil himself!")); + lore.add(CC.translate("&7&oStolen by a demon, this set holds the")); + lore.add(CC.translate("&7&opower of corruption and illusions.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lEffects:")); + lore.add(CC.translate("&f • Immune to Silence.")); + lore.add(CC.translate("&f • Deal an extra " + (int) this.damagePercentIncreaseToPlayers + "% more damage.")); + lore.add(CC.translate("&f • Soul devour Ability")); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lAbility:")); + lore.add(CC.translate("&fSoul Devour ability &7&o(Summons bloody swords)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "DiabloSet"); + if (Math.random() < diabloEffectChance/100) { + if (CooldownUtils.isCooldownActive((Player) attacked, "diabloEffect")) return; + devourAbility((Player) attacked); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.hiddenDamagePercentDecreaseFromPlayers, event, this.getName() + " Set (Hidden)"); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.FIREBALL; + } + + @Override + public String getDisplayName() { + return "&4&lDiablo"; + } + + @Override + public String getSwordName() { + return "&8» &4&lNightblood &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lDiablo Effects:")); + lore.add(CC.translate("&f • Enjoy a 5% damage reduction.")); + lore.add(CC.translate("&f • Deal 5% more damage in lava.")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB(219, 0, 0); + } + + public void devourAbility(Player attacked) { + CooldownUtils.registerCooldown(attacked, new DiabloDevourEfectCooldown("diabloEffect", 90)); + DiabloEffectTask diabloEffectTask = new DiabloEffectTask(attacked, super.getDamageHandler()); + diabloEffectTask.runTaskTimer(CrankedArmor.getInstance(), 0, 100); + } + + @Override + public void onWeaponAttacked(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().reduceDamage(5, event, "DiabloWeapon"); + } + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + Location loc = new Location(attacker.getWorld(), attacker.getLocation().getX(), attacker.getLocation().clone().getY()-1, attacker.getLocation().getZ()); + if (loc.getBlock().isLiquid()) { + super.getDamageHandler().increaseDamage(5, event, "DiabloWeaponLava"); + } + } + } + } + + + diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/FortuneArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/FortuneArmorSet.java new file mode 100644 index 0000000..3b510d1 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/FortuneArmorSet.java @@ -0,0 +1,141 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class FortuneArmorSet extends ArmorSet implements Heroic, Weapon, Sword { + + @ConfigValue + private double damagePercentIncreaseToMobs = 20; + + @Override + public String getName() { + return "FORTUNE"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &e&lFortune Headband &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &e&lFortune Coat &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &e&lFortune Shorts &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &e&lFortune Slippers &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oAn armor set for those who are truly")); + lore.add(CC.translate("&7&oready for the grind and hustle in")); + lore.add(CC.translate("&7&obecoming successful!")); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lEffects:")); + lore.add(CC.translate("&f • Deal " + (int) this.damagePercentIncreaseToMobs + "% more damage to all mobs.")); + lore.add(CC.translate("&f • Gain 2x more EXP.")); + lore.add(CC.translate("&f • Immune to Purge.")); + lore.add(CC.translate("&f • Permanent Resistance II effect.")); + lore.add(CC.translate("&f • Permanent Haste III effect.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lAbility:")); + lore.add(CC.translate("&fWhile wearing this set, you can occasionally")); + lore.add(CC.translate("&fkill more than one mob off of a stack at once.")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (!(attacked instanceof Player)) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToMobs, event, "FortuneSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + } + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.DAMAGE_RESISTANCE, 2, "FortuneRes"); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.FAST_DIGGING, 3, "FortuneHaste"); + + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "FortuneRes"); + PotionEffectUtils.removePotionEffect(player, "FortuneHaste"); + + } + + @Override + public Material getDisplayMaterial() { + return Material.EXP_BOTTLE; + } + + @Override + public String getDisplayName() { + return "&e&lFortune"; + } + + @Override + public String getSwordName() { + return "&8» &e&lFortune Blade &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lFortune Effects:")); + lore.add(CC.translate("&f • Deal " + (int) this.damagePercentIncreaseToMobs + "% more damage to all mobs.")); + lore.add(CC.translate("&f • Gain 2x more EXP.")); + lore.add(CC.translate("&f • Immune to Purge.")); + lore.add(CC.translate("&f • Permanent Resistance II effect.")); + lore.add(CC.translate("&f • Permanent Haste III effect.")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB( 236, 255, 27 ); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/InfernoArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/InfernoArmorSet.java new file mode 100644 index 0000000..963455a --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/InfernoArmorSet.java @@ -0,0 +1,218 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Axe; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedarmor.tasks.InfernoBleedTask; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedutils.utils.BlockUtil; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; + +public class InfernoArmorSet extends ArmorSet implements Heroic, Weapon, Axe { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 20; + @ConfigValue + private int cobWebDuration = 5; + @ConfigValue + private int cobWebRadius = 6; + @ConfigValue + private double cobWebAbilityChance = 3; + @ConfigValue + private double pushBackAbilityChance = 3; + @ConfigValue + private int cooldown = 90; + + @ConfigValue + private double hiddenDamagePercentDecreaseFromPlayers = 20; + + @Override + public String getName() { + return "INFERNO"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &6&lCap of Ignition &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &6&lVest of Combustion &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &6&lScorched Leggings &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &6&lPyromaniac Boots &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oOne of the most sacred pieces of armor")); + lore.add(CC.translate("&7&ohanded down to those who are worthy")); + lore.add(CC.translate("&7&oof yielding the power of the sun!")); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lEffects:")); + lore.add(CC.translate("&f • Permanent Fire Resistance I effect.")); + lore.add(CC.translate("&f • Deal an extra " + (int) this.damagePercentIncreaseToPlayers + "% damage to all enemies.")); + lore.add(CC.translate("&f • Amaterasu ability.")); + lore.add(CC.translate("&f • Heatwave ability.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lAbilities:")); + lore.add(CC.translate("&fAmaterasu ability &7&o(Summons cob webs and bleed effect)")); + lore.add(CC.translate("&fHeatwave ability &7&o(Pushes back opponents and damages them)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "InfernoSet"); + if(super.isOnCooldown((Player) attacked)) return; + if (Math.random() < cobWebAbilityChance/100) { + super.registerCooldown((Player) attacked, this.cooldown); + cobWebAbility((Player) attacked); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.hiddenDamagePercentDecreaseFromPlayers, event, this.getName() + " Set (Hidden)"); + if(super.isOnCooldown(attacked)) return; + if (Math.random() < pushBackAbilityChance/100) { + super.registerCooldown(attacked, this.cooldown); + pushAwayAbility(attacked.getLocation(), attacker, 1.7); + } + } + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.FIRE_RESISTANCE, 1, "InfernoFireRes"); + + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "InfernoFireRes"); + + } + + @Override + public Material getDisplayMaterial() { + return Material.BLAZE_ROD; + } + + @Override + public String getDisplayName() { + return "&6&lInferno"; + } + + @Override + public String getAxeName() { + return "&8» &6&lSuper Hot Fire &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lInferno Effects:")); + lore.add(CC.translate("&f • Enjoy a 5% damage reduction from enemies.")); + lore.add(CC.translate("&f • Deal an extra 5% damage to all enemies.")); + return lore; + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "InfernoWeapon"); + } + } + + @Override + public void onWeaponAttacked(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().reduceDamage(5, event, "InfernoWeapon"); + } + } + + @Override + public Color getColor() { + return Color.fromRGB( 238, 136, 0 ); + } + + public void cobWebAbility(Player player) { + for(Player target : PVPUtils.getNearbyEnemyPlayersExceptPlayer(player, cobWebRadius)) { + Location location = target.getLocation(); + + Block underBlock = location.clone().getBlock(); + + Material underBlockType = underBlock.getType(); + + boolean setAtLeastOne = false; + if(underBlockType == Material.AIR) { + BlockUtil.setBlockFast(underBlock, Material.WEB.getId(), (byte) 0, false); + InfernoBleedTask.bleedPlayers.add(player.getUniqueId()); + setAtLeastOne = true; + } + if(setAtLeastOne) { + Bukkit.getScheduler().runTaskLater(CrankedPets.getInstance(), () -> { + if (underBlock.getType() == Material.WEB) { + BlockUtil.setAir(underBlock, true); + InfernoBleedTask.bleedPlayers.remove(player.getUniqueId()); + } + }, cobWebDuration * 20L); + + } + } + } + + + + public void pushAwayAbility( Location center, Entity entity, double speed) { + final Vector unitVector = entity.getLocation().toVector().subtract(center.toVector()); + if (unitVector.length() != 0.0) { + unitVector.normalize(); + } + entity.setVelocity(unitVector.multiply(speed)); + super.getDamageHandler().damage((LivingEntity) entity, 5, "InfernoPushback"); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/LeviathanArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/LeviathanArmorSet.java new file mode 100644 index 0000000..f43eea9 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/LeviathanArmorSet.java @@ -0,0 +1,160 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Axe; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class LeviathanArmorSet extends ArmorSet implements Heroic, Weapon, Axe { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 15; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 5; + @ConfigValue + private double dodgeChance = 5; + @ConfigValue + private int cooldown = 7; + + @Override + public String getName() { + return "LEVIATHAN"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &3&lWater Proof Goggles &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &3&lSoaked Vest &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &3&lEmpowered Legs of Water &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &3&lWater Dripped Shoes &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oAn armorset that is used to")); + lore.add(CC.translate("&7&oconquer and win battles all")); + lore.add(CC.translate("&7&othroughout the ocean!")); + lore.add(CC.translate("")); + lore.add(CC.translate("&3&lEffects:")); + lore.add(CC.translate("&f • +4 Max Hearts.")); + lore.add(CC.translate("&f • Deal an extra " + (int) this.damagePercentIncreaseToPlayers + "% damage.")); + lore.add(CC.translate("&f • Enjoy a " + (int) this.damagePercentDecreaseFromPlayers + "% damage reduction.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&3&lAbility:")); + lore.add(CC.translate("&f5% To dodge Incoming Hits")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "LeviathanSet"); + } + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + if (!ItemUtils.isAirOrNull(((Player) attacked).getItemInHand()) && ((Player) attacked).getItemInHand().getType().name().endsWith("_SWORD")) { + super.getDamageHandler().increaseDamage(5, event, "LeviWeaponEnemySword"); + } + Location loc = new Location(attacker.getWorld(), attacker.getLocation().getX(), attacker.getLocation().clone().getY()-1, attacker.getLocation().getZ()); + if (loc.getBlock().isLiquid()) { + super.getDamageHandler().reduceDamage(10, event, "LeviWeaponWater"); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "LeviathanSet"); + } + if(super.isOnCooldown(attacked)) return; + if (Math.random() < dodgeChance/100) { + super.registerCooldown(attacked, this.cooldown); + super.getDamageHandler().cancelDamage(event, "LeviCancelDMG"); + } + } + + public void onEquip(Player player) { + PotionEffectUtils.addExtraPotionEffect(player, PotionEffectType.HEALTH_BOOST, 2, "LeviathanExtraHealth"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "LeviathanExtraHealth"); + } + + + + @Override + public Material getDisplayMaterial() { + return Material.CLAY; + } + + @Override + public String getDisplayName() { + return "&3&lLeviathan"; + } + + @Override + public String getAxeName() { + return "&8» &3&lAqua Axe &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&3&lLeviathan Effects:")); + lore.add(CC.translate("&f • Deal 10% more damage in water.")); + lore.add(CC.translate("&f • Deal 5% more damage to players holding swords.")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB( 0, 194, 225 ); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/MarksmanArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/MarksmanArmorSet.java new file mode 100644 index 0000000..a83b190 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/MarksmanArmorSet.java @@ -0,0 +1,134 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Bow; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class MarksmanArmorSet extends ArmorSet implements Heroic, Weapon, Bow { + + @ConfigValue + private double bowDamagePercentIncreaseToPlayers = 30; + @ConfigValue + private double bowDamagePercentDecreaseFromPlayers = 25; + + @Override + public String getName() { + return "MARKSMAN"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &a&lMarksman Glasses &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &a&lMarksman Vest &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &a&lMarksman Pants &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &a&lMarksman Boots &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oHave an eye of an eagle? Become a")); + lore.add(CC.translate("&7&omarksman with this armor set.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&a&lEffects:")); + lore.add(CC.translate("&f • Permanent Speed III effect.")); + lore.add(CC.translate("&f • Bows deal " + (int) this.bowDamagePercentIncreaseToPlayers + "% extra damage.")); + lore.add(CC.translate("&f • Enemy bows deal " + (int) this.bowDamagePercentDecreaseFromPlayers + "% less damage.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&a&lAbility:")); + lore.add(CC.translate("&fWhile wearing this set, you can go into")); + lore.add(CC.translate("&fa Spectral mode becoming invincible!")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + } + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 3, "MarksmanSet"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "MarksmanSet"); + } + + @Override + public Material getDisplayMaterial() { + return Material.BOW; + } + + @Override + public String getDisplayName() { + return "&a&lMarksman"; + } + + @Override + public String getBowName() { + return "&8» &a&lMarksman Sniper &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&a&lMarksman Effects:")); + lore.add(CC.translate("&f • Enemy bows deal 25% less damage.")); + lore.add(CC.translate("&f • Marksman Bow gives 30% extra bow damage.")); + lore.add(CC.translate("&f • Tag players and deal more damage.")); + return lore; + } + + + @Override + public Color getColor() { + return Color.fromRGB( 143, 255, 36 ); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/OrcArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/OrcArmorSet.java new file mode 100644 index 0000000..035f0f6 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/OrcArmorSet.java @@ -0,0 +1,148 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Axe; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class OrcArmorSet extends ArmorSet implements Heroic, Weapon, Axe { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 10; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 10; + + + @ConfigValue + private final double orcAbilityChance = 3; + + @ConfigValue + private final int orcAbilityDuration = 5; + + @Override + public String getName() { + return "ORC"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &b&lOrc Headgear &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &b&lOrc Thornplate &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &b&lOrc Kneeguard &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &b&lOrc Fuzzy Boots &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oBecome enraged like a beast while wearing")); + lore.add(CC.translate("&7&othis set for those who play both passive")); + lore.add(CC.translate("&7&oand aggressive.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lEffects:")); + lore.add(CC.translate("&f • Deal an extra " + (int) this.damagePercentIncreaseToPlayers + "% damage to enemies.")); + lore.add(CC.translate("&f • Enjoy a " + (int) this.damagePercentDecreaseFromPlayers + "% damage reduction.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lAbility:")); + lore.add(CC.translate("&fWhile wearing this set, you can become")); + lore.add(CC.translate("&fEnraged and receive a great amount of")); + lore.add(CC.translate("&fstrength for a limited period of time.")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "OrcSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "OrcSet"); + } + + if (Math.random() < orcAbilityChance / 100) { + PotionEffectUtils.addPotionEffect(attacked, PotionEffectType.INCREASE_DAMAGE, 3, "OrcAbility", orcAbilityDuration); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.EMERALD; + } + + @Override + public String getDisplayName() { + return "&b&lOrc"; + } + + @Override + public String getAxeName() { + return "&8» &b&lOrc Axe &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lOrc Effects:")); + lore.add(CC.translate("&f • Deal 10% more durability damage.")); + lore.add(CC.translate("&f • Deal 5% more damage to players holding axes.")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB(0, 255, 253); + } + + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "OrcWeapon"); + } + + + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/PirateArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/PirateArmorSet.java new file mode 100644 index 0000000..1e315ac --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/PirateArmorSet.java @@ -0,0 +1,155 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.cooldowns.cadia.PiratePhoenixCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedarmor.tasks.PirateFireEffectTask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class PirateArmorSet extends ArmorSet implements Heroic, Weapon, Sword { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 20; + + + @Override + public String getName() { + return "PIRATE"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &c&lPirate Cap &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &c&lPirate Coat &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &c&lPirate Pantaloons &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &c&lPirate Boots &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oOne of the most deadly set for")); + lore.add(CC.translate("&7&othose who are aggressive damage")); + lore.add(CC.translate("&7&odealers!")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lEffects:")); + lore.add(CC.translate("&f • Deal an extra " + (int) this.damagePercentIncreaseToPlayers + "% damage to all enemies.")); + lore.add(CC.translate("&f • Look cool with a neat fire effect.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lAbility:")); + lore.add(CC.translate("&fWhile wearing this set, you can become")); + lore.add(CC.translate("&fa Phoenix and go up to full health!")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "LeviathanSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacked.getHealth() - event.getFinalDamage() <= 0) { + if (CooldownUtils.isCooldownActive(attacked, "piratePhoenix")) { + attacked.sendMessage(CC.translate("&c&l* PIRATE PHOENIX ON COOLDOWN &7[" + CooldownUtils.getFormattedCooldown(attacked, "piratePhoenix") + "&7] &c&l*")); + return; + } + ArmorSet attackerSet = CrankedArmorAPI.getCurrentArmorSet(attacked); + if (attackerSet != null && attackerSet.getID().equals("rover") && CrankedArmorAPI.isPlayersWeaponSameAsSet((Player) attacker)) { + attacked.sendMessage(CC.translate("&f&l* ROVER WEAPON &7[Blocked Phoenix] &f&l*")); + + return; + } + CooldownUtils.registerCooldown(attacked, new PiratePhoenixCooldown("piratePhoenix", 600)); + attacked.setHealth(attacked.getMaxHealth()); + attacked.playSound(attacked.getLocation(), Sound.ENDERDRAGON_GROWL, 2, 2); + attacked.sendMessage(""); + attacked.sendMessage(CC.translate("&c&l* PIRATE PHOENIX &7[10m Cooldown] &c&l*")); + attacked.sendMessage(CC.translate("&7(( You have healed back to full health! ))")); + attacked.sendMessage(""); + for (Player other : PVPUtils.getNearbyEnemyPlayersExceptPlayer(attacked, 8)) { + other.sendMessage(CC.translate("&c&l* PIRATE PHOENIX &7[" + attacked.getName() + "&7] &c&l*")); + } + } + + } + + public void onEquip(Player player) { + PirateFireEffectTask.firePlayers.add(player.getUniqueId()); + } + + public void onUnequip(Player player) { + PirateFireEffectTask.firePlayers.remove(player.getUniqueId()); + } + + @Override + public Material getDisplayMaterial() { + return Material.FLINT_AND_STEEL; + } + + @Override + public String getDisplayName() { + return "&c&lPirate"; + } + + @Override + public String getSwordName() { + return "&8» &c&lPirate Scythe &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lPirate Effects:")); + lore.add(CC.translate("&f • Have a 15% chance to negate Holy White Scrolls.")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB( 253, 42, 38 ); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/RavagerArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/RavagerArmorSet.java new file mode 100644 index 0000000..2480661 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/RavagerArmorSet.java @@ -0,0 +1,175 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class RavagerArmorSet extends ArmorSet implements Heroic, Weapon, Sword { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 15; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 10; + @ConfigValue + private double ravagerAbilityChance = 7; + @ConfigValue + private double antiBlockPlaceChance = 5; + @ConfigValue + private int antiBlockPlaceDuration = 5; + + public static List antiBlockPlace = new ArrayList<>(); + + @Override + public String getName() { + return "RAVAGER"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &9&lScratch Resistant Goggles &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &9&lOversized Trench Coat &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &9&lLousy Trousers &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &9&lSteel Toed Galoshes &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oAn armorset destined to ravage all of those")); + lore.add(CC.translate("&7&owho dare not wear armor worthy of battle.")); + lore.add(CC.translate("&7&oLet it be know that even the mightiest")); + lore.add(CC.translate("&7&oof explosions cannot best me.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&9&lEffects:")); + lore.add(CC.translate("&f • Deal an extra " + (int) this.damagePercentIncreaseToPlayers + "% damage to all enemies.")); + lore.add(CC.translate("&f • Deal an extra 25% more damage to players not in Armor Sets.")); + lore.add(CC.translate("&f • Enjoy a 15% damage reduction when in water.")); + lore.add(CC.translate("&f • Enjoy a " + (int) this.damagePercentDecreaseFromPlayers + "% damage reduction when not in water.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&9&lAbility:")); + lore.add(CC.translate("&fRavaged Absorption ability &7&o(Resistance II temporarily in claim)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "RavagerArmorSet"); + if (CrankedArmorAPI.getCurrentArmorSet((Player) attacked) == null) { + super.getDamageHandler().increaseDamage(25, event, "RavagerArmorSetNoArmorset"); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + Location loc = new Location(attacker.getWorld(), attacker.getLocation().getX(), attacker.getLocation().clone().getY()-1, attacker.getLocation().getZ()); + if (loc.getBlock().isLiquid()) { + super.getDamageHandler().reduceDamage(15, event, "RavagerArmorSetWater"); + } else { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "RavagerArmorSet"); + } + } + if (Math.random() < ravagerAbilityChance/100) { + if (FactionUtils.isInsideOwnFaction(attacked)) { + PotionEffectUtils.addPotionEffect(attacked, PotionEffectType.DAMAGE_RESISTANCE, 2, "RavagerAbility", 5); + } + } + } + + @Override + public Material getDisplayMaterial() { + return Material.GOLDEN_CARROT; + } + + @Override + public String getDisplayName() { + return "&9&lRavager"; + } + + @Override + public String getSwordName() { + return "&8» &9&lRavager's Wraith &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&9&lRavager Effects:")); + lore.add(CC.translate("&f • Deal 5% more damage to players holding blocks.")); + lore.add(CC.translate("&f • Chance to disable players from placing blocks temporarily.")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB( 34, 166, 255 ); + } + + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + if (ItemUtils.isAirOrNull(((Player) attacked).getItemInHand())) return; + if (((Player) attacked).getItemInHand().getType().isBlock()) { + super.getDamageHandler().increaseDamage(5, event, "RavagerWeapon"); + } + if (Math.random() < antiBlockPlaceChance) { + if (antiBlockPlace.contains(attacked.getUniqueId())) return; + antiBlockPlace.add(attacked.getUniqueId()); + attacked.sendMessage(CC.translate("&9&l* RAVAGER SWORD ANTI BLOCK PLACE &7[5s] &9&l*")); + Bukkit.getScheduler().runTaskLaterAsynchronously(CrankedArmor.getInstance(), ()-> { + antiBlockPlace.remove(attacked.getUniqueId()); + }, antiBlockPlaceDuration* 20L); + } + } + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/RoverArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/RoverArmorSet.java new file mode 100644 index 0000000..245cd0e --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/RoverArmorSet.java @@ -0,0 +1,160 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedarmor.tasks.RoverLanternTask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class RoverArmorSet extends ArmorSet implements Heroic, Weapon, Sword { + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 20; + @ConfigValue + private double damagePercentIncreaseToPlayers = 25; + @ConfigValue + private double lanternEffectChance = 3; + @ConfigValue + private int lanternEffectDuration = 5; + @ConfigValue + private int cooldown = 90; + + @Override + public String getName() { + return "ROVER"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &f&lRover Helmet &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &f&lRover Chestplate &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &f&lRover Leggings &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &f&lRover Boots &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oAn armorset for those who prefer")); + lore.add(CC.translate("&7&oto play passively while making you")); + lore.add(CC.translate("&7&olook confident.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lEffects:")); + lore.add(CC.translate("&f • Enjoy a " + (int) this.damagePercentDecreaseFromPlayers + "% damage reduction from enemies.")); + lore.add(CC.translate("&f • Walk around with confidence.")); + lore.add(CC.translate("&f • Spiritual Damage Ability.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lAbility:")); + lore.add(CC.translate("&fSpiritual Damage ability &7&o(Summons a heat seeking lantern)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + if (RoverLanternTask.lanterned.containsKey(attacked.getUniqueId())) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "LanternExtraDamage"); + } + if (Math.random() < lanternEffectChance/100) { + if (RoverLanternTask.lanterned.containsKey(attacked.getUniqueId())) return; + if(super.isOnCooldown((Player) attacked)) return; + super.registerCooldown((Player) attacked, this.cooldown); + Location loc = attacked.getLocation().add(0, 2, 0); + ArmorStand armorStand = (ArmorStand) attacked.getWorld().spawnEntity(loc, EntityType.ARMOR_STAND); + armorStand.setVisible(false); + armorStand.setGravity(false); + armorStand.setHelmet(new ItemStack(Material.SEA_LANTERN)); + RoverLanternTask.lanterned.put(attacked.getUniqueId(), armorStand); + Bukkit.getScheduler().runTaskLaterAsynchronously(CrankedArmor.getInstance(), ()-> { + RoverLanternTask.stop(attacked.getUniqueId()); + }, lanternEffectDuration* 20L); + } + + } + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "RoverSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "RoverSet"); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.QUARTZ; + } + + @Override + public String getDisplayName() { + return "&f&lRover"; + } + + @Override + public String getSwordName() { + return "&8» &f&lRover Blade &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lRover Effects:")); + lore.add(CC.translate("&f • Deal 10% more damage to enemies.")); + lore.add(CC.translate("&f • 100% chance to block enemy Phoenix.")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB( 255, 255, 255 ); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/WardenArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/WardenArmorSet.java new file mode 100644 index 0000000..ab77f53 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cadia/WardenArmorSet.java @@ -0,0 +1,141 @@ +package net.crankedpvp.crankedarmor.armorsets.cadia; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Axe; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class WardenArmorSet extends ArmorSet implements Heroic, Weapon, Axe { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 10; + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 20; + + @ConfigValue + private double lockdownAbilityChance = 3; + + @Override + public String getName() { + return "WARDEN"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8» &e&lWarden Riot Helmet &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8» &e&lWarden Tac Vest &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8» &e&lWarden Khakis &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8» &e&lWarden Boots &8«")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oA strict yet intense armor set witholding")); + lore.add(CC.translate("&7&othe power of the entire facility.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lEffects:")); + lore.add(CC.translate("&f • Deal an extra " + (int) this.damagePercentIncreaseToPlayers + "% more damage.")); + lore.add(CC.translate("&f • Enjoy a " + (int) this.damagePercentDecreaseFromPlayers + "% damage reduction.")); + lore.add(CC.translate("&f • Immune to Dimensional Rift Ability")); + lore.add(CC.translate("&f • Lockdown Ability")); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lAbility:")); + lore.add(CC.translate("&fSpawn a 6x6 Cage to force close quarter")); + lore.add(CC.translate("&fcombat against your foes and deal 1.5x more")); + lore.add(CC.translate("&fdamage for a limited time")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, this.getName() + " Set"); + + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, this.getName() + " Set"); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.IRON_BARDING; + } + + @Override + public String getDisplayName() { + return "&e&lWarden"; + } + + @Override + public String getAxeName() { + return "&8» &e&lWarden Baton &8«"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lWarden Effects:")); + lore.add(CC.translate("&f • Deal an extra 10% damage to all enemies")); + lore.add(CC.translate("&f • Chance to disable enemies Grappler's")); + return lore; + } + + @Override + public Color getColor() { + return Color.fromRGB(223, 227, 11); + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, this.getName() + " Weapon"); + } + } +} + + + diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicDragonSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicDragonSet.java new file mode 100644 index 0000000..1ab8fb8 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicDragonSet.java @@ -0,0 +1,164 @@ +package net.crankedpvp.crankedarmor.armorsets.cosmic; + + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class CosmicDragonSet extends ArmorSet implements Listener, Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 15; + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 20; + + + @Override + public String getName() { + return "Dragon"; + } + + public ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)).setName(CC.translate("&e&lDecapitated Dragon Skull")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)).setName(CC.translate("&e&lFiery Chestplate of Dragons")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)).setName(CC.translate("&e&lScorched Leggings of Dragons")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)).setName(CC.translate("&e&lDragon Slayer Battle Boots")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&e&lDragon Effects")); + message.add(CC.translate("&e • &fDeal +15% damage to enemies")); + message.add(CC.translate("&e • &fEnemies deal 15% less damage to you")); + message.add(CC.translate("&e • &fImmune to slowness.")); + message.add(CC.translate("&e • &fChance to reflect silence")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oDid dragons even exist..?")); + lore.add(CC.translate("&7&oWait, do they still exist..?")); + lore.add(CC.translate("&7&oUnleash undeniable power with this set.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lDragon Effects")); + lore.add(CC.translate("&e • &fDeal +15% damage to enemies")); + lore.add(CC.translate("&e • &fEnemies deal 15% less damage to you")); + lore.add(CC.translate("&e • &fImmune to slowness.")); + lore.add(CC.translate("&e • &fChance to reflect silence")); + //lore.add(CC.translate("&7(&oRequires all 4 dragon set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "DragonSetIncrease"); + } + } + + @Override + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "DragonSetReduce"); + } + } + + public void onEquip(Player player) { + } + + public void onUnequip(Player player) { + } + + + @Override + public Material getDisplayMaterial() { + return Material.EYE_OF_ENDER; + } + + + @Override + public String getDisplayName() { + return "&e&lDragon"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lDragon Effects")); + lore.add(CC.translate("&e • &fDeal +10% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 dragon set items.&7)")); + return lore; + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "DragonWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(232, 220, 0); + } + + @Override + public String getSwordName() { + return "&e&lDragon Dagger &8✧"; + } + + + + @EventHandler + public void onPotionEffectInKothSet(PotionEffectAddEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = ((Player) event.getEntity()); + if (CrankedArmorAPI.getCurrentArmorSet(player) != null && Objects.equals(CrankedArmorAPI.getCurrentArmorSet(player), this)) { + if (PotionEffectUtils.getDebuffsList().contains(event.getEffect().getType())) + event.setCancelled(true); + } + } + + @Override + public int getWeight() { + return 8; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicKothSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicKothSet.java new file mode 100644 index 0000000..909a4cc --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicKothSet.java @@ -0,0 +1,183 @@ +package net.crankedpvp.crankedarmor.armorsets.cosmic; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class CosmicKothSet extends ArmorSet implements Listener, Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 20; + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 15; + + + @Override + public String getName() { + return "KOTH"; + } + + public ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)).setName(CC.translate("&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nHelmet&r")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)).setName(CC.translate("&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nChestplate&r")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)).setName(CC.translate("&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nLeggings&r")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)).setName(CC.translate("&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nBoots&r")) .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&lEffects")); + message.add(CC.translate("&b • &fDeal +20% damage to enemies")); + message.add(CC.translate("&b • &fEnemies deal 15% less damage to you")); + message.add(CC.translate("&b • &fPermanent Speed IV.")); + message.add(CC.translate("&b • &fAuto Bless.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oObtained from open the KOTH Lootbag.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&lEffects")); + lore.add(CC.translate("&b • &fDeal +20% damage to enemies")); + lore.add(CC.translate("&b • &fEnemies deal 15% less damage to you")); + lore.add(CC.translate("&b • &fPermanent Speed IV.")); + lore.add(CC.translate("&b • &fAuto Bless.")); + //lore.add(CC.translate("&7(&oRequires all 4 koth set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "KothSetIncrease"); + } + } + + @Override + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "KothSetReduce"); + } + } + + public void onEquip(Player player) { + PotionEffectUtils.bless(player); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "KothSet"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "KothSet"); + + } + + + @Override + public Material getDisplayMaterial() { + return Material.NETHER_STAR; + } + + + @Override + public String getDisplayName() { + return "&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r"; + } + + + @EventHandler + public void onPotionEffectInKothSet(PotionEffectAddEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = ((Player) event.getEntity()); + if (CrankedArmorAPI.getCurrentArmorSet(player) != null && Objects.equals(CrankedArmorAPI.getCurrentArmorSet(player), this)) { + if (PotionEffectUtils.getDebuffsList().contains(event.getEffect().getType())) + event.setCancelled(true); + } + } + + /* + @Override + public String getWeaponName() { + return "&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nScalpel&r &8✧"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oObtained from open the KOTH Lootbag.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&lEffects")); + lore.add(CC.translate("&b • &fDeal +10% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 koth set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "KothWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(255, 255, 255); + } + + @Override + public String getSwordName() { + return "&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nScalpel&r &8✧"; + } + + @Override + public int getWeight() { + return 10; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicPhantomSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicPhantomSet.java new file mode 100644 index 0000000..f4434a9 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicPhantomSet.java @@ -0,0 +1,171 @@ +package net.crankedpvp.crankedarmor.armorsets.cosmic; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class CosmicPhantomSet extends ArmorSet implements Weapon, Sword, Listener, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 10; + + + @Override + public String getName() { + return "PHANTOM"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&c&lPhantom Hood")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe fabled hood of the Phantom.")) + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&c&lPhantom Shroud")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe legendary shroud of the Phantom.")) + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&c&lPhantom Robeset")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe demonic robe of the Phantom.")) + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&c&lPhantom Sandals")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe silent sandals of the Phantom.")) + */ + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&c&lPhantom Effects")); + message.add(CC.translate("&c • &fDeal +20% damage to enemies.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oThe phantom awaits you as")); + lore.add(CC.translate("&7&oyour presence is necessary..")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lPhantom Effects")); + lore.add(CC.translate("&c • &fDeal +20% damage to enemies.")); + //lore.add(CC.translate("&7&o(Requires all 4 phantom items.)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "PhantomSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + + } + + @Override + public Material getDisplayMaterial() { + return Material.BLAZE_POWDER; + } + + @Override + public String getDisplayName() { + return "&c&lPhantom"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7An eerie blade designed to")); + lore.add(CC.translate("&7cut through the enemies.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lPhantom Effects")); + lore.add(CC.translate("&c • &fDeal +10% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 phantom set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "PhantomWeapon"); + } + + } + + @Override + public Color getColor() { + return org.bukkit.Color.fromRGB(255, 64, 64); + } + + + @Override + public String getSwordName() { + return "&c&lPhantom Scythe"; + } + + @Override + public int getWeight() { + return 1; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicTravelerSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicTravelerSet.java new file mode 100644 index 0000000..f82f08b --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicTravelerSet.java @@ -0,0 +1,177 @@ +package net.crankedpvp.crankedarmor.armorsets.cosmic; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Axe; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class CosmicTravelerSet extends ArmorSet implements Weapon, Axe, Listener, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 30; + + + @Override + public String getName() { + return "TRAVELER"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&5&lInterdimensional Hood")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe savage mask of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&5&lChestplate of Ad Infinitum")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe impermable chestplate of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&5&lTimeless Robes")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe cosy yet monstrous legs of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&5&lWarp Speed Sandals")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oBigfoot has nothing on these boots.")) + + */ + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&5&lTraveler Effects")); + message.add(CC.translate("&5 • &fDeal +30% damage to enemies.")); + message.add(CC.translate("&5 • &fTime Warp Ability")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oTravelling throughout galaxies")); + lore.add(CC.translate("&7&ois not an easy as it may seem..")); + lore.add(CC.translate("")); + lore.add(CC.translate("&5&lTraveler Effects")); + lore.add(CC.translate("&5 • &fDeal +30% damage to enemies.")); + lore.add(CC.translate("&5 • &fTime Warp Ability")); + //lore.add(CC.translate("&7&o(Requires all 4 yeti items.)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, this.getName() + "Set"); + } + } + + + @Override + public Material getDisplayMaterial() { + return Material.WATCH; + } + + @Override + public String getDisplayName() { + return "&5&lTraveler"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7The mythic, fabled magic axe")); + lore.add(CC.translate("&7with the impossible power to")); + lore.add(CC.translate("&7cut the very fabric of time")); + lore.add(CC.translate("")); + lore.add(CC.translate("&5&lTraveler Effects")); + lore.add(CC.translate("&5 • &fDeal +10% damage to all enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 yeti set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, this.getName() + "Weapon"); + } + + } + + + + @Override + public Color getColor() { + return Color.fromRGB(179, 47, 255); + } + + + @Override + public String getAxeName() { + return "&5&lTime Splitter"; + } + + @Override + public int getWeight() { + return 7; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicYetiSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicYetiSet.java new file mode 100644 index 0000000..3e2c148 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicYetiSet.java @@ -0,0 +1,181 @@ +package net.crankedpvp.crankedarmor.armorsets.cosmic; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Axe; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class CosmicYetiSet extends ArmorSet implements Weapon, Axe, Listener, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 12.5; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 10; + + + @Override + public String getName() { + return "YETI"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&b&lYeti Facemask")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe savage mask of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&b&lBloody Yeti Torso")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe impermable chestplate of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&b&lFuzzy Yeti Leggings")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe cosy yet monstrous legs of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&b&lBig-Yeti Boots")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oBigfoot has nothing on these boots.")) + + */ + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&b&lYeti Effects")); + message.add(CC.translate("&b • &fDeal +12.5% damage to enemies.")); + message.add(CC.translate("&b • &fEnemies deal 10% less damage to you.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oHidden amongst the icy depths")); + lore.add(CC.translate("&7&oof the antarctic mountains..")); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lYeti Effects")); + lore.add(CC.translate("&b • &fDeal +12.5% damage to enemies.")); + lore.add(CC.translate("&b • &fEnemies deal 10% less damage to you.")); + //lore.add(CC.translate("&7&o(Requires all 4 yeti items.)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "YetiSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "YetiSet"); + + } + + @Override + public Material getDisplayMaterial() { + return Material.SNOW_BALL; + } + + @Override + public String getDisplayName() { + return "&b&lYeti"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7A penetrating axe used by a Yeti")); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lYeti Effects")); + lore.add(CC.translate("&b • &fDeal +7.5% damage to enemies.")); + //lore.add(CC.translate("&7(&oRequires all 4 yeti set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "YetiWeapon"); + } + + } + + + + @Override + public Color getColor() { + return Color.fromRGB(0, 255, 255); + } + + + @Override + public String getAxeName() { + return "&b&lYeti Maul"; + } + + @Override + public int getWeight() { + return 2; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicYijkiSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicYijkiSet.java new file mode 100644 index 0000000..db195e8 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cosmic/CosmicYijkiSet.java @@ -0,0 +1,191 @@ +package net.crankedpvp.crankedarmor.armorsets.cosmic; + +import net.crankedpvp.crankedarmor.cooldowns.YijkiLightningCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class CosmicYijkiSet extends ArmorSet implements Weapon, Sword, Listener, Heroic, Weighable { + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 25; + + @ConfigValue + private double abilityChance = 3; + @ConfigValue + private int abilityCooldown = 60; + + + @Override + public String getName() { + return "YIJKI"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&f&lYijki Mask")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oYijki face mask.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&f&lYijki Torso")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe forbidden mantel of yijki.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&f&lFabled Robes of Yijki.")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe fabled robes of yijki.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&f&lYijki Footwraps")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oLight as feather, heavy as stone.")) + + */ + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&f&lYijki Effects")); + message.add(CC.translate("&f • &fEnemies deal 25% less damage to you.")); + message.add(CC.translate("&f • &fRevenge of Yijki Passive Ability.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oFeeling threatened by the Yijki")); + lore.add(CC.translate("&7&othat awaits you round the corner.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lYijki Effects")); + lore.add(CC.translate("&f • &fEnemies deal 25% less damage to you.")); + lore.add(CC.translate("&f • &fRevenge of Yijki Passive Ability.")); + //lore.add(CC.translate("&7&o(Requires all 4 yijki items.)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "YijkiSet"); + + if(CooldownUtils.isCooldownActive(attacked, "YijkiLightning")) return; + if(Math.random() > abilityChance / 100) return; + super.getDamageHandler().reduceDamage(50, event, "YijkiAbility"); + CooldownUtils.registerCooldown(attacked, new YijkiLightningCooldown("YijkiLightning", this.abilityCooldown)); + PVPUtils.strikeLightningCircle(attacked.getLocation()); + + } + + @Override + public Material getDisplayMaterial() { + return Material.NETHER_STALK; + } + + @Override + public String getDisplayName() { + return "&f&lYijki"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7An absolute massive, corrupted")); + lore.add(CC.translate("&7executioner blade imbued with")); + lore.add(CC.translate("&7highly destructive dark magic.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lYijki Effects")); + lore.add(CC.translate("&f • &fDeal +10% damage to enemies.")); + lore.add(CC.translate("&f • &f+25% Revenge of Yijki Ability.")); + //lore.add(CC.translate("&7(&oRequires all 4 yijki set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "YijkiWeapon"); + } + + } + + @Override + public Color getColor() { + return Color.fromRGB(255, 255, 255); + } + + @Override + public String getSwordName() { + return "&f&lYijki Dagger"; + } + + @Override + public int getWeight() { + return 3; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/AgaresArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/AgaresArmorSet.java new file mode 100644 index 0000000..0de866b --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/AgaresArmorSet.java @@ -0,0 +1,166 @@ +package net.crankedpvp.crankedarmor.armorsets.cranked; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class AgaresArmorSet extends ArmorSet implements Weapon, Heroic { + + @Override + public String getName() { + return "AGARES"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&a&lAgares Scope Goggles")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&a&lAgares Bullet Vest")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&a&lAgares Camo Pants")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&a&lAgares Airmax 45's")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "AgaresSetSpeed"); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.JUMP, 4, "AgaresSetJump"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "AgaresSetSpeed"); + PotionEffectUtils.removePotionEffect(player, "AgaresSetJump"); + } + + //TODO on bow + //TODO on bowed + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&a&lAGARES SET BONUS")); + message.add(CC.translate("&f • &a+30% Outgoing Bow Damage.")); + message.add(CC.translate("&f • &a-25% Outgoing Bow Damage.")); + message.add(CC.translate("&f • &aPermanent Speed IV.")); + message.add(CC.translate("&f • &aPermanent Jump Boost IV.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oAgares is a devout follower of the Holy")); + lore.add(CC.translate("&7&oChurch and believes that all humans")); + lore.add(CC.translate("&7&oshould offer their lives to their god.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&a&lAGARES SET BONUS")); + lore.add(CC.translate("&f • &a+35% Outgoing Bow Damage.")); + lore.add(CC.translate("&f • &a-25% Incoming Bow Damage.")); + lore.add(CC.translate("&f • &aPermanent Speed IV.")); + lore.add(CC.translate("&f • &aPermanent Jump Boost IV.")); + lore.add(CC.translate("&7(&oRequires all 4 agares set items.&7)")); + return lore; + } + + /* + @Override + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String name = enchanted ? "&d&lEnchanted Lootbox (&a&lAgares&d&l)" : "&f&lArmor Lootbox (&a&lAgares&f&l)"; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the &aagares &7set collection", + ""); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + */ + + @Override + public Material getDisplayMaterial() { + return Material.SPONGE; + } + + @Override + public String getDisplayName() { + return "&a&lAgares"; + } + +/* + @Override + public String getWeaponName() { + return "&a&lAgares Longbow"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(""); + lore.add(CC.translate("&7&oAgares is a devout follower of the Holy")); + lore.add(CC.translate("&7&oChurch and believes that all humans")); + lore.add(CC.translate("&7&oshould offer their lives to their god.")); + lore.add(""); + lore.add(CC.translate("&a&lAGARES WEAPON BONUS")); + lore.add(CC.translate("&f • &a+20% Outgoing Bow Damage")); + lore.add(CC.translate("&7(&oRequires all 4 agares set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.BOW }; + } + + */ + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(153, 255, 51); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/GamblerArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/GamblerArmorSet.java new file mode 100644 index 0000000..daefd7c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/GamblerArmorSet.java @@ -0,0 +1,192 @@ +package net.crankedpvp.crankedarmor.armorsets.cranked; + +import io.netty.util.internal.ThreadLocalRandom; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.cooldowns.old.GamblerAbilityCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class GamblerArmorSet extends ArmorSet implements Weapon, Heroic { + + private final List gambleAbilityPlayers = new ArrayList<>(); + + @ConfigValue + private long abilityDuration = 7; + + @ConfigValue + private double abilityChance = 2.5; + + @ConfigValue + private int abilityCooldown = 60; + + private final double damagePercentIncreaseToPlayers = 60; + + private final double damagePercentIncreaseFromPlayers = 30; + + @Override + public String getName() { + return "GAMBLER"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&d&lGambler's Poker Hat")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&d&lGamblers Waistcoat")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&d&lGamblers Lucky Undies")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&d&lGamblers Black Leather Shoes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + double damageAddition = gambleAbilityPlayers.contains(attacker) ? this.damagePercentIncreaseToPlayers + 10 : this.damagePercentIncreaseToPlayers; + super.getDamageHandler().increaseDamage(damageAddition, event, "GamblerSet"); + if (ThreadLocalRandom.current().nextDouble(100) < abilityChance) { + procGamblerEffect(attacker); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + double damageAddition = gambleAbilityPlayers.contains(attacker) ? this.damagePercentIncreaseFromPlayers + 10 : this.damagePercentIncreaseFromPlayers; + super.getDamageHandler().increaseDamage(damageAddition, event, "GamblerSet"); + } + } + + public void procGamblerEffect(Player player) { + if (CooldownUtils.isCooldownActive(player, "gamblerAbility")) { + return; + } + + CooldownUtils.registerCooldown(player, new GamblerAbilityCooldown("gamblerAbility", abilityCooldown)); + this.gambleAbilityPlayers.add(player); + player.sendMessage(CC.translate("&d&lGambler &8➥ &dYou dive deeper into gambling...")); + CrankedArmor.getInstance().getServer().getScheduler().runTaskLater(CrankedArmor.getInstance(), () -> { + this.gambleAbilityPlayers.remove(player); + player.sendMessage(CC.translate("&d&lGambler &8➥ &cYour gambler ability has worn off")); + }, this.abilityDuration * 20L); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&d&lGAMBLERS SET BONUS")); + message.add(CC.translate("&f • &d+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage")); + message.add(CC.translate("&f • &d+" + (int) this.damagePercentIncreaseFromPlayers + "% Incoming Damage")); + message.add(CC.translate("&f • &dGamblers Ability")); + message.add(CC.translate(" &7&o(+10% Outgoing Damage, +10% Incoming Damage)")); + //message.add(CC.translate(" &7&o+10% Incoming Damage")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oOnly a true gambler will equip this")); + lore.add(CC.translate("&7&oarmor set. Are you willing to deal crazy")); + lore.add(CC.translate("&7&odamage at the expense of receiving the same?")); + lore.add(CC.translate("")); + lore.add(CC.translate("&d&lGAMBLERS SET BONUS")); + lore.add(CC.translate("&f • &d+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage")); + lore.add(CC.translate("&f • &d+" + (int) this.damagePercentIncreaseFromPlayers + "% Incoming Damage")); + lore.add(CC.translate("&f • &dGamblers Ability")); + lore.add(CC.translate("&7(&oRequires all 4 gambler set items.&7)")); + return lore; + } + + + @Override + public Material getDisplayMaterial() { + return Material.DIAMOND; + } + + @Override + public String getDisplayName() { + return "&d&lGambler"; + } + +/* + @Override + public String getWeaponName() { + return "&d&lGambler Machete"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oOnly a true gambler will equip this")); + lore.add(CC.translate("&7&oarmor set. Are you willing to deal crazy")); + lore.add(CC.translate("&7&odamage at the expense of receiving the same?")); + lore.add(CC.translate("")); + lore.add(CC.translate("&d&lGAMBLER WEAPON BONUS")); + lore.add(CC.translate("&f • &d+20% Outgoing Damage")); + lore.add(CC.translate("&7(&oRequires all 4 gambler set items.&7)")); + return lore; + } + /* + + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD, Material.DIAMOND_AXE }; + } + + + */ + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(20, event, "GamblerWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(249, 64, 255); + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/JuggernautArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/JuggernautArmorSet.java new file mode 100644 index 0000000..aef659b --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/JuggernautArmorSet.java @@ -0,0 +1,215 @@ +package net.crankedpvp.crankedarmor.armorsets.cranked; + +import io.netty.util.internal.ThreadLocalRandom; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.cooldowns.old.GamblerAbilityCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class JuggernautArmorSet extends ArmorSet implements Weapon, Heroic { + + private final List juggernautAbilityPlayers = new ArrayList<>(); + + @ConfigValue + private long abilityDuration = 7; + + @ConfigValue + private double abilityChance = 2.5; + + @ConfigValue + private int abilityCooldown = 60; + + private final double damagePercentIncreaseToPlayers = 5; + + private final double damagePercentDecreaseFromPlayers = 30; + + + @Override + public String getName() { + return "JUGGERNAUT"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&6&lJuggernaut's Helmet")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&6&lJuggernaut's Bullet-Proof Vest")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&6&lJuggernaut's Metal Legs")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&6&lJuggernaut's Stompers")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + double damageAddition = juggernautAbilityPlayers.contains(attacker) ? this.damagePercentIncreaseToPlayers + 30 : this.damagePercentIncreaseToPlayers; + super.getDamageHandler().increaseDamage(damageAddition, event, "JuggernautSet"); + if (ThreadLocalRandom.current().nextDouble(100) < abilityChance) { + procJuggernautEffect(attacker); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + double damageAddition = juggernautAbilityPlayers.contains(attacker) ? this.damagePercentDecreaseFromPlayers - 20 : this.damagePercentDecreaseFromPlayers; + super.getDamageHandler().reduceDamage(damageAddition, event, "JuggernautSet"); + } + } + + public void procJuggernautEffect(Player player) { + if (CooldownUtils.isCooldownActive(player, "juggernautAbility")) { + return; + } + + CooldownUtils.registerCooldown(player, new GamblerAbilityCooldown("juggernautAbility", abilityCooldown)); + this.juggernautAbilityPlayers.add(player); + player.sendMessage(CC.translate("&6&lJuggernaut &8➥ &6Your juggernaut armor begins to malfunction...")); + CrankedArmor.getInstance().getServer().getScheduler().runTaskLater(CrankedArmor.getInstance(), () -> { + this.juggernautAbilityPlayers.remove(player); + player.sendMessage(CC.translate("&6&lJuggernaut &8➥ &cYour juggernaut armor reinstates itself")); + }, this.abilityDuration * 20L); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&6&lJUGGERNAUT SET BONUS")); + message.add(CC.translate("&f • &6+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage")); + message.add(CC.translate("&f • &6-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage")); + message.add(CC.translate("&f • &6Malfunction Ability")); + message.add(CC.translate(" &7&o(+20% Incoming Damage, +30% Outgoing Damage)")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oNobody can stop the juggernaut.")); + lore.add(CC.translate("&7&oIt's heavily armored and prepared to")); + lore.add(CC.translate("&7&ofight. Are you strong enough to take it on?")); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lJUGGERNAUT SET BONUS")); + lore.add(CC.translate("&f • &6+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage")); + lore.add(CC.translate("&f • &6-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage")); + lore.add(CC.translate("&f • &6Malfunction Ability")); + lore.add(CC.translate("&7(&oRequires all 4 juggernaut set items.&7)")); + return lore; + } + + /* + @Override + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String name = enchanted ? "&d&lEnchanted Lootbox (&6&lJuggernaut&d&l)" : "&f&lArmor Lootbox (&6&lJuggernaut&f&l)"; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the &6juggernaut &7set collection", + ""); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + */ + + @Override + public Material getDisplayMaterial() { + return Material.CHAINMAIL_CHESTPLATE; + } + + @Override + public String getDisplayName() { + return "&6&lJuggernaut"; + } + + + /* + @Override + public String getWeaponName() { + return "&8✧ &6&lJuggernaut Bayonet"; + } + + + */ + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oNobody can stop the juggernaut.")); + lore.add(CC.translate("&7&oIt's heavily armored and prepared to")); + lore.add(CC.translate("&7&ofight. Are you strong enough to take it on?")); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lJUGGERNAUT WEAPON BONUS")); + lore.add(CC.translate("&f • &6+10% Outgoing Damage")); + lore.add(CC.translate("&7(&oRequires all 4 juggernaut set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD, Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "JuggernautWeapon"); + } + + } + + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(235, 129, 0); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/LucidArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/LucidArmorSet.java new file mode 100644 index 0000000..ca4f853 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/LucidArmorSet.java @@ -0,0 +1,209 @@ +package net.crankedpvp.crankedarmor.armorsets.cranked; + +import io.netty.util.internal.ThreadLocalRandom; +import net.crankedpvp.crankedarmor.cooldowns.old.LucidAbilityCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class LucidArmorSet extends ArmorSet implements Weapon, Heroic { + + @ConfigValue + private long abilityDuration = 3; + + @ConfigValue + private double abilityChance = 2.5; + + @ConfigValue + private int abilityCooldown = 120; + + private final double damagePercentIncreaseToPlayers = 15; + + private final double damagePercentDecreaseFromPlayers = 15; + + @Override + public String getName() { + return "LUCID"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&5&lLucid Eyes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&5&lLucid Bloody Chain")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&5&lLucid Skirt")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&5&lLucid Slippers")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&5&lLUCID SET BONUS")); + message.add(CC.translate("&f • &5+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + message.add(CC.translate("&f • &5-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + message.add(CC.translate("&f • &5Blinding Ability.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oLucid dreaming is dreaming but")); + lore.add(CC.translate("&7&oyou being aware that you're doing it.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&5&lLUCID SET BONUS")); + lore.add(CC.translate("&f • &5+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + lore.add(CC.translate("&f • &5-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + lore.add(CC.translate("&f • &5Blinding Ability.")); + lore.add(CC.translate("&7(&oRequires all 4 lucid set items.&7)")); + return lore; + } + + public void procLucidAbility(Player player) { + if (CooldownUtils.isCooldownActive(player, "lucidAbility")) { + return; + } + + CooldownUtils.registerCooldown(player, new LucidAbilityCooldown("lucidAbility", abilityCooldown)); + player.sendMessage(CC.translate("&5&lLucid &8➥ &5Your body fades from existence...")); + List players = player.getNearbyEntities(50D, 50D, 50D) + .stream().filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .collect(Collectors.toList()); + players.forEach(loopPlayer -> loopPlayer.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 5, 1, false, false))); + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "LucidSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "LucidSet"); + if (ThreadLocalRandom.current().nextDouble(100) < abilityChance) { + procLucidAbility(attacked); + } + } + } + + @Override + public Material getDisplayMaterial() { + return Material.MAGMA_CREAM; + } + + @Override + public String getDisplayName() { + return "&5&lLucid"; + } + + /* + @Override + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String name = enchanted ? "&d&lEnchanted Lootbox (&5&lLucid&d&l)" : "&f&lArmor Lootbox (&5&lLucid&f&l)"; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the &5lucid &7set collection", + ""); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + */ + + /* + @Override + public String getWeaponName() { + return "&5&lLucid Dagger"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oLucid dreaming is dreaming but")); + lore.add(CC.translate("&7&oyou being aware that you're doing it.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&5&lLUCID WEAPON BONUS")); + lore.add(CC.translate("&f • &5+10% Outgoing Damage")); + lore.add(CC.translate("&7(&oRequires all 4 lucid set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "LucidWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(151, 33, 255); + } + + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/LuciferArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/LuciferArmorSet.java new file mode 100644 index 0000000..cfa98b3 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/LuciferArmorSet.java @@ -0,0 +1,173 @@ +package net.crankedpvp.crankedarmor.armorsets.cranked; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class LuciferArmorSet extends ArmorSet implements Weapon, Heroic { + + private final double damagePercentIncreaseToPlayers = 30; + private final double damagePercentDecreaseFromPlayers = 30; + + @Override + public String getName() { + return "LUCIFER"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&4&lL&c&lu&4&lc&c&li&4&lf&c&le&4&lr &c&lH&4&lo&c&lr&4&ln&c&ls")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&4&lL&c&lu&4&lc&c&li&4&lf&c&le&4&lr &c&lW&4&li&c&ln&4&lg&c&ls")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&4&lL&c&lu&4&lc&c&li&4&lf&c&le&4&lr &c&lC&4&lh&c&la&4&lp&c&ls")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&4&lL&c&lu&4&lc&c&li&4&lf&c&le&4&lr &4&lT&c&lr&4&le&c&la&4&ld&c&ls")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + //TODO effect + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&4&lL&c&lU&4&lC&c&lI&4&lF&c&lE&4&lR &c&lSET BONUS")); + message.add(CC.translate("&f • &4+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + message.add(CC.translate("&f • &4-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + message.add(CC.translate("&f • &4Permanent Speed IV Effect")); + message.add(CC.translate("&f • &4Immune to natures wrath")); + message.add(CC.translate("&f • &4Immune to headless ability")); + message.add(CC.translate("&f • &4Bearing Torch Ability")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oCareful. Too much tequila can bring the")); + lore.add(CC.translate("&7&odevil out of anyone. But, I will make")); + lore.add(CC.translate("&7&oyou a believer, of course..")); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lL&c&lU&4&lC&c&lI&4&lF&c&lE&4&lR &c&lS&4&lE&c&lT &4&lB&c&lO&4&lN&c&lU&4&lS")); + lore.add(CC.translate("&f • &4+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + lore.add(CC.translate("&f • &4-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + lore.add(CC.translate("&f • &4Permanent Speed IV Effect")); + lore.add(CC.translate("&f • &4Immune to natures wrath")); + lore.add(CC.translate("&f • &4Immune to headless ability")); + lore.add(CC.translate("&f • &4Bearing Torch Ability")); + return lore; + } + + + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "LuciferSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "LuciferSet"); + } + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "LuciferSet"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "LuciferSet"); + + } + + @Override + public Material getDisplayMaterial() { + return Material.ENCHANTMENT_TABLE; + } + + @Override + public String getDisplayName() { + return "&4&lL&c&lu&4&lc&c&li&4&lf&c&le&4&lr"; + } + + /* + + @Override + public String getWeaponName() { + return "&4&lL&c&lu&4&lc&c&li&4&lf&c&le&4&lr Scythe"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oCareful. Too much tequila can bring the")); + lore.add(CC.translate("&7&odevil out of anyone. But, I will make")); + lore.add(CC.translate("&7&oyou a believer, of course..")); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lL&c&lU&4&lC&c&lI&4&lF&c&lE&4&lR &c&lS&4&lE&c&lT &4&lW&c&lE&4&lA&c&lP&4&lO&c&lN &4&lB&c&lO&4&lN&c&lU&4&lS")); + lore.add(CC.translate("&f • &4+15% Outgoing Damage")); + lore.add(CC.translate("&7(&oRequires all 4 lucifer set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(15, event, "LuciferWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(201, 0, 0); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SacredArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SacredArmorSet.java new file mode 100644 index 0000000..90762de --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SacredArmorSet.java @@ -0,0 +1,178 @@ +package net.crankedpvp.crankedarmor.armorsets.cranked; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class SacredArmorSet extends ArmorSet implements Weapon, Heroic { + + private final double damagePercentIncreaseToPlayers = 5; + + private final double damagePercentDecreaseFromPlayers = 15; + + @Override + public String getName() { + return "SACRED"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&b&lSacred Grail")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&b&lSacred Chained Torso")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&b&lSacred Jeans")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&b&lSacred Jumpers")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&b&lSACRED SET BONUS")); + message.add(CC.translate("&f • &b+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + message.add(CC.translate("&f • &b-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + message.add(CC.translate("&f • &b+5% Outgoing Axe Damage.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oYour sacred space is where you")); + lore.add(CC.translate("&7&ocan find yourself again and again.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lSACRED SET BONUS")); + lore.add(CC.translate("&f • &b+" + (int) this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + lore.add(CC.translate("&f • &b-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + lore.add(CC.translate("&f • &b+5% Outgoing Axe Damage.")); + lore.add(CC.translate("&7(&oRequires all 4 sacred set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + if (attacker.getItemInHand() != null && attacker.getItemInHand().getType().name().endsWith("_AXE")) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers + 5, event, "SacredSetAxe"); + } else { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "SacredSet"); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "SacredSet"); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.SNOW_BALL; + } + + @Override + public String getDisplayName() { + return "&b&lSacred"; + } + + /* + @Override + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String name = enchanted ? "&d&lEnchanted Lootbox (&b&lSacred&d&l)" : "&f&lArmor Lootbox (&b&lSacred&f&l)"; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the &bsacred &7set collection", + ""); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + */ + + /* + @Override + public String getWeaponName() { + return "&b&lSacred Tomohawk"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oYour sacred space is where you")); + lore.add(CC.translate("&7&ocan find yourself again and again.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lSACRED WEAPON BONUS")); + lore.add(CC.translate("&f • &b+10% Outgoing Damage")); + lore.add(CC.translate("&7(&oRequires all 4 sacred set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "SacredWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(84, 238, 255); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SpectreArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SpectreArmorSet.java new file mode 100644 index 0000000..a910166 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SpectreArmorSet.java @@ -0,0 +1,219 @@ +package net.crankedpvp.crankedarmor.armorsets.cranked; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.cooldowns.old.LucidAbilityCooldown; +import net.crankedpvp.crankedarmor.listeners.SpectreSetListener; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class SpectreArmorSet extends ArmorSet implements Weapon, Heroic { + public List immuneList; + + public SpectreArmorSet() { + CrankedArmor.getInstance().getServer().getPluginManager().registerEvents(new SpectreSetListener(), CrankedArmor.getInstance()); + this.immuneList = new ArrayList<>(); + } + + private final double damagePercentIncreaseToPlayers = 12.5; + private final double damagePercentDecreaseFromPlayers = 12.5; + + @ConfigValue + private double spectreAbilityChancePercent = 2.5; + + @ConfigValue + private int spectreAbilityDurationInSeconds = 3; + + @Override + public String getName() { + return "SPECTRE"; + } + + @Override + public String getDisplayName() { + return "&d&lSpectre"; + } + + @Override + public Material getDisplayMaterial() { + return Material.WATCH; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&d&lSpectre Crown")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&d&lSpectre Shirt")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&d&lSpectre Shorts")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&d&lSpectre Flash Boots")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&d&lSPECTRE SET BONUS")); + message.add(CC.translate("&f • &d+" + this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + message.add(CC.translate("&f • &d-" + this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + message.add(CC.translate("&f • &dSpectre Vanishing Ability.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oA license to kill also")); + lore.add(CC.translate("&7&omeans a license Not to kill.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&d&lSPECTRE SET BONUS")); + lore.add(CC.translate("&f • &d+" + this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + lore.add(CC.translate("&f • &d-" + this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + lore.add(CC.translate("&f • &dSpectre Vanishing Ability.")); + lore.add(CC.translate("&7(&oRequires all 4 spectre set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "SpectreSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "SpectreSet"); + + if (CooldownUtils.isCooldownActive(attacked, "spectreAbility")) { + return; + } + + if (Math.random() < this.spectreAbilityChancePercent) { + CooldownUtils.registerCooldown(attacked, new LucidAbilityCooldown("spectreAbility", 60)); + procSpectreAbility(attacked); + } + } + } + + + public void procSpectreAbility(Player player) { + player.sendMessage(CC.translate("&d&l* SPECTRE VANISHING ABILITY [&7" + this.spectreAbilityDurationInSeconds + "s&d&l] *")); + player.sendMessage(CC.translate("&7&o(Immune to all incoming damage)")); + + player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 20 * this.spectreAbilityDurationInSeconds, 2,false)); + this.immuneList.add(player.getUniqueId()); + + Bukkit.getScheduler().runTaskLaterAsynchronously(CrankedArmor.getInstance(), ()-> { + this.immuneList.remove(player.getUniqueId()); + },spectreAbilityDurationInSeconds * 20L); + + } + + + /* + @Override + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String name = enchanted ? "&d&lEnchanted Lootbox (&d&lSpectre&d&l)" : "&f&lArmor Lootbox (&d&lSpectre&f&l)"; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the &dspectre &7set collection", + ""); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + */ + + /* + @Override + public String getWeaponName() { + return "&8✧ &d&lSpectre Scythe"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oA license to kill also")); + lore.add(CC.translate("&7&omeans a license Not to kill.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&d&lSPECTRE WEAPON BONUS")); + lore.add(CC.translate("&f • &d+10% Outgoing Damage")); + lore.add(CC.translate("&7(&oRequires all 4 spectre set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "SpectreWeapon"); + } + + } + + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(84, 238, 255); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SpiritArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SpiritArmorSet.java new file mode 100644 index 0000000..a4e068d --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/cranked/SpiritArmorSet.java @@ -0,0 +1,184 @@ +package net.crankedpvp.crankedarmor.armorsets.cranked; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.listeners.SpiritSetListener; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class SpiritArmorSet extends ArmorSet implements Weapon, Heroic { + + public SpiritArmorSet() { + CrankedArmor.getInstance().getServer().getPluginManager().registerEvents(new SpiritSetListener(), CrankedArmor.getInstance()); + } + + private final double damagePercentIncreaseToPlayers = 7.5; + private final double damagePercentDecreaseFromPlayers = 15; + + @Override + public String getName() { + return "SPIRIT"; + } + + @Override + public String getDisplayName() { + return "&e&lSpirit"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&e&lSpirit Cap")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&e&lSpirit Vest")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&e&lSpirit Cape")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&e&lSpirit Shoes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&e&lSPIRIT SET BONUS")); + message.add(CC.translate("&f • &e+" + this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + message.add(CC.translate("&f • &e-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + message.add(CC.translate("&f • &e-50% Incoming Armor Durability.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oLife without liberty is")); + lore.add(CC.translate("&7&olike a body without spirit.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lSPIRIT SET BONUS")); + lore.add(CC.translate("&f • &e+" + this.damagePercentIncreaseToPlayers + "% Outgoing Damage.")); + lore.add(CC.translate("&f • &e-" + (int) this.damagePercentDecreaseFromPlayers + "% Incoming Damage.")); + lore.add(CC.translate("&f • &e-50% Incoming Armor Durability.")); + lore.add(CC.translate("&7(&oRequires all 4 spirit set items.&7)")); + return lore; + } + + + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "SpiritSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "SpiritSet"); + } + } + + //TODO decrease armor dura damage + + @Override + public Material getDisplayMaterial() { + return Material.GOLD_INGOT; + } + + /* + @Override + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String name = enchanted ? "&d&lEnchanted Lootbox (&e&lSpirit&d&l)" : "&f&lArmor Lootbox (&e&lSpirit&f&l)"; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the &espirit &7set collection", + ""); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + */ + + /* + @Override + public String getWeaponName() { + return "&e&lSpirit Sword"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oLife without liberty is")); + lore.add(CC.translate("&7&olike a body without spirit.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lSPIRIT WEAPON BONUS")); + lore.add(CC.translate("&f • &e+10% Outgoing Damage")); + lore.add(CC.translate("&7(&oRequires all 4 spirit set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "SpiritWeapon"); + } + + } + + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(255, 248, 54); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/AssassinArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/AssassinArmorSet.java new file mode 100644 index 0000000..8bf3851 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/AssassinArmorSet.java @@ -0,0 +1,189 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class AssassinArmorSet extends ArmorSet implements Listener, Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayersBehind = 30; + @ConfigValue + private double damagePercentIncreaseToPlayers = 20; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 10; + + @Override + public String getName() { + return "ASSASSIN"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&3&lAssassin Horns")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&3&lAssassin Shield")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&3&lAssassin Joggers")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&3&lAssassin Spiked Shoes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public void onEquip(Player player) { + PotionEffectUtils.bless(player); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "AssassinSet"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "AssassinSet"); + } + + @Override + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "AssassinSet"); + if(PlayerUtils.isPlayerBehind(attacker, attacked)) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayersBehind, event, "AssassinSetBehind"); + } + } + + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&3&lAssassin Effects")); + message.add(CC.translate("&3 • &fDeal +10% damage to enemies")); + message.add(CC.translate("&3 • &fDeal +30% damage to enemies from behind")); + message.add(CC.translate("&3 • &fEnemies deal 10% less damage to you")); + message.add(CC.translate("&3 • &fPermanent Speed IV effect.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oFrom the fiery depths of the underworld,")); + lore.add(CC.translate("&7&oThis armor set shows you when it's time")); + lore.add(CC.translate("&7&ofor a fresh start.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&3&lAssassin Effects")); + lore.add(CC.translate("&3 • &fDeal +10% damage to enemies")); + lore.add(CC.translate("&3 • &fDeal +30% damage to enemies from behind")); + lore.add(CC.translate("&3 • &fEnemies deal 10% less damage to you")); + lore.add(CC.translate("&3 • &fPermanent Speed IV effect.")); + //lore.add(CC.translate("&7(&oRequires all 4 assassin set items.&7)")); + return lore; + } + + @Override + public Material getDisplayMaterial() { + return Material.GOLD_SWORD; + } + + @Override + public String getDisplayName() { + return "&3&lAssassin"; + } + + /* + @Override + public String getWeaponName() { + return "&3&lAssassin Scythe"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oFrom the fiery depths of the underworld,")); + lore.add(CC.translate("&7&oThis armor set shows you when it's time")); + lore.add(CC.translate("&7&ofor a fresh start.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&3&lAssassin Effects")); + lore.add(CC.translate("&3 • &fDeal +5% damage to enemies")); + lore.add(CC.translate("&3 • &fDeal +10% damage to enemies from behind")); + //lore.add(CC.translate("&7(&oRequires all 4 assassin set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "AssassinWeapon"); + if(PlayerUtils.isPlayerBehind(attacker, attacked)) { + super.getDamageHandler().increaseDamage(10, event, "AssassinWeaponBehind"); + } + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(3, 177, 252); + } + + @Override + public String getSwordName() { + return "&3&lAssassin Scythe"; + } + + @Override + public int getWeight() { + return 2; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/BardArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/BardArmorSet.java new file mode 100644 index 0000000..ec290c1 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/BardArmorSet.java @@ -0,0 +1,157 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class BardArmorSet extends ArmorSet implements Listener, Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseFromPlayers = 50; + + + @Override + public String getName() { + return "Bard"; + } + + public ItemStack getHelmet() { + return addDiamondArmorData((new ItemBuilder(Material.GOLD_HELMET)).setName(CC.translate("&6&lBard Helmet")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).setUnbreakable(true).build()); + + } + + public ItemStack getChestplate() { + return addDiamondArmorData((new ItemBuilder(Material.GOLD_CHESTPLATE)).setName(CC.translate("&6&lBard Chestplate")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).setUnbreakable(true).build()); + } + + public ItemStack getLeggings() { + return addDiamondArmorData((new ItemBuilder(Material.GOLD_LEGGINGS)).setName(CC.translate("&6&lBard Leggings")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).setUnbreakable(true).build()); + } + + public ItemStack getBoots() { + return addDiamondArmorData((new ItemBuilder(Material.GOLD_BOOTS)).setName(CC.translate("&6&lBard Boots")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.DURABILITY, 3).setUnbreakable(true).build()); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&6&lBard Effects")); + message.add(CC.translate("&6 • &fEnemies deal 50% more damage to you")); + message.add(CC.translate("&6 • &fPermanent Speed IV Effect")); + message.add(CC.translate("&6 • &fSugar: Speed")); + message.add(CC.translate("&6 • &fFeather: Jump Boost")); + message.add(CC.translate("&6 • &fBlaze Powder: Strength")); + message.add(CC.translate("&6 • &fIron Ingot: Resistance")); + message.add(CC.translate("&6 • &fGhast Tear: Regeneration")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oA team player is the best player.")); + lore.add(CC.translate("&7&oTake one for the team to provide")); + lore.add(CC.translate("&7&ounstoppable buffs for your teammates.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lBard Effects")); + lore.add(CC.translate("&6 • &fEnemies deal 50% more damage to you")); + lore.add(CC.translate("&6 • &fPermanent Speed IV Effect")); + lore.add(CC.translate("&6 • &fSugar: Speed")); + lore.add(CC.translate("&6 • &fFeather: Jump Boost")); + lore.add(CC.translate("&6 • &fIron Ingot: Resistance")); + lore.add(CC.translate("&6 • &fGhast Tear: Regeneration")); + lore.add(CC.translate("&6 • &fBlaze Powder: Strength")); + return lore; + } + + @Override + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseFromPlayers, event, "BardSetIncrease"); + } + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "BardSetSpeed"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "BardSetSpeed"); + } + + + @Override + public Material getDisplayMaterial() { + return Material.GOLDEN_APPLE; + } + + + @Override + public String getDisplayName() { + return "&6&lBard"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lBard Effects")); + lore.add(CC.translate("&6 • &fDeal +10% damage to enemies")); + return lore; + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "BardWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(232, 116, 0); + } + + @Override + public String getSwordName() { + return "&6&lBards Dagger"; + } + + + private ItemStack addDiamondArmorData(ItemStack oldItemStack) { + ItemStack itemStack = oldItemStack.clone(); + Material material = itemStack.getType(); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("wine-armor-override", CrankedArmorAPI.getArmorStrengthFromItem(material)); + return nbtItem.getItem(); + } + + @Override + public int getWeight() { + return 0; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DemonArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DemonArmorSet.java new file mode 100644 index 0000000..6d918bf --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DemonArmorSet.java @@ -0,0 +1,167 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class DemonArmorSet extends ArmorSet implements Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 40; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 40; + + + @ConfigValue + private double demonAbilityChance = 3; + + + @Override + public String getName() { + return "DEMON"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&2&lDemon Eyes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&2&lDemon Bloody Torso")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&2&lDemon Tail")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&2&lDemon Spikes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&2&lDemon Effects")); + message.add(CC.translate("&4 • &fDeal +40% damage to enemies")); + message.add(CC.translate("&4 • &fEnemies deal 40% less damage to you")); + message.add(CC.translate("&4 • &fDemon Devour Skulls Ability.")); + message.add(CC.translate("&4 • &fChance to bypass armored")); + message.add(CC.translate("&4 • &fExtra hearts from iron golem pet")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oWe don't beat the reaper by")); + lore.add(CC.translate("&7&oliving longer, we beat the reaper")); + lore.add(CC.translate("&7&oby living well and living fully.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lReaper Effects")); + lore.add(CC.translate("&4 • &fDeal +35% damage to enemies")); + lore.add(CC.translate("&4 • &fEnemies deal 35% less damage to you")); + lore.add(CC.translate("&4 • &fReaper Hell Trap Ability.")); + lore.add(CC.translate("&4 • &fChance to bypass armored")); + lore.add(CC.translate("&4 • &fExtra hearts from iron golem pet")); + //lore.add(CC.translate("&7(&oRequires all 4 reaper set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "ReaperSet"); + Player victim = (Player) attacked; + + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "ReaperSet"); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.BLAZE_POWDER; + } + + @Override + public String getDisplayName() { + return "&4&lDemon"; + } + + @Override + public String getSwordName() { + return "&2&lDemon Trident"; + } + + @Override + public int getWeight() { + return 9; + } + + + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oWe don't beat the reaper by")); + lore.add(CC.translate("&7&oliving longer, we beat the reaper")); + lore.add(CC.translate("&7&oby living well and living fully.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lReaper Effects")); + lore.add(CC.translate("&4 • &fDeal +15% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 reaper set items.&7)")); + return lore; + } + + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(15, event, "DemonWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(199, 0, 0); + } +} + diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DracoArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DracoArmorSet.java new file mode 100644 index 0000000..64a61f3 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DracoArmorSet.java @@ -0,0 +1,256 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import io.netty.util.internal.ThreadLocalRandom; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.cooldowns.old.DracoAbilityCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class DracoArmorSet extends ArmorSet implements Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 25; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 20; + + @ConfigValue + private double abilityDamageMinHP = 4; + + @ConfigValue + private double abilityDamageMaxHP = 10; + + @ConfigValue + private long abilityDuration = 5; + + @ConfigValue + private double abilityChance = 2.5; + + @ConfigValue + private int abilityCooldown = 60; + + @Override + public String getName() { + return "DRACO"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&c&lDraco Horns")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&c&lDraco Chest of Fire")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&c&lDraco Pants of Hell")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&c&lDraco Flamey Boots")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + //TODO effect + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&c&lDraco Effects")); + message.add(CC.translate("&c • &fDeal +20% damage to enemies")); + message.add(CC.translate("&c • &fEnemies deal 20% less damage to you.")); + message.add(CC.translate("&c • &f+25% Critical Damage Modifier")); + message.add(CC.translate("&c • &fWeb Stickler Ability")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oMost of the time, you have to make")); + lore.add(CC.translate("&7&oa choice. At a certain point of the man")); + lore.add(CC.translate("&7&oyou want to be and that's so hard.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lDraco Effects")); + lore.add(CC.translate("&c • &fDeal +20% damage to enemies")); + lore.add(CC.translate("&c • &fEnemies deal 20% less damage to you.")); + lore.add(CC.translate("&c • &f+25% Critical Damage Modifier")); + lore.add(CC.translate("&c • &fWeb Stickler Ability")); + //lore.add(CC.translate("&7(&oRequires all 4 draco set items.&7)")); + return lore; + } + + public void procDracoAbility(Player performer, Player target) { + if (CooldownUtils.isCooldownActive(performer,"dracoAbility")) { + return; + } + + CooldownUtils.registerCooldown(performer, new DracoAbilityCooldown("dracoAbility", abilityCooldown)); + Location location = target.getLocation(); + //target.setVelocity(new Vector(0, 0.8, 0)); + + //Block topBlock = location.clone().add(0, 2, 0).getBlock(); + Block underBlock = location.clone().getBlock(); + + //Material topBlockType = topBlock.getType(); + Material underBlockType = underBlock.getType(); + + boolean setAtLeastOne = false; + +/* if (topBlockType == Material.AIR) { + topBlock.setType(Material.WEB); + setAtLeastOne = true; + }*/ + + if (underBlockType == Material.AIR) { + underBlock.setType(Material.WEB); + setAtLeastOne = true; + } + + + + target.damage(ThreadLocalRandom.current().nextDouble(abilityDamageMinHP, abilityDamageMaxHP), performer); + PotionEffectUtils.addPotionEffect(target, PotionEffectType.BLINDNESS,5, "DracoAbility", (int) abilityDuration); + + if (setAtLeastOne) { + Bukkit.getScheduler().runTaskLater(CrankedArmor.getInstance(), () -> { +/* if (topBlock.getType() == Material.WEB) { + topBlock.setType(Material.AIR); + }*/ + + if (underBlock.getType() == Material.WEB) { + underBlock.setType(Material.AIR); + } + + + }, abilityDuration * 20); + + } + } + + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + if (PVPUtils.isCritical(attacker)) { + attacker.sendMessage(CC.translate("&c* CRITICAL HIT *")); + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers * 1.25, event, "DracoSetCritical"); + } else { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "DracoSet"); + } + if (ThreadLocalRandom.current().nextDouble(100) < abilityChance) { + if (!PVPUtils.canPVP(attacker, (LivingEntity) attacked)) return; + procDracoAbility(attacker, (Player) attacked); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "DracoSet"); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.REDSTONE; + } + + @Override + public String getDisplayName() { + return "&c&lDraco"; + } + + /* + @Override + public String getWeaponName() { + return "&8✧ &c&lDraco Cutlass &8✧"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oMost of the time, you have to make")); + lore.add(CC.translate("&7&oa choice. At a certain point of the man")); + lore.add(CC.translate("&7&oyou want to be and that's so hard.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lDraco Effects")); + lore.add(CC.translate("&c • &fDeal +15% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 draco set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD, Material.DIAMOND_AXE}; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(15, event, "DracoWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(255, 64, 64); + } + + @Override + public String getSwordName() { + return "&c&lDraco Cutlass"; + } + + @Override + public int getWeight() { + return 4; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DragonArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DragonArmorSet.java new file mode 100644 index 0000000..5e9564d --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/DragonArmorSet.java @@ -0,0 +1,164 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class DragonArmorSet extends ArmorSet implements Listener, Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 15; + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 20; + + + @Override + public String getName() { + return "Dragon"; + } + + public ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)).setName(CC.translate("&e&lDecapitated Dragon Skull")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)).setName(CC.translate("&e&lFiery Chestplate of Dragons")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)).setName(CC.translate("&e&lScorched Leggings of Dragons")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)).setName(CC.translate("&e&lDragon Slayer Battle Boots")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&e&lDragon Effects")); + message.add(CC.translate("&e • &fDeal +15% damage to enemies")); + message.add(CC.translate("&e • &fEnemies deal 15% less damage to you")); + message.add(CC.translate("&e • &fImmune to slowness.")); + message.add(CC.translate("&e • &fChance to reflect silence")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oDid dragons even exist..?")); + lore.add(CC.translate("&7&oWait, do they still exist..?")); + lore.add(CC.translate("&7&oUnleash undeniable power with this set.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lDragon Effects")); + lore.add(CC.translate("&e • &fDeal +15% damage to enemies")); + lore.add(CC.translate("&e • &fEnemies deal 15% less damage to you")); + lore.add(CC.translate("&e • &fImmune to slowness.")); + lore.add(CC.translate("&e • &fChance to reflect silence")); + //lore.add(CC.translate("&7(&oRequires all 4 dragon set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "DragonSetIncrease"); + } + } + + @Override + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "DragonSetReduce"); + } + } + + public void onEquip(Player player) { + } + + public void onUnequip(Player player) { + } + + + @Override + public Material getDisplayMaterial() { + return Material.EYE_OF_ENDER; + } + + + @Override + public String getDisplayName() { + return "&e&lDragon"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&e&lDragon Effects")); + lore.add(CC.translate("&e • &fDeal +10% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 dragon set items.&7)")); + return lore; + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "DragonWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(232, 220, 0); + } + + @Override + public String getSwordName() { + return "&e&lDragon Dagger &8✧"; + } + + + + @EventHandler + public void onPotionEffectInKothSet(PotionEffectAddEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = ((Player) event.getEntity()); + if (CrankedArmorAPI.getCurrentArmorSet(player) != null && Objects.equals(CrankedArmorAPI.getCurrentArmorSet(player), this)) { + if (PotionEffectUtils.getDebuffsList().contains(event.getEffect().getType())) + event.setCancelled(true); + } + } + + @Override + public int getWeight() { + return 3; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/GoblinArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/GoblinArmorSet.java new file mode 100644 index 0000000..f1fa7d0 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/GoblinArmorSet.java @@ -0,0 +1,158 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class GoblinArmorSet extends ArmorSet implements Heroic, Weighable { + @Override + public String getName() { + return "GOBLIN"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&6&lGoblin Hat")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&6&lGoblin Golden Chain")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&6&lGoblin Black Jeans")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&6&lGoblin Leather Boots")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&6&lGoblin Effects")); + message.add(CC.translate("&6 • &f2x EXP from Mobs.")); + message.add(CC.translate("&6 • &fPermanent Haste III.")); + message.add(CC.translate("&6 • &fPermanent Speed IV.")); + message.add(CC.translate("&6 • &fChance to kill multiple mobs at once.")); + message.add(CC.translate("&6 • &fIncreased % to obtain keys while grinding.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oWho’s going to pay for the ring?")); + lore.add(CC.translate("&7&oIt doesn’t matter who pays.")); + lore.add(CC.translate("&7&oYou’ll both pay a heavy price for it anyway.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lGoblin Effects")); + lore.add(CC.translate("&6 • &f2x EXP from Mobs.")); + lore.add(CC.translate("&6 • &fPermanent Haste III.")); + lore.add(CC.translate("&6 • &fPermanent Speed IV.")); + lore.add(CC.translate("&6 • &fChance to kill multiple mobs at once.")); + lore.add(CC.translate("&6 • &fIncreased % to obtain keys while grinding.")); + //lore.add(CC.translate("&7(&oRequires all 4 goblin set items.&7)")); + return lore; + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.FAST_DIGGING, 3, "GoblinSetHaste"); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "GoblinSetSpeed"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "GoblinSetHaste"); + PotionEffectUtils.removePotionEffect(player, "GoblinSetSpeed"); + } + + //TODO exp boost + + + + + @Override + public Material getDisplayMaterial() { + return Material.EXP_BOTTLE; + } + + @Override + public String getDisplayName() { + return "&6&lGoblin"; + } + + /* + @Override + public String getWeaponName() { + return "&6&lGoblin Pick Pocket"; + } + + */ + + /* + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oWho’s going to pay for the ring?")); + lore.add(CC.translate("&7&oIt doesn’t matter who pays.")); + lore.add(CC.translate("&7&oYou’ll both pay a heavy price for it anyway.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&6&lGOBLIN WEAPON BONUS")); + lore.add(CC.translate("&f • &6+10% Key Grind Chance")); + lore.add(CC.translate("&f • &6+35% EXP Gain")); + lore.add(CC.translate("&f • &6+15% Chance to kill multiple mobs at once")); + lore.add(CC.translate("&7(&oRequires all 4 goblin set items.&7)")); + return lore; + } + + */ + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(255, 136, 18); + } + + @Override + public int getWeight() { + return 0; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/KothArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/KothArmorSet.java new file mode 100644 index 0000000..fa9b71c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/KothArmorSet.java @@ -0,0 +1,183 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class KothArmorSet extends ArmorSet implements Listener, Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 20; + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 20; + + + @Override + public String getName() { + return "KOTH"; + } + + public ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)).setName(CC.translate("&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nHelmet&r")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)).setName(CC.translate("&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nChestplate&r")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)).setName(CC.translate("&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nLeggings&r")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)).setName(CC.translate("&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nBoots&r")) .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&lEffects")); + message.add(CC.translate("&b • &fDeal +25% damage to enemies")); + message.add(CC.translate("&b • &fEnemies deal 20% less damage to you")); + message.add(CC.translate("&b • &fPermanent Speed IV.")); + message.add(CC.translate("&b • &fAuto Bless.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oObtained from open the KOTH Lootbag.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&lEffects")); + lore.add(CC.translate("&b • &fDeal +25% damage to enemies")); + lore.add(CC.translate("&b • &fEnemies deal 20% less damage to you")); + lore.add(CC.translate("&b • &fPermanent Speed IV.")); + lore.add(CC.translate("&b • &fAuto Bless.")); + //lore.add(CC.translate("&7(&oRequires all 4 koth set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "KothSetIncrease"); + } + } + + @Override + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "KothSetReduce"); + } + } + + public void onEquip(Player player) { + PotionEffectUtils.bless(player); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "KothSet"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "KothSet"); + + } + + + @Override + public Material getDisplayMaterial() { + return Material.NETHER_STAR; + } + + + @Override + public String getDisplayName() { + return "&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r"; + } + + + @EventHandler + public void onPotionEffectInKothSet(PotionEffectAddEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = ((Player) event.getEntity()); + if (CrankedArmorAPI.getCurrentArmorSet(player) != null && Objects.equals(CrankedArmorAPI.getCurrentArmorSet(player), this)) { + if (PotionEffectUtils.getDebuffsList().contains(event.getEffect().getType())) + event.setCancelled(true); + } + } + + /* + @Override + public String getWeaponName() { + return "&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nScalpel&r &8✧"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oObtained from open the KOTH Lootbag.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&lEffects")); + lore.add(CC.translate("&b • &fDeal +10% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 koth set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "KothWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(255, 255, 255); + } + + @Override + public String getSwordName() { + return "&f&l&k;&r &c&lK&6&l.&e&lO&a&l.&b&lT&5&l.&d&lH &f&l&k;&r &f&l&nScalpel&r &8✧"; + } + + @Override + public int getWeight() { + return 5; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/MageArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/MageArmorSet.java new file mode 100644 index 0000000..f50b696 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/MageArmorSet.java @@ -0,0 +1,158 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class MageArmorSet extends ArmorSet implements Listener, Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseFromPlayers = 25; + + + @Override + public String getName() { + return "Mage"; + } + + public ItemStack getHelmet() { + return addDiamondArmorData((new ItemBuilder(Material.GOLD_HELMET)).setName(CC.translate("&2&lMage Helmet")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).setUnbreakable(true).build()); + } + + public ItemStack getChestplate() { + return addDiamondArmorData((new ItemBuilder(Material.CHAINMAIL_CHESTPLATE)).setName(CC.translate("&2&lMage Chestplate")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).setUnbreakable(true).build()); + } + + public ItemStack getLeggings() { + return addDiamondArmorData((new ItemBuilder(Material.CHAINMAIL_LEGGINGS)).setName(CC.translate("&2&lMage Leggings")).addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).setUnbreakable(true).build()); + } + + public ItemStack getBoots() { + return addDiamondArmorData((new ItemBuilder(Material.GOLD_BOOTS)).setName(CC.translate("&2&lMage Boots")) .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).setUnbreakable(true).build()); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&2&lMage Effects")); + message.add(CC.translate("&2 • &fEnemies deal 25% more damage to you")); + message.add(CC.translate("&2 • &fPermanent Regeneration I Effect")); + message.add(CC.translate("&2 • &fSeeds: Nausea")); + message.add(CC.translate("&2 • &fGreen Dye: Poison")); + message.add(CC.translate("&2 • &fSpider Eye: Wither")); + message.add(CC.translate("&2 • &fRotten Flesh: Hunger")); + message.add(CC.translate("&2 • &fCoal: Weakness")); + message.add(CC.translate("&2 • &fGold Nugget: Slowness")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oA team player is the best player.")); + lore.add(CC.translate("&7&oTake one for the team to provide")); + lore.add(CC.translate("&7&oimmense debuffs for your opponents.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&2&lMage Effects")); + lore.add(CC.translate("&2 • &fEnemies deal 25% more damage to you")); + lore.add(CC.translate("&2 • &fPermanent Regeneration I Effect")); + lore.add(CC.translate("&2 • &fSeeds: Nausea")); + lore.add(CC.translate("&2 • &fGreen Dye: Poison")); + lore.add(CC.translate("&2 • &fSpider Eye: Wither")); + lore.add(CC.translate("&2 • &fRotten Flesh: Hunger")); + lore.add(CC.translate("&2 • &fCoal: Weakness")); + lore.add(CC.translate("&2 • &fGold Nugget: Slowness")); + return lore; + } + + @Override + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseFromPlayers, event, "MageSetIncrease"); + } + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.REGENERATION, 1, "MageSetRegeneration"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "MageSetRegeneration"); + } + + + @Override + public Material getDisplayMaterial() { + return Material.SEEDS; + } + + + @Override + public String getDisplayName() { + return "&2&lMage"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&2&lMage Effects")); + lore.add(CC.translate("&2 • &fDeal +10% damage to enemies")); + return lore; + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "MageWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(20, 107, 2); + } + + @Override + public String getSwordName() { + return "&2&lMage Dagger"; + } + + + private ItemStack addDiamondArmorData(ItemStack oldItemStack) { + ItemStack itemStack = oldItemStack.clone(); + Material material = itemStack.getType(); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("wine-armor-override", CrankedArmorAPI.getArmorStrengthFromItem(material)); + return nbtItem.getItem(); + } + + @Override + public int getWeight() { + return 0; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/NightmareArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/NightmareArmorSet.java new file mode 100644 index 0000000..fe13675 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/NightmareArmorSet.java @@ -0,0 +1,223 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.managers.HeadlessAbilityManager; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class NightmareArmorSet extends ArmorSet implements Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 15; + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 15; + + @ConfigValue + private double headlessAbilityChance = 0.5; + + private final HeadlessAbilityManager headlessAbilityManager = CrankedArmor.getInstance().getHeadlessAbilityManager(); + + + + @Override + public String getName() { + return "NIGHTMARE"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&8&lNightmare Sleepy Eyes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&8&lNightmare Chest")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&8&lNightmare Shorts Eyes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&8&lNightmare Feet Eyes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&8&lNightmare Effects")); + message.add(CC.translate("&8 • &fDeal +25% damage to enemies.")); + message.add(CC.translate("&8 • &fEnemies deal 25% less damage to you")); + message.add(CC.translate("&8 • &fHeadless Ability.")); + message.add(CC.translate("&8 • &fImmune to ignited holograph damage")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oTeamwork makes the dream work,")); + lore.add(CC.translate("&7&obut a vision becomes a nightmare when")); + lore.add(CC.translate("&7&othe leader has a big dream and a bad team.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&8&lNightmare Effects")); + lore.add(CC.translate("&8 • &fDeal +25% damage to enemies.")); + lore.add(CC.translate("&8 • &fEnemies deal 25% less damage to you")); + lore.add(CC.translate("&8 • &fHeadless Ability.")); + lore.add(CC.translate("&8 • &fImmune to ignited holograph damage")); + //lore.add(CC.translate("&7(&oRequires all 4 nightmare set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "NightmareSet"); + if (ThreadLocalRandom.current().nextInt(101) < headlessAbilityChance) { + if (!PVPUtils.canPVP(attacker, (LivingEntity) attacked)) return; + Player victim = (Player) attacked; + if(CrankedMasksAPI.hasMaskEquipped(victim, CrankedMasks.getInstance().getMasksRegister().getMaskFromID("dream"))) return; + //if(Objects.equals(CrankedArmorAPI.getCurrentArmorSet(victim), CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID("lucifer"))) return; + if(this.headlessAbilityManager == null) { + System.out.println("ability manager is null"); + return; + } + this.headlessAbilityManager.activateAbility(attacker, (Player) attacked); + } + } + } + + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "NightmareSet"); + } + } + + + @Override + public Material getDisplayMaterial() { + return Material.COAL; + } + + @Override + public String getDisplayName() { + return "&8&lNightmare"; + } + + /* + @Override + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String name = enchanted ? "&d&lEnchanted Lootbox (&8&lNightmare&d&l)" : "&f&lArmor Lootbox (&8&lNightmare&f&l)"; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the &8nightmare &7set collection", + ""); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + */ + + /* + @Override + public String getWeaponName() { + return "&8&lNightmare Blade"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oTeamwork makes the dream work,")); + lore.add(CC.translate("&7&obut a vision becomes a nightmare when")); + lore.add(CC.translate("&7the leader has a big dream and a bad team.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&8&lNightmare Effects")); + lore.add(CC.translate("&8 • &fDeal +10% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 nightmare set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD }; + } + + */ + + @Override + public String getSwordName() { + return "&8&lNightmare's Blade"; + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "NightmareWeapon"); + } + + } + + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(43, 43, 43); + } + + @Override + public int getWeight() { + return 6; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/PhantomArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/PhantomArmorSet.java new file mode 100644 index 0000000..2934c63 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/PhantomArmorSet.java @@ -0,0 +1,171 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class PhantomArmorSet extends ArmorSet implements Weapon, Sword, Listener, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 18; + + + @Override + public String getName() { + return "PHANTOM"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&c&lPhantom Hood")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe fabled hood of the Phantom.")) + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&c&lPhantom Shroud")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe legendary shroud of the Phantom.")) + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&c&lPhantom Robeset")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe demonic robe of the Phantom.")) + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&c&lPhantom Sandals")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe silent sandals of the Phantom.")) + */ + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&c&lPhantom Effects")); + message.add(CC.translate("&c • &fDeal +5% damage to enemies.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oThe phantom awaits you as")); + lore.add(CC.translate("&7&oyour presence is necessary..")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lPhantom Effects")); + lore.add(CC.translate("&c • &fDeal +5% damage to enemies.")); + //lore.add(CC.translate("&7&o(Requires all 4 phantom items.)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "PhantomSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + + } + + @Override + public Material getDisplayMaterial() { + return Material.BLAZE_POWDER; + } + + @Override + public String getDisplayName() { + return "&c&lPhantom"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7An eerie blade designed to")); + lore.add(CC.translate("&7cut through the enemies.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&c&lPhantom Effects")); + lore.add(CC.translate("&c • &fDeal +10% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 phantom set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "PhantomWeapon"); + } + + } + + @Override + public Color getColor() { + return org.bukkit.Color.fromRGB(255, 64, 64); + } + + + @Override + public String getSwordName() { + return "&c&lPhantom Scythe"; + } + + @Override + public int getWeight() { + return 1; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/ReaperArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/ReaperArmorSet.java new file mode 100644 index 0000000..ca3296d --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/ReaperArmorSet.java @@ -0,0 +1,349 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import com.google.common.collect.Lists; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.cooldowns.old.ReaperAbilityCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; + +public class ReaperArmorSet extends ArmorSet implements Weapon, Sword, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 25; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 20; + + + @ConfigValue + private double hellTrapDamagePercentIncreaseToPlayers = 20; + @ConfigValue + private double hellTrapAbilityDurationInSeconds = 7; + @ConfigValue + private double hellTrapFreezeDurationInSeconds = 3; + @ConfigValue + private double hellTrapAbilityChance = 2.5; + @ConfigValue + private String hellTrapDamageMessage = "&4&l[HELL TRAP] +25% DAMAGE"; + + @ConfigValue + private final int hellTrapCooldown = 60; + private final List trapList = Lists.newArrayList(); + + + @Override + public String getName() { + return "REAPER"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&4&lReaper Red Eyes")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&4&lReaper Vest")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&4&lReaper Pants of Cuts")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&4&lReaper Dark Timbs")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&4&lReaper Effects")); + message.add(CC.translate("&4 • &fDeal +35% damage to enemies")); + message.add(CC.translate("&4 • &fEnemies deal 35% less damage to you")); + message.add(CC.translate("&4 • &fReaper Hell Trap Ability.")); + message.add(CC.translate("&4 • &fChance to bypass armored")); + message.add(CC.translate("&4 • &fExtra hearts from iron golem pet")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oWe don't beat the reaper by")); + lore.add(CC.translate("&7&oliving longer, we beat the reaper")); + lore.add(CC.translate("&7&oby living well and living fully.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lReaper Effects")); + lore.add(CC.translate("&4 • &fDeal +35% damage to enemies")); + lore.add(CC.translate("&4 • &fEnemies deal 35% less damage to you")); + lore.add(CC.translate("&4 • &fReaper Hell Trap Ability.")); + lore.add(CC.translate("&4 • &fChance to bypass armored")); + lore.add(CC.translate("&4 • &fExtra hearts from iron golem pet")); + //lore.add(CC.translate("&7(&oRequires all 4 reaper set items.&7)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "ReaperSet"); + + Player victim = (Player) attacked; + for(HellTrapAbility hellTrapAbility : this.trapList) { + if(!checkDistance(victim, hellTrapAbility)) continue; + super.getDamageHandler().increaseDamage(this.hellTrapDamagePercentIncreaseToPlayers, event, "Reaper Helltrap Damage"); + attacker.sendMessage(CC.translate(this.hellTrapDamageMessage)); + } + if(event.isCancelled() || event.getFinalDamage() <= 0) return; + if (ThreadLocalRandom.current().nextInt(101) < hellTrapAbilityChance) { + if (!PVPUtils.canPVP(attacker, (LivingEntity) attacked)) return; + + if (CooldownUtils.isCooldownActive(attacker, "reaperAbility")) { + return; + } + CooldownUtils.registerCooldown(attacker, new ReaperAbilityCooldown("reaperAbility", hellTrapCooldown)); + new HellTrapAbility(attacker); + } + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "ReaperSet"); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.MAGMA_CREAM; + } + + @Override + public String getDisplayName() { + return "&4&lReaper"; + } + + @Override + public String getSwordName() { + return "&4&lReaper's Sickle"; + } + + @Override + public int getWeight() { + return 8; + } + + private boolean checkDistance(Player player, HellTrapAbility hellTrapAbility) { + return !(player.getLocation().distance(hellTrapAbility.location) > 7); + } + + + public class HellTrapAbility { + + private final Location location; + private final List hellBlockTypes = Lists.newArrayList(Material.NETHERRACK, Material.NETHER_BRICK); + private Player player; + private int minX; + private int minY; + private int minZ; + + private int maxX; + private int maxY; + private int maxZ; + + public HellTrapAbility(Player player) { + this.player = player; + this.location = player.getLocation(); + this.setBlocks(); + trapList.add(this); + } + + public boolean isInTrap(Player player) { + Location loc = player.getLocation(); + int x = loc.getBlockX(); + int z = loc.getBlockZ(); + return (x <= maxX && x >= minX) && (z <= maxZ && z >= minZ); + } + + public void setBlocks() { + Location loc = player.getLocation(); + minX = loc.getBlockX() - 5; + minY = loc.getBlockY() - 2; + minZ = loc.getBlockZ() - 5; + maxX = loc.getBlockX() + 5; + maxY = loc.getBlockY() + 1; + maxZ = loc.getBlockZ() + 5; + + List playerList = PVPUtils.getNearbyPlayers(player, 12); + List blockList = Lists.newArrayList(); + + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y < maxY; y++) { + for (int z = minZ; z <= maxZ; z++) { + Block block = loc.getWorld().getBlockAt(x, y, z); + if (!block.getType().isSolid() || block.getType() == Material.AIR || block.getLocation().clone().add(0, 1, 0).getBlock().getType() != Material.AIR) { + continue; + } + blockList.add(block); + } + } + } + + for (Player player : playerList) { + if (isInTrap(player) && player != this.player) { + player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, (int) (hellTrapAbilityDurationInSeconds * 20), 2, true)); + player.setWalkSpeed(0.0F); + } + blockList.forEach(block -> { + Material randMat = getRandomType(); + player.sendBlockChange(block.getLocation(), randMat, (byte) 0); + if (randMat == Material.NETHERRACK) { + player.sendBlockChange(block.getRelative(BlockFace.UP).getLocation(), Material.FIRE, (byte) 0); + } + }); + player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 10, 10); + player.sendMessage(""); + player.sendMessage(CC.translate(StringUtils.getCenteredMessage("&4&l** HELL TRAP ABILITY [&7" + this.player.getName() + "&4&l] **"))); + player.sendMessage(CC.translate("&7&o(Players in the hell trap will take +" + hellTrapDamagePercentIncreaseToPlayers + "% damage from enemies in reaper set.)")); + player.sendMessage(""); + } + + Bukkit.getScheduler().runTaskLater(CrankedArmor.getInstance(), () -> playerList.forEach(eachPlayer -> eachPlayer.setWalkSpeed(0.2F)), (long) hellTrapFreezeDurationInSeconds * 20L); + + Bukkit.getScheduler().runTaskLater(CrankedArmor.getInstance(), ()-> { + blockList.forEach(block -> { + block.getState().update(); + block.getRelative(BlockFace.UP).getState().update(); + }); + playerList.clear(); + blockList.clear(); + delete(); + },(long) (hellTrapAbilityDurationInSeconds * 20)); + } + + public void delete() { + player = null; + trapList.remove(this); + } + + public Material getRandomType() { + return hellBlockTypes.get(new Random().nextInt(hellBlockTypes.size())); + } + + + } + + + /* + @Override + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String name = enchanted ? "&d&lEnchanted Lootbox (&4&lReaper&d&l)" : "&f&lArmor Lootbox (&4&lReaper&f&l)"; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the &4reaper &7set collection", + ""); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + + */ + + /* + @Override + public String getWeaponName() { + return "&8✧ &4&lReaper's Sickle"; + } + + */ + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oWe don't beat the reaper by")); + lore.add(CC.translate("&7&oliving longer, we beat the reaper")); + lore.add(CC.translate("&7&oby living well and living fully.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&4&lReaper Effects")); + lore.add(CC.translate("&4 • &fDeal +15% damage to enemies")); + //lore.add(CC.translate("&7(&oRequires all 4 reaper set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_SWORD, Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(15, event, "ReaperWeapon"); + } + + } + + @Override + public org.bukkit.Color getColor() { + return org.bukkit.Color.fromRGB(199, 0, 0); + } +} + diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/WraithArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/WraithArmorSet.java new file mode 100644 index 0000000..39da40c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/WraithArmorSet.java @@ -0,0 +1,214 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.cooldowns.cadia.WraithAbilityCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class WraithArmorSet extends ArmorSet implements Heroic, Weapon, Sword, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 20; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 20; + @ConfigValue + private double wraithAbilityChance = 3; + + @ConfigValue + private int abilityDuration = 5; + @ConfigValue + private int abilityCooldown = 60; + + private List wraithDamage = new ArrayList<>(); + + @ConfigValue + private double wraithAbilityDamage = 40; + + + @Override + public String getName() { + return "WRAITH"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&d&lGlasses of Travel")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&d&lCompressed Shield")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&d&lObsidian Plated Leggings")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&d&lAnkle Weighted Boots")) + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oAn versatile armorset that holds the")); + lore.add(CC.translate("&7&ocapability of keeping you protected")); + lore.add(CC.translate("&7&owhile having a form of aggression.")); + lore.add(CC.translate("&7&oUtilize the power of the Void to your")); + lore.add(CC.translate("&7&oadvantage.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&d&lWraith Effects")); + lore.add(CC.translate("&d • &fDeal +30% damage to enemies.")); + lore.add(CC.translate("&d • &fEnemies deal 30% less damage to you")); + lore.add(CC.translate("&d • &fPermanent Speed IV effect.")); + lore.add(CC.translate("&d • &fDimensional Rift Ability &7(1.75x dmg)")); + /* + lore.add(CC.translate("")); + lore.add(CC.translate("&d&lAbility:")); + lore.add(CC.translate("&d • &fDimensional Rift ability &7&o(Chance to go")); + lore.add(CC.translate(" &7&oinvisible and deal 2x damage)")); + + */ + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "WraithSet"); + if (wraithDamage.contains(attacker.getUniqueId())) { + super.getDamageHandler().increaseDamage(this.wraithAbilityDamage, event, "WraithAbility"); + } + } + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&d&lWraith Effects")); + message.add(CC.translate("&d • &fDeal +30% damage to enemies.")); + message.add(CC.translate("&d • &fEnemies deal 30% less damage to you")); + message.add(CC.translate("&d • &fPermanent Speed IV effect.")); + message.add(CC.translate("&d • &fDimensional Rift Ability &7(1.75x dmg)")); + /* + message.add(CC.translate("")); + message.add(CC.translate("&d&lAbility:")); + message.add(CC.translate("&d • &fDimensional Rift ability &7&o(Chance to go")); + message.add(CC.translate(" &7&oinvisible and deal 2x damage)")); + + */ + return message; + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "wraithSpeed"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "wraithSpeed"); + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + if (attacker instanceof Player) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "WraithSet"); + } + + if(event.isCancelled() || event.getFinalDamage() <= 0) return; + + //if (attacked.getWorld().getName().equals(ArcadeAPI.WORLD_NAME)) return; + if(CooldownUtils.isCooldownActive(attacked, "WraithAbilityCooldown")) return; + if (Math.random() < wraithAbilityChance / 100) { + TitleUtils.sendTitle(attacked, CC.translate("&d&lDimensional Rift"), CC.translate("&7&o(( 1.75x DMG for " + this.abilityDuration + "s ))"), 0, 2, 1); + CooldownUtils.registerCooldown(attacked, new WraithAbilityCooldown(this.abilityCooldown)); + for (Player other : Bukkit.getOnlinePlayers()) { + if (other.getUniqueId() == attacked.getUniqueId()) continue; + if (other.canSee(attacked)) other.hidePlayer(attacked); + } + wraithDamage.add(attacked.getUniqueId()); + Bukkit.getScheduler().runTaskLaterAsynchronously(CrankedArmor.getInstance(), () -> { + for (Player other : Bukkit.getOnlinePlayers()) { + if (other.getUniqueId() == attacked.getUniqueId()) continue; + if (!other.canSee(attacked)) other.showPlayer(attacked); + } + wraithDamage.remove(attacked.getUniqueId()); + }, abilityDuration * 20L); + } + } + + @Override + public Material getDisplayMaterial() { + return Material.ENDER_PORTAL_FRAME; + } + + @Override + public String getDisplayName() { + return "&d&lWraith"; + } + + @Override + public String getSwordName() { + return "&d&lVoicer"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&d&lWraith Effects:")); + lore.add(CC.translate("&d • &fDeal an extra 10% damage.")); + return lore; + } + + + @Override + public Color getColor() { + return Color.fromRGB(248, 79, 245); + } + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(10, event, "WraithWeapon"); + } + } + + @Override + public int getWeight() { + return 7; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/YetiArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/YetiArmorSet.java new file mode 100644 index 0000000..5fbeabf --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/YetiArmorSet.java @@ -0,0 +1,178 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.struct.*; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class YetiArmorSet extends ArmorSet implements Weapon, Axe, Listener, Heroic, Weighable { + + @ConfigValue + private double damagePercentIncreaseToPlayers = 8; + @ConfigValue + private double damagePercentDecreaseFromPlayers = 8; + + + @Override + public String getName() { + return "YETI"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&b&lYeti Facemask")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe savage mask of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&b&lBloody Yeti Torso")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe impermable chestplate of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&b&lFuzzy Yeti Leggings")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe cosy yet monstrous legs of the Yeti.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&b&lBig-Yeti Boots")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oBigfoot has nothing on these boots.")) + + */ + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&b&lYeti Effects")); + message.add(CC.translate("&b • &fDeal +2.5% damage to enemies.")); + message.add(CC.translate("&b • &fEnemies deal 2.5% less damage to you.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oHidden amongst the icy depths")); + lore.add(CC.translate("&7&oof the antarctic mountains..")); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lYeti Effects")); + lore.add(CC.translate("&b • &fDeal +2.5% damage to enemies.")); + lore.add(CC.translate("&b • &fEnemies deal 2.5% less damage to you.")); + //lore.add(CC.translate("&7&o(Requires all 4 yeti items.)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(this.damagePercentIncreaseToPlayers, event, "YetiSet"); + } + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "YetiSet"); + + } + + @Override + public Material getDisplayMaterial() { + return Material.SNOW_BALL; + } + + @Override + public String getDisplayName() { + return "&b&lYeti"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7A penetrating axe used by a Yeti")); + lore.add(CC.translate("")); + lore.add(CC.translate("&b&lYeti Effects")); + lore.add(CC.translate("&b • &fDeal +7.5% damage to enemies.")); + //lore.add(CC.translate("&7(&oRequires all 4 yeti set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "YetiWeapon"); + } + + } + + + + @Override + public Color getColor() { + return org.bukkit.Color.fromRGB(0, 255, 255); + } + + + @Override + public String getAxeName() { + return "&b&lYeti Maul"; + } + + @Override + public int getWeight() { + return 1; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/YijkiArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/YijkiArmorSet.java new file mode 100644 index 0000000..a55355e --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/armorsets/current/YijkiArmorSet.java @@ -0,0 +1,191 @@ +package net.crankedpvp.crankedarmor.armorsets.current; + +import net.crankedpvp.crankedarmor.cooldowns.YijkiLightningCooldown; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Heroic; +import net.crankedpvp.crankedarmor.struct.Sword; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class YijkiArmorSet extends ArmorSet implements Weapon, Sword, Listener, Heroic, Weighable { + + @ConfigValue + private double damagePercentDecreaseFromPlayers = 25; + + @ConfigValue + private double abilityChance = 3; + @ConfigValue + private int abilityCooldown = 60; + + + @Override + public String getName() { + return "YIJKI"; + } + + @Override + protected ItemStack getHelmet() { + return (new ItemBuilder(Material.DIAMOND_HELMET)) + .setName(CC.translate("&f&lYijki Mask")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oYijki face mask.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getChestplate() { + return (new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .setName(CC.translate("&f&lYijki Torso")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe forbidden mantel of yijki.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getLeggings() { + return (new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .setName(CC.translate("&f&lFabled Robes of Yijki.")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oThe fabled robes of yijki.")) + + */ + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + protected ItemStack getBoots() { + return (new ItemBuilder(Material.DIAMOND_BOOTS)) + .setName(CC.translate("&f&lYijki Footwraps")) + /* + .addLoreLine("") + .addLoreLine(CC.translate("&7&oLight as feather, heavy as stone.")) + + */ + .addEnchantment(Enchantment.DEPTH_STRIDER, 3) + + .addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4) + .addEnchantment(Enchantment.DURABILITY, 3).build(); + } + + @Override + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(""); + message.add(CC.translate("&f&lYijki Effects")); + message.add(CC.translate("&f • &fEnemies deal 7.5% less damage to you.")); + message.add(CC.translate("&f • &fRevenge of Yijki Passive Ability.")); + message.add(""); + return message; + } + + public List getArmorLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7&oFeeling threatened by the Yijki")); + lore.add(CC.translate("&7&othat awaits you round the corner.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lYijki Effects")); + lore.add(CC.translate("&f • &fEnemies deal 7.5% less damage to you.")); + lore.add(CC.translate("&f • &fRevenge of Yijki Passive Ability.")); + //lore.add(CC.translate("&7&o(Requires all 4 yijki items.)")); + return lore; + } + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + } + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) { + super.getDamageHandler().reduceDamage(this.damagePercentDecreaseFromPlayers, event, "YijkiSet"); + + if(CooldownUtils.isCooldownActive(attacked, "YijkiLightning")) return; + if(Math.random() > abilityChance / 100) return; + super.getDamageHandler().reduceDamage(50, event, "YijkiAbility"); + CooldownUtils.registerCooldown(attacked, new YijkiLightningCooldown("YijkiLightning", this.abilityCooldown)); + PVPUtils.strikeLightningCircle(attacked.getLocation()); + + } + + @Override + public Material getDisplayMaterial() { + return Material.NETHER_STALK; + } + + @Override + public String getDisplayName() { + return "&f&lYijki"; + } + + @Override + public List getWeaponLore() { + List lore = new ArrayList<>(); + lore.add(CC.translate("")); + lore.add(CC.translate("&7An absolute massive, corrupted")); + lore.add(CC.translate("&7executioner blade imbued with")); + lore.add(CC.translate("&7highly destructive dark magic.")); + lore.add(CC.translate("")); + lore.add(CC.translate("&f&lYijki Effects")); + lore.add(CC.translate("&f • &fDeal +10% damage to enemies.")); + lore.add(CC.translate("&f • &f+25% Revenge of Yijki Ability.")); + //lore.add(CC.translate("&7(&oRequires all 4 yijki set items.&7)")); + return lore; + } + + /* + @Override + public Material[] getWeaponMaterials() { + return new Material[] { Material.DIAMOND_AXE }; + } + + */ + + @Override + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) { + + if (attacked instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "YijkiWeapon"); + } + + } + + @Override + public Color getColor() { + return org.bukkit.Color.fromRGB(255, 255, 255); + } + + @Override + public String getSwordName() { + return "&f&lYijki Dagger"; + } + + @Override + public int getWeight() { + return 1; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffect.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffect.java new file mode 100644 index 0000000..af87eb6 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffect.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedarmor.bard; + +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; + +import java.util.List; + +public abstract class BardEffect implements Listener { + + public abstract String getName(); + public abstract int getEnergyCost(); + public abstract int getHeldDuration(); + public abstract int getClickedDuration(); + public abstract int getCooldown(); + + public abstract void runEffectWhenHeld(List players); + + public abstract void runEffectWhenClicked(Player player); +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffectCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffectCooldown.java new file mode 100644 index 0000000..96cb8ce --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffectCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.bard; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class BardEffectCooldown extends CurrentCooldown { + public BardEffectCooldown(int durationInSeconds) { + super("BardCooldown", durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffectRegister.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffectRegister.java new file mode 100644 index 0000000..6ab80fa --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/BardEffectRegister.java @@ -0,0 +1,81 @@ +package net.crankedpvp.crankedarmor.bard; + +import lombok.Getter; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.bard.effects.*; +import org.bukkit.Bukkit; + +import java.util.*; + +public class BardEffectRegister { + + @Getter + private static BardEffectRegister instance; + private final Map bardEffects; + + + public BardEffectRegister() { + instance = this; + this.bardEffects = new HashMap<>(); + } + + public void initialize() { + + this.registerAll(new Sugar(), new Feather(), new BlazePowder(), new GhastTear(), new IronIngot()); + + + } + + public void registerAll(BardEffect... bardEffects) { + for (BardEffect bardEffect : bardEffects) { + this.register(bardEffect); + } + } + + public void register(BardEffect bardEffect) { + try { + this.bardEffects.put(bardEffect.getName().toUpperCase(Locale.ROOT), bardEffect); + CrankedArmor.getInstance().getServer().getPluginManager().registerEvents(bardEffect, CrankedArmor.getInstance()); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register bard effect " + bardEffect.getName()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.bardEffects.clear(); + } + + public void unregister(BardEffect bardEffect) { + this.bardEffects.remove(bardEffect.getName()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isBardEffect(String name) { + return (this.getBardEffectFromID(name) != null); + } + + public BardEffect getBardEffectFromID(String name) { + return this.bardEffects.get(name.toUpperCase(Locale.ROOT)); + } + + public BardEffect getBardEffectFromName(String name) { + name = this.getBardEffectIDFromName(name); + if (this.bardEffects.get(name) == null) { + return this.bardEffects.get("SUGAR"); + } + return this.bardEffects.get(name.toUpperCase(Locale.ROOT)); + } + + public String getBardEffectIDFromName(String name) { + return name.replace(" ", "").toUpperCase(Locale.ROOT); + } + + public Collection getBardEffects() { + return Collections.unmodifiableCollection(this.bardEffects.values()); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/cache/BardResistanceCache.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/cache/BardResistanceCache.java new file mode 100644 index 0000000..2c78d0f --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/cache/BardResistanceCache.java @@ -0,0 +1,37 @@ +package net.crankedpvp.crankedarmor.bard.cache; + +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class BardResistanceCache { + + private final Map resistanceCache; + + public BardResistanceCache() { + this.resistanceCache = new HashMap<>(); + } + + public boolean isInCache(Player player) { + return this.resistanceCache.containsKey(player); + } + + public void addPlayerToCache(Player player) { + this.resistanceCache.put(player, System.currentTimeMillis() + 7*1000L); + } + + public void addPlayerToCache(Player player, long time) { + this.resistanceCache.put(player, System.currentTimeMillis() + time); + } + + public void checkCache() { + Set playersInCache = this.resistanceCache.keySet(); + for(Player player : playersInCache) { + if(System.currentTimeMillis() > this.resistanceCache.get(player)) { + this.resistanceCache.remove(player); + } + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/cache/BardStrengthCache.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/cache/BardStrengthCache.java new file mode 100644 index 0000000..5998b0f --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/cache/BardStrengthCache.java @@ -0,0 +1,37 @@ +package net.crankedpvp.crankedarmor.bard.cache; + +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class BardStrengthCache { + + private final Map strengthCache; + + public BardStrengthCache() { + this.strengthCache = new HashMap<>(); + } + + public boolean isInCache(Player player) { + return this.strengthCache.containsKey(player); + } + + public void addPlayerToCache(Player player) { + this.strengthCache.put(player, System.currentTimeMillis() + 7*1000L); + } + + public void addPlayerToCache(Player player, long time) { + this.strengthCache.put(player, System.currentTimeMillis() + time); + } + + public void checkCache() { + Set playersInCache = this.strengthCache.keySet(); + for(Player player : playersInCache) { + if(System.currentTimeMillis() > this.strengthCache.get(player)) { + this.strengthCache.remove(player); + } + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/BlazePowder.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/BlazePowder.java new file mode 100644 index 0000000..cf62a0e --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/BlazePowder.java @@ -0,0 +1,72 @@ +package net.crankedpvp.crankedarmor.bard.effects; + +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketCooldown; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.bard.BardEffect; +import net.crankedpvp.crankedarmor.bard.BardEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class BlazePowder extends BardEffect { + + private final static int POTION_LEVEL = 5; + + @Override + public String getName() { + return "BLAZE_POWDER"; + } + + @Override + public int getEnergyCost() { + return 45; + } + + @Override + public int getHeldDuration() { + return 7; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenHeld(List players) { + for(Player nearbyPlayer : players) { + if(PotionEffectUtils.hasPotionEffect(nearbyPlayer, "BardClickedStrength")) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + CrankedArmor.getInstance().getBardStrengthCache().addPlayerToCache(nearbyPlayer, this.getHeldDuration() * 1000L); + //PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.INCREASE_DAMAGE, 3, "BardHeldStrength", getHeldDuration()); + } + } + + @Override + public void runEffectWhenClicked(Player player) { + LunarClientAPI.getInstance().sendPacket(player, new LCPacketCooldown("bard", TimeUnit.SECONDS.toMillis(this.getCooldown()), Material.GOLD_CHESTPLATE.getId())); + CooldownUtils.registerCooldown(player, new BardEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.INCREASE_DAMAGE, POTION_LEVEL, "BardClickedStrength", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &cStrength " + RomanNumeral.convertToRoman(POTION_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + PotionEffectUtils.addPotionEffect(player, PotionEffectType.INCREASE_DAMAGE, POTION_LEVEL, "BardClickedStrength", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &cStrength " + RomanNumeral.convertToRoman(POTION_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(player); + + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/Feather.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/Feather.java new file mode 100644 index 0000000..9a9c323 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/Feather.java @@ -0,0 +1,75 @@ +package net.crankedpvp.crankedarmor.bard.effects; + + +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketCooldown; +import net.crankedpvp.crankedarmor.bard.BardEffect; +import net.crankedpvp.crankedarmor.bard.BardEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class Feather extends BardEffect { + + @Override + public String getName() { + return "FEATHER"; + } + + @Override + public int getEnergyCost() { + return 25; + } + + @Override + public int getHeldDuration() { + return 4; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 10; + } + + + @Override + public void runEffectWhenHeld(List players) { + for(Player nearbyPlayer : players) { + if(PotionEffectUtils.hasPotionEffect(nearbyPlayer, "BardClickedJump")) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.JUMP, 2, "BardHeldJump", getHeldDuration()); + } + } + + @Override + public void runEffectWhenClicked(Player player) { + LunarClientAPI.getInstance().sendPacket(player, new LCPacketCooldown("bard", TimeUnit.SECONDS.toMillis(this.getCooldown()), Material.GOLD_CHESTPLATE.getId())); + CooldownUtils.registerCooldown(player, new BardEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + int currentLevel = PotionEffectUtils.getPlayerEffectLevel(nearbyPlayer, PotionEffectType.JUMP); + if(currentLevel < 2) currentLevel = 2; + currentLevel++; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.JUMP, currentLevel, "BardClickedJump", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &bJump " + RomanNumeral.convertToRoman(currentLevel) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + int currentLevel = PotionEffectUtils.getPlayerEffectLevel(player, PotionEffectType.JUMP); + if(currentLevel < 2) currentLevel = 2; + currentLevel++; + PotionEffectUtils.addPotionEffect(player, PotionEffectType.JUMP, currentLevel, "BardClickedSpeed", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &bJump " + RomanNumeral.convertToRoman(currentLevel) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(player); + + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/GhastTear.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/GhastTear.java new file mode 100644 index 0000000..962bae5 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/GhastTear.java @@ -0,0 +1,70 @@ +package net.crankedpvp.crankedarmor.bard.effects; + +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketCooldown; +import net.crankedpvp.crankedarmor.bard.BardEffect; +import net.crankedpvp.crankedarmor.bard.BardEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class GhastTear extends BardEffect { + + private final static int EFFECT_LEVEL = 4; + + @Override + public String getName() { + return "GHAST_TEAR"; + } + + @Override + public int getEnergyCost() { + return 40; + } + + @Override + public int getHeldDuration() { + return 5; + } + + @Override + public int getClickedDuration() { + return 6; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenHeld(List players) { + for(Player nearbyPlayer : players) { + if(PotionEffectUtils.hasPotionEffect(nearbyPlayer, "BardClickedRegeneration")) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.REGENERATION, 2, "BardHeldRegeneration", getHeldDuration()); + } + } + + @Override + public void runEffectWhenClicked(Player player) { + LunarClientAPI.getInstance().sendPacket(player, new LCPacketCooldown("bard", TimeUnit.SECONDS.toMillis(this.getCooldown()), Material.GOLD_CHESTPLATE.getId())); + CooldownUtils.registerCooldown(player, new BardEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.REGENERATION, EFFECT_LEVEL, "BardClickedRegeneration", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &dRegeneration " + RomanNumeral.convertToRoman(EFFECT_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + PotionEffectUtils.addPotionEffect(player, PotionEffectType.REGENERATION, EFFECT_LEVEL, "BardClickedRegeneration", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &dRegeneration " + RomanNumeral.convertToRoman(EFFECT_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(player); + + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/IronIngot.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/IronIngot.java new file mode 100644 index 0000000..b058620 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/IronIngot.java @@ -0,0 +1,72 @@ +package net.crankedpvp.crankedarmor.bard.effects; + +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketCooldown; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.bard.BardEffect; +import net.crankedpvp.crankedarmor.bard.BardEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class IronIngot extends BardEffect { + + private final static int EFFECT_LEVEL = 3; + + @Override + public String getName() { + return "IRON_INGOT"; + } + + @Override + public int getEnergyCost() { + return 45; + } + + @Override + public int getHeldDuration() { + return 5; + } + + @Override + public int getClickedDuration() { + return 5; + } + + @Override + public int getCooldown() { + return 25; + } + + + @Override + public void runEffectWhenHeld(List players) { + for(Player nearbyPlayer : players) { + if(PotionEffectUtils.hasPotionEffect(nearbyPlayer, "BardClickedResistance")) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + CrankedArmor.getInstance().getBardResistanceCache().addPlayerToCache(nearbyPlayer, this.getHeldDuration() * 1000L); + //PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.DAMAGE_RESISTANCE, 1, "BardHeldResistance", getHeldDuration()); + } + } + + @Override + public void runEffectWhenClicked(Player player) { + LunarClientAPI.getInstance().sendPacket(player, new LCPacketCooldown("bard", TimeUnit.SECONDS.toMillis(this.getCooldown()), Material.GOLD_CHESTPLATE.getId())); + CooldownUtils.registerCooldown(player, new BardEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.DAMAGE_RESISTANCE, EFFECT_LEVEL, "BardClickedResistance", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &7Resistance " + RomanNumeral.convertToRoman(EFFECT_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + PotionEffectUtils.addPotionEffect(player, PotionEffectType.DAMAGE_RESISTANCE, EFFECT_LEVEL, "BardClickedResistance", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &7Resistance " + RomanNumeral.convertToRoman(EFFECT_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(player); + + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/Sugar.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/Sugar.java new file mode 100644 index 0000000..efb43cf --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/effects/Sugar.java @@ -0,0 +1,74 @@ +package net.crankedpvp.crankedarmor.bard.effects; + +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketCooldown; +import net.crankedpvp.crankedarmor.bard.BardEffect; +import net.crankedpvp.crankedarmor.bard.BardEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class Sugar extends BardEffect { + + @Override + public String getName() { + return "SUGAR"; + } + + @Override + public int getEnergyCost() { + return 30; + } + + @Override + public int getHeldDuration() { + return 7; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenHeld(List players) { + for(Player nearbyPlayer : players) { + if(PotionEffectUtils.hasPotionEffect(nearbyPlayer, "BardClickedSpeed")) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.SPEED, 4, "BardHeldSpeed", getHeldDuration()); + } + } + + @Override + public void runEffectWhenClicked(Player player) { + LunarClientAPI.getInstance().sendPacket(player, new LCPacketCooldown("bard", TimeUnit.SECONDS.toMillis(this.getCooldown()), Material.GOLD_CHESTPLATE.getId())); + CooldownUtils.registerCooldown(player, new BardEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(nearbyPlayer)) continue; + int currentLevel = PotionEffectUtils.getPlayerEffectLevel(nearbyPlayer, PotionEffectType.SPEED); + if(currentLevel < 4) currentLevel = 4; + currentLevel++; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.SPEED, currentLevel, "BardClickedSpeed", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &aSpeed " + RomanNumeral.convertToRoman(currentLevel) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + int currentLevel = PotionEffectUtils.getPlayerEffectLevel(player, PotionEffectType.SPEED); + if(currentLevel < 4) currentLevel = 4; + currentLevel++; + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, currentLevel, "BardClickedSpeed", getClickedDuration()); + new ActionBarUtils(CC.translate("&6Bard&8: &aSpeed " + RomanNumeral.convertToRoman(currentLevel) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(player); + + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/listeners/PlayerListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/listeners/PlayerListener.java new file mode 100644 index 0000000..680893c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/listeners/PlayerListener.java @@ -0,0 +1,44 @@ +package net.crankedpvp.crankedarmor.bard.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.bard.cache.BardResistanceCache; +import net.crankedpvp.crankedarmor.bard.cache.BardStrengthCache; +import net.crankedpvp.crankedutils.CrankedUtils; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class PlayerListener implements Listener { + + private final CrankedArmor plugin; + public PlayerListener(CrankedArmor plugin) { + this.plugin = plugin; + } + + @EventHandler + public void dealMoreDamageWithStrength(EntityDamageByEntityEvent event) { + if(event.getEntity() == null || !(event.getEntity() instanceof Player)) return; + if(event.getDamager() == null || !(event.getDamager() instanceof Player)) return; + + BardStrengthCache bardStrengthCache = this.plugin.getBardStrengthCache(); + + Player player = (Player) event.getDamager(); + if(!bardStrengthCache.isInCache(player)) return; + + CrankedUtils.getInstance().getDamageHandler().increaseDamage(5, event, "Bard Strength"); + } + + @EventHandler + public void receiveLessDamageWithResistance(EntityDamageByEntityEvent event) { + if(event.getEntity() == null || !(event.getEntity() instanceof Player)) return; + if(event.getDamager() == null || !(event.getDamager() instanceof Player)) return; + + BardResistanceCache bardResistanceCache = this.plugin.getBardResistanceCache(); + + Player player = (Player) event.getEntity(); + if(!bardResistanceCache.isInCache(player)) return; + + CrankedUtils.getInstance().getDamageHandler().reduceDamage(5, event, "Bard Resistance"); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/tasks/CheckCachesTask.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/tasks/CheckCachesTask.java new file mode 100644 index 0000000..e2ca9f1 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/bard/tasks/CheckCachesTask.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedarmor.bard.tasks; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import org.bukkit.scheduler.BukkitRunnable; + +public class CheckCachesTask extends BukkitRunnable { + + private CrankedArmor plugin; + public CheckCachesTask(CrankedArmor plugin) { + this.plugin = plugin; + } + + @Override + public void run() { + this.plugin.getBardStrengthCache().checkCache(); + this.plugin.getBardResistanceCache().checkCache(); + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/AdminArmorSetCommand.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/AdminArmorSetCommand.java new file mode 100644 index 0000000..8ecb7a6 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/AdminArmorSetCommand.java @@ -0,0 +1,336 @@ +package net.crankedpvp.crankedarmor.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.inventory.ArmorSetsInventory; +import net.crankedpvp.crankedarmor.language.Language; +import net.crankedpvp.crankedarmor.language.LanguageHandler; +import net.crankedpvp.crankedarmor.struct.*; +import net.crankedpvp.crankedarmor.struct.cache.ArmorSetCache; +import net.crankedpvp.crankedarmor.struct.config.ArmorConfigManager; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GodsetUtils; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +@Command("ca") +@Alias({"sets", "na", "crankedarmor", "armorset", "armorsets"}) +public class AdminArmorSetCommand extends CommandBase { + + private final ArmorConfigManager armorConfigManager; + private final LanguageHandler languageHandler; + + public AdminArmorSetCommand(CrankedArmor plugin) { + this.armorConfigManager = plugin.getArmorConfigManager(); + this.languageHandler = plugin.getLanguageHandler(); + } + + @Default + public void mainCommand(CommandSender sender) { + if(sender.hasPermission("cranked.admin")) { + Language.ADMIN_COMMAND_HELP.send(sender); + return; + } + + Player player = (Player)sender; + + ArmorSetsInventory armorSetsInventory = new ArmorSetsInventory(player); + armorSetsInventory.getUI().open(player); + } + + @SubCommand("sets") + @Alias("view") + public void setsCommand(CommandSender sender) { + if(!(sender instanceof Player)) return; + Player player = (Player)sender; + ArmorSetsInventory armorSetsInventory = new ArmorSetsInventory(player); + armorSetsInventory.getUI().open(player); + } + + @SubCommand("hook") + @WrongUsage("&cUsage: /ca hook [player]") + @Permission("cranked.admin") + public void hookCommand(final CommandSender commandSender, @Completion("#sets") final ArmorSet armorSet, @Completion("#players") @Optional Player player) { + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + if(!(armorSet instanceof Weapon)) { + commandSender.sendMessage(CC.translate("&3&lSets &8➥ &cThis armor set has no weapon(s) attached")); + return; + } + + if (player == null && commandSender instanceof Player) { + player = (Player) commandSender; + } + + if (player != null) { + player.getInventory().addItem(armorSet.tryBuildHook()); + } + } + + @SubCommand("ehook") + @WrongUsage("&cUsage: /ca ehook [player]") + @Permission("cranked.admin") + public void ehookCommand(final CommandSender commandSender, @Completion("#sets") final ArmorSet armorSet, @Completion("#players") @Optional Player player) { + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + if(!(armorSet instanceof Weapon)) { + commandSender.sendMessage(CC.translate("&3&lSets &8➥ &cThis armor set has no weapon(s) attached")); + return; + } + + if (player == null && commandSender instanceof Player) { + player = (Player) commandSender; + } + + if (player != null) { + player.getInventory().addItem(this.applyEnchants(armorSet.tryBuildHook(), false)); + } + } + + @SubCommand("weapon") + @Alias({"sword", "axe", "bow"}) + @WrongUsage("&cUsage: /ca weapon [player]") + @Permission("cranked.admin") + public void weaponCommand(final CommandSender commandSender, @Completion("#sets") final ArmorSet armorSet, @Completion("#players") @Optional Player player) { + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + if(!(armorSet instanceof Weapon)) { + commandSender.sendMessage(CC.translate("&3&lSets &8➥ &cThis armor set has no weapon(s) attached")); + return; + } + + if (player == null && commandSender instanceof Player) { + player = (Player) commandSender; + } + + if (player != null) { + player.getInventory().addItem(this.getWeaponFromSet(armorSet)); + } + } + + + @SubCommand("eweapon") + @Alias({"esword", "eaxe", "ebow"}) + @WrongUsage("&cUsage: /ca eweapon [player]") + @Permission("cranked.admin") + public void enchantedWeaponCommand(final CommandSender commandSender, @Completion("#sets") final ArmorSet armorSet, @Optional @Completion("#players") Player player) { + if (player == null && commandSender instanceof Player) { + player = (Player) commandSender; + } + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + if(!(armorSet instanceof Weapon)) { + commandSender.sendMessage(CC.translate("&3&lSets &8➥ &cThis armor set has no weapon(s) attached")); + return; + } + + + if (player != null) { + player.getInventory().addItem(applyEnchants(this.getWeaponFromSet(armorSet), false)); + } + } + + private ItemStack getWeaponFromSet(ArmorSet armorSet) { + if(!(armorSet instanceof Weapon)) { + return armorSet.applyData(armorSet.getArmorSet().get(ThreadLocalRandom.current().nextInt(4))); + } else { + if(armorSet instanceof Sword) { + return armorSet.tryBuildSword(); + } else if(armorSet instanceof Axe) { + return armorSet.tryBuildAxe(); + } else if(armorSet instanceof Bow) { + return armorSet.tryBuildBow(); + } + } + return null; + } + + @SubCommand("set") + @WrongUsage("&cUsage: /ca set [player]") + @Permission("cranked.admin") + public void setCommand(CommandSender sender, @Completion("#sets") ArmorSet armorSet, @Completion("#players") @Optional Player player) { + + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(sender); + return; + } + + if (player != null) { + armorSet.givePlayerArmorSet(player); + return; + } + + if (sender instanceof Player) { + armorSet.givePlayerArmorSet((Player) sender); + } + } + + @SubCommand("eset") + @Alias("enchantedset") + @WrongUsage("&cUsage: /ca eset [random]") + @Permission("cranked.admin") + public void enchantedSetCommand(CommandSender commandSender, @Completion("#sets") ArmorSet armorSet, @Optional @Completion("#players") Player player) { + + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + List items = armorSet.getSetItemsWithData() + .stream() + .map(item -> applyEnchants(item, false)) + .collect(Collectors.toList()); + + if (player != null) { + items.forEach(itemStack -> player.getInventory().addItem(itemStack)); + return; + } + + if (commandSender instanceof Player) { + Player sender = (Player) commandSender; + items.forEach(itemStack -> sender.getInventory().addItem(itemStack)); + } + } + + + @SubCommand("lootbox") + @WrongUsage("&cUsage: /ca lootbox [player]") + @Permission("cranked.admin") + public void lootboxCommand(CommandSender sender, @Completion("#sets") ArmorSet armorSet, @Optional @Completion("#players") Player player) { + + if(player == null) player = (Player) sender; + + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(sender); + return; + } + + armorSet.givePlayerArmorSetLootbox(player, false, false); + } + + @SubCommand("elootbox") + @Alias("enchantedlootbox") + @WrongUsage("&cUsage: /ca elootbox [random]") + @Permission("cranked.admin") + public void elootboxCommand(CommandSender sender, @Completion("#sets") ArmorSet armorSet, @Optional @Completion("#players") Player player) { + + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(sender); + return; + } + + if (player != null) { + armorSet.givePlayerArmorSetLootbox(player, true, false); + return; + } + + if (sender instanceof Player) { + armorSet.givePlayerArmorSetLootbox((Player) sender, true, false); + } + } + + @SubCommand("bundle") + @WrongUsage("&cUsage: /ca bundle [player]") + @Permission("cranked.admin") + public void bundleCommand(CommandSender sender, @Completion("#sets") ArmorSet armorSet, @Optional @Completion("#players") Player player) { + + if(player == null) player = (Player) sender; + + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(sender); + return; + } + + armorSet.givePlayerArmorSetBundle(player, false, false); + } + + @SubCommand("ebundle") + @Alias("enchantedbundle") + @WrongUsage("&cUsage: /ca ebundle [random]") + @Permission("cranked.admin") + public void ebundleCommand(CommandSender sender, @Completion("#sets") ArmorSet armorSet, @Optional @Completion("#players") Player player) { + + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(sender); + return; + } + + if (player != null) { + armorSet.givePlayerArmorSetBundle(player, true, false); + return; + } + + if (sender instanceof Player) { + armorSet.givePlayerArmorSetBundle((Player) sender, true, false); + } + } + + @SubCommand("reload") + @WrongUsage("&cUsage: /ca reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + this.languageHandler.load(); + this.armorConfigManager.reloadFiles(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } + + @SubCommand("debug") + @WrongUsage("&cUsage: /ca debug") + @Permission("cranked.admin") + public void debugCommand(Player sender) { + ArmorSetCache armorSetCache = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer(sender).getCache("armor_set"); + armorSetCache.getArmorSets().forEach((armorset, amount) -> { + System.out.println(armorset.getID() + " -> " + amount); + }); + try { + System.out.println(CrankedArmorAPI.getCurrentArmorSet(sender).getID()); + } catch(Exception e) { + System.out.println("No Armor Set"); + } + } + + private ItemStack applyEnchants(ItemStack itemStack, boolean random) { + EnchantRegister enchantRegister = CrankedEnchants.getInstance().getEnchantRegister(); + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + for(String enchantName : GodsetUtils.enchantments.get(itemStack.getType().name().split("_")[1].toLowerCase())) { + Enchantment enchantment = enchantRegister.getEnchantmentFromID(enchantName); + int level = random ? enchantment.getRandomLevel() : enchantment.getMax(); + enchantedItemBuilder.addEnchantment(enchantment, level); + } + + enchantedItemBuilder.sortEnchantLore(); + enchantedItemBuilder.setProtected(true); + + return enchantedItemBuilder.build(); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/BardEffectsCommand.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/BardEffectsCommand.java new file mode 100644 index 0000000..5b1b61d --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/BardEffectsCommand.java @@ -0,0 +1,54 @@ +package net.crankedpvp.crankedarmor.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; + +@Command("bard") +@Alias({"bardeffect", "bardeffects"}) +public class BardEffectsCommand extends CommandBase { + + private final static double IRON_INGOT_PRICE = 130 * 64; + private final static double SUGAR_PRICE = 5 * 64; + private final static double BLAZE_POWDER_PRICE = 62.5 * 32; + private final static double FEATHER_PRICE = 5 * 64; + private final static double GHAST_TEAR_PRICE = 97.5 * 64; + + private final static ItemStack IRON_INGOT_ITEMSTACK = new ItemBuilder(Material.IRON_INGOT, "&7&lResistance").setAmount(64).colorize().build(); + private final static ItemStack BLAZE_POWDER_ITEMSTACK = new ItemBuilder(Material.BLAZE_POWDER, "&c&lStrength").setAmount(64).colorize().build(); + private final static ItemStack FEATHER_ITEMSTACK = new ItemBuilder(Material.FEATHER, "&b&lJump Boost").setAmount(64).colorize().build(); + private final static ItemStack SUGAR_ITEMSTACK = new ItemBuilder(Material.SUGAR, "&a&lSpeed").setAmount(64).colorize().build(); + private final static ItemStack GHAST_TEAR_ITEMSTACK = new ItemBuilder(Material.GHAST_TEAR, "&d&lRegeneration").setAmount(64).colorize().build(); + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + @Default + public void bardEffectsCommand(final Player player) { + double price = IRON_INGOT_PRICE + SUGAR_PRICE + BLAZE_POWDER_PRICE + FEATHER_PRICE + GHAST_TEAR_PRICE; + if(!EconomyUtils.hasBalance(player, price)) { + player.sendMessage(CC.translate("&6&lBard &8" + Arrow.arrow() + " &cYou need $" + moneyFormat.format(price - EconomyUtils.getBalance(player)) + " more to buy bard effects")); + SoundUtils.tryPlayErrorSound(player); + return; + } + EconomyUtils.withdrawBalance(player, price); + player.sendMessage(CC.translate("&6&lBard &8" + Arrow.arrow() + " &eYou have purchased &7bard effects &efor &a$"+moneyFormat.format(price))); + SoundUtils.tryPlaySuccessSound(player); + + player.getInventory().addItem(IRON_INGOT_ITEMSTACK.clone()); + player.getInventory().addItem(GHAST_TEAR_ITEMSTACK.clone()); + player.getInventory().addItem(BLAZE_POWDER_ITEMSTACK.clone()); + player.getInventory().addItem(SUGAR_ITEMSTACK.clone()); + player.getInventory().addItem(FEATHER_ITEMSTACK.clone()); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/DebugArmorSetCommand.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/DebugArmorSetCommand.java new file mode 100644 index 0000000..bd59624 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/DebugArmorSetCommand.java @@ -0,0 +1,42 @@ +package net.crankedpvp.crankedarmor.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.cache.ArmorSetCache; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.cache.CachedPlayer; +import org.bukkit.entity.Player; + +import java.util.Map; + +@Command("debugarmor") +public class DebugArmorSetCommand extends CommandBase { + @Default() + @Permission("cranked.admin") + public void defaultCommand(Player sender, @Optional @Completion("#players") Player player) { + if (player == null) { + checkArmor(sender, sender); + } else { + checkArmor(player, sender); + } + } + + public void checkArmor(Player toCheck, Player sender) { + CachedPlayer armorSetPlayer = CrankedUtils.getInstance().getCacheManager().getCachedPlayer(toCheck); + ArmorSetCache cache = (ArmorSetCache) (armorSetPlayer.hasCache("armor_set") ? armorSetPlayer.getCache("armor_set") : armorSetPlayer.registerCache(new ArmorSetCache(toCheck))); + sender.sendMessage(CC.translate("&aChecking armorsets for: " + toCheck.getName())); + if (cache.getCurrentArmorSet() != null) { + sender.sendMessage(CC.translate("&aCurrent ArmorSet: &f" + cache.getCurrentArmorSet().getName())); + } else { + sender.sendMessage(CC.translate("&aCurrent ArmorSet: &fnone")); + + } + sender.sendMessage(CC.translate("&dArmorSets Equipped: &f")); + for (Map.Entry entry : cache.getArmorSets().entrySet()) { + sender.sendMessage(CC.translate("&d * &f" + entry.getKey().getName() + " &8: &7" + entry.getValue())); + } + sender.sendMessage(""); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/HeroicArmorSetCommand.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/HeroicArmorSetCommand.java new file mode 100644 index 0000000..767668f --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/HeroicArmorSetCommand.java @@ -0,0 +1,272 @@ +package net.crankedpvp.crankedarmor.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.inventory.ArmorSetsInventory; +import net.crankedpvp.crankedarmor.language.Language; +import net.crankedpvp.crankedarmor.language.LanguageHandler; +import net.crankedpvp.crankedarmor.struct.*; +import net.crankedpvp.crankedarmor.struct.config.ArmorConfigManager; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GodsetUtils; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +@Command("hca") +@Alias({"heroicarmor", "hsets", "hna", "hcrankedarmor", "harmorset", "harmorsets"}) +public class HeroicArmorSetCommand extends CommandBase { + + private final ArmorConfigManager armorConfigManager; + private final LanguageHandler languageHandler; + + public HeroicArmorSetCommand(CrankedArmor plugin) { + this.armorConfigManager = plugin.getArmorConfigManager(); + this.languageHandler = plugin.getLanguageHandler(); + } + + @Default + public void mainCommand(CommandSender sender) { + if(sender.hasPermission("cranked.admin")) { + Language.ADMIN_COMMAND_HEROIC_HELP.send(sender); + return; + } + + Player player = (Player)sender; + + ArmorSetsInventory armorSetsInventory = new ArmorSetsInventory(player); + armorSetsInventory.getUI().open(player); + } + + @SubCommand("armorupgrade") + @Alias({"au"}) + @WrongUsage("&cUsage: /hca armorupgrade [player]") + @Permission("cranked.admin") + public void heroicUpgradeCommand(CommandSender sender, @Optional @Completion("#players") Player player) { + if(player == null) player = (Player) sender; + ArmorSet armorSet = ArmorSetRegister.getInstance().getArmorSetFromID("spectre"); + player.getInventory().addItem(armorSet.buildHeroicArmorUpgrade(100)); + player.playSound(player.getLocation(), Sound.LAVA_POP, 2.0f, 2.0f); + player.sendMessage(CC.translate("&aReceived heroic upgrade for " + armorSet.getNameWithColor() + " &aset")); + } + + @SubCommand("weaponupgrade") + @WrongUsage("&cUsage: /hca weaponupgrade [player]") + @Permission("cranked.admin") + public void heroicWeaponUpgradeCommand(CommandSender sender, @Optional @Completion("#players") Player player) { + if(player == null) player = (Player) sender; + ArmorSet armorSet = ArmorSetRegister.getInstance().getArmorSetFromID("spectre"); + player.getInventory().addItem(armorSet.buildHeroicWeaponUpgrade(100)); + player.playSound(player.getLocation(), Sound.LAVA_POP, 2.0f, 2.0f); + player.sendMessage(CC.translate("&aReceived heroic upgrade for " + armorSet.getNameWithColor() + " &aweapon")); + } + + @SubCommand("hookupgrade") + @WrongUsage("&cUsage: /hca hookupgrade [player]") + @Permission("cranked.admin") + public void heroicHookUpgradeCommand(CommandSender sender, @Optional @Completion("#players") Player player) { + if(player == null) player = (Player) sender; + ArmorSet armorSet = ArmorSetRegister.getInstance().getArmorSetFromID("spectre"); + player.getInventory().addItem(armorSet.buildHeroicHookUpgrade(100)); + player.playSound(player.getLocation(), Sound.LAVA_POP, 2.0f, 2.0f); + player.sendMessage(CC.translate("&aReceived heroic upgrade for " + armorSet.getNameWithColor() + " &ahook")); + } + + + @SubCommand("hook") + @WrongUsage("&cUsage: /hca hook [player]") + @Permission("cranked.admin") + public void hookCommand(final CommandSender commandSender, @Completion("#sets") final ArmorSet armorSet, @Completion("#players") @Optional Player player) { + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + if(!(armorSet instanceof Weapon)) { + commandSender.sendMessage(CC.translate("&3&lSets &8➥ &cThis armor set has no weapon(s) attached")); + return; + } + + if (player == null && commandSender instanceof Player) { + player = (Player) commandSender; + } + + if (player != null) { + player.getInventory().addItem(CrankedArmorAPI.heroifyHook(armorSet.tryBuildHook(), armorSet)); + } + } + + @SubCommand("ehook") + @WrongUsage("&cUsage: /hca ehook [player]") + @Permission("cranked.admin") + public void ehookCommand(final CommandSender commandSender, @Completion("#sets") final ArmorSet armorSet, @Completion("#players") @Optional Player player) { + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + if(!(armorSet instanceof Weapon)) { + commandSender.sendMessage(CC.translate("&3&lSets &8➥ &cThis armor set has no weapon(s) attached")); + return; + } + + if (player == null && commandSender instanceof Player) { + player = (Player) commandSender; + } + + if (player != null) { + player.getInventory().addItem(this.applyEnchants(CrankedArmorAPI.heroifyHook(armorSet.tryBuildHook(), armorSet), false)); + } + } + + @SubCommand("weapon") + @Alias({"sword", "axe", "bow"}) + @WrongUsage("&cUsage: /hca weapon [player]") + @Permission("cranked.admin") + public void weaponCommand(final CommandSender commandSender, @Completion("#sets") final ArmorSet armorSet, @Completion("#players") @Optional Player player) { + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + if(!(armorSet instanceof Weapon)) { + commandSender.sendMessage(CC.translate("&3&lSets &8➥ &cThis armor set has no weapon(s) attached")); + return; + } + + if (player == null && commandSender instanceof Player) { + player = (Player) commandSender; + } + + if (player != null) { + player.getInventory().addItem(CrankedArmorAPI.heroifyWeapon(this.getWeaponFromSet(armorSet), armorSet)); + } + } + + @SubCommand("eweapon") + @Alias({"esword", "eaxe", "ebow"}) + @WrongUsage("&cUsage: /hca eweapon [player]") + @Permission("cranked.admin") + public void enchantedWeaponCommand(final CommandSender commandSender, @Completion("#sets") final ArmorSet armorSet, @Optional @Completion("#players") Player player) { + if (player == null && commandSender instanceof Player) { + player = (Player) commandSender; + } + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + if(!(armorSet instanceof Weapon)) { + commandSender.sendMessage(CC.translate("&3&lSets &8➥ &cThis armor set has no weapon(s) attached")); + return; + } + + + if (player != null) { + player.getInventory().addItem(applyEnchants(CrankedArmorAPI.heroifyWeapon(this.getWeaponFromSet(armorSet), armorSet), false)); + } + } + + + + @SubCommand("set") + @WrongUsage("&cUsage: /hca set [player]") + @Permission("cranked.admin") + public void setCommand(CommandSender sender, @Completion("#sets") ArmorSet armorSet, @Completion("#players") @Optional Player player) { + + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(sender); + return; + } + + if (player != null) { + armorSet.givePlayerHeroifiedArmorSet(player); + return; + } + + if (sender instanceof Player) { + armorSet.givePlayerHeroifiedArmorSet((Player) sender); + } + } + + @SubCommand("eset") + @Alias("enchantedset") + @WrongUsage("&cUsage: /hca eset [random]") + @Permission("cranked.admin") + public void enchantedSetCommand(CommandSender commandSender, @Completion("#sets") ArmorSet armorSet, @Optional @Completion("#players") Player player) { + + if (armorSet == null) { + Language.INVALID_ARMOR_SET.send(commandSender); + return; + } + + List items = armorSet.getSetItemsWithData() + .stream() + .map(itemStack -> CrankedArmorAPI.heroifyArmor(itemStack, armorSet)) + .map(item -> applyEnchants(item, false)) + .collect(Collectors.toList()); + + if (player != null) { + items.forEach(itemStack -> player.getInventory().addItem(itemStack)); + return; + } + + if (commandSender instanceof Player) { + Player sender = (Player) commandSender; + items.forEach(itemStack -> sender.getInventory().addItem(itemStack)); + } + } + + + + + + + + + + + private ItemStack getWeaponFromSet(ArmorSet armorSet) { + if(!(armorSet instanceof Weapon)) { + return armorSet.applyData(armorSet.getArmorSet().get(ThreadLocalRandom.current().nextInt(4))); + } else { + if(armorSet instanceof Sword) { + return armorSet.tryBuildSword(); + } else if(armorSet instanceof Axe) { + return armorSet.tryBuildAxe(); + } else if(armorSet instanceof Bow) { + return armorSet.tryBuildBow(); + } + } + return null; + } + + + + private ItemStack applyEnchants(ItemStack itemStack, boolean random) { + EnchantRegister enchantRegister = CrankedEnchants.getInstance().getEnchantRegister(); + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + for(String enchantName : GodsetUtils.enchantments.get(itemStack.getType().name().split("_")[1].toLowerCase())) { + Enchantment enchantment = enchantRegister.getEnchantmentFromID(enchantName); + int level = random ? enchantment.getRandomLevel() : enchantment.getMax(); + enchantedItemBuilder.addEnchantment(enchantment, level); + } + + enchantedItemBuilder.sortEnchantLore(); + enchantedItemBuilder.setProtected(true); + + return enchantedItemBuilder.build(); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/MageEffectsCommand.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/MageEffectsCommand.java new file mode 100644 index 0000000..c157c50 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/commands/MageEffectsCommand.java @@ -0,0 +1,52 @@ +package net.crankedpvp.crankedarmor.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; + +@Command("mage") +@Alias({"mageeffect", "mageeffects"}) +public class MageEffectsCommand extends CommandBase { + + private static final int price = 15000; + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final static ItemStack SEEDS_ITEMSTACK = new ItemBuilder(Material.SEEDS, "&b&lNausea II").setAmount(64).colorize().build(); + private final static ItemStack COAL_ITEMSTACK = new ItemBuilder(Material.COAL, "&b&lWeakness II").setAmount(64).colorize().build(); + private final static ItemStack GOLD_NUGGET_ITEMSTACK = new ItemBuilder(Material.GOLD_NUGGET, "&b&lSlowness II").setAmount(64).colorize().build(); + private final static ItemStack ROTTEN_FLESH_ITEMSTACK = new ItemBuilder(Material.ROTTEN_FLESH, "&b&lHunger II").setAmount(64).colorize().build(); + private final static ItemStack INK_SACK_ITEMSTACK = new ItemBuilder(Material.INK_SACK, "&b&lPoison I").setDurability(DyeColor.GREEN.getDyeData()).setAmount(64).colorize().build(); + private final static ItemStack SPIDER_EYE_ITEMSTACK = new ItemBuilder(Material.SPIDER_EYE, "&b&lWither II").setAmount(64).colorize().build(); + + @Default + public void mageEffectsCommand(final Player player) { + if(!EconomyUtils.hasBalance(player, price)) { + player.sendMessage(CC.translate("&2&lMage &8" + Arrow.arrow() + " &cYou need $" + moneyFormat.format(price - EconomyUtils.getBalance(player)) + " more to buy mage effects")); + SoundUtils.tryPlayErrorSound(player); + return; + } + EconomyUtils.withdrawBalance(player, price); + player.sendMessage(CC.translate("&2&lMage &8" + Arrow.arrow() + " &eYou have purchased &7mage effects &efor &a$"+moneyFormat.format(price))); + SoundUtils.tryPlaySuccessSound(player); + + player.getInventory().addItem(COAL_ITEMSTACK); + player.getInventory().addItem(GOLD_NUGGET_ITEMSTACK); + player.getInventory().addItem(INK_SACK_ITEMSTACK); + player.getInventory().addItem(ROTTEN_FLESH_ITEMSTACK); + player.getInventory().addItem(SEEDS_ITEMSTACK); + player.getInventory().addItem(SPIDER_EYE_ITEMSTACK); + } +} \ No newline at end of file diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/ArmorSetCooldownCache.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/ArmorSetCooldownCache.java new file mode 100644 index 0000000..1031c2c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/ArmorSetCooldownCache.java @@ -0,0 +1,17 @@ +package net.crankedpvp.crankedarmor.cooldowns; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class ArmorSetCooldownCache extends CurrentCooldown { + + public ArmorSetCooldownCache(ArmorSet armorSet, int duration) { + super("armor_cooldown_" + armorSet.getID(), duration); + } + + public ArmorSetCooldownCache(String armorID, int duration) { + super("armor_cooldown_" + armorID, duration); + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/YijkiLightningCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/YijkiLightningCooldown.java new file mode 100644 index 0000000..6969d6c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/YijkiLightningCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class YijkiLightningCooldown extends CurrentCooldown { + public YijkiLightningCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/DiabloDevourEfectCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/DiabloDevourEfectCooldown.java new file mode 100644 index 0000000..1d4fa7d --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/DiabloDevourEfectCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.cadia; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class DiabloDevourEfectCooldown extends CurrentCooldown { + public DiabloDevourEfectCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/InfernoAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/InfernoAbilityCooldown.java new file mode 100644 index 0000000..1019545 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/InfernoAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.cadia; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class InfernoAbilityCooldown extends CurrentCooldown { + public InfernoAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/PiratePhoenixCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/PiratePhoenixCooldown.java new file mode 100644 index 0000000..c380cba --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/PiratePhoenixCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.cadia; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class PiratePhoenixCooldown extends CurrentCooldown { + public PiratePhoenixCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/WraithAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/WraithAbilityCooldown.java new file mode 100644 index 0000000..a0bd9ca --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/cadia/WraithAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.cadia; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class WraithAbilityCooldown extends CurrentCooldown { + public WraithAbilityCooldown(int durationInSeconds) { + super("WraithAbilityCooldown", durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/DracoAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/DracoAbilityCooldown.java new file mode 100644 index 0000000..e01797f --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/DracoAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.old; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class DracoAbilityCooldown extends CurrentCooldown { + public DracoAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/GamblerAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/GamblerAbilityCooldown.java new file mode 100644 index 0000000..7fa83f0 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/GamblerAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.old; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class GamblerAbilityCooldown extends CurrentCooldown { + public GamblerAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/HeadlessAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/HeadlessAbilityCooldown.java new file mode 100644 index 0000000..1256089 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/HeadlessAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.old; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class HeadlessAbilityCooldown extends CurrentCooldown { + public HeadlessAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/JuggernautAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/JuggernautAbilityCooldown.java new file mode 100644 index 0000000..946a2c3 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/JuggernautAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.old; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class JuggernautAbilityCooldown extends CurrentCooldown { + public JuggernautAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/LucidAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/LucidAbilityCooldown.java new file mode 100644 index 0000000..b97201b --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/LucidAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.old; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class LucidAbilityCooldown extends CurrentCooldown { + public LucidAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/ReaperAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/ReaperAbilityCooldown.java new file mode 100644 index 0000000..2d1bad2 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/ReaperAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.old; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class ReaperAbilityCooldown extends CurrentCooldown { + public ReaperAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/SpectreAbilityCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/SpectreAbilityCooldown.java new file mode 100644 index 0000000..40a751b --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/cooldowns/old/SpectreAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.cooldowns.old; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class SpectreAbilityCooldown extends CurrentCooldown { + public SpectreAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/events/ArmorSetEquipEvent.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/events/ArmorSetEquipEvent.java new file mode 100644 index 0000000..c0960e1 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/events/ArmorSetEquipEvent.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedarmor.events; + +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@Getter +public class ArmorSetEquipEvent extends Event implements Cancellable { + + private final Player player; + private final ArmorSet setType; + private boolean cancelled; + private static final HandlerList handlers = new HandlerList(); + + public ArmorSetEquipEvent(Player player, ArmorSet type) { + this.player = player; + this.setType = type; + this.cancelled = false; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorItemsSubCategory.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorItemsSubCategory.java new file mode 100644 index 0000000..cba8d0e --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorItemsSubCategory.java @@ -0,0 +1,58 @@ +package net.crankedpvp.crankedarmor.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class ArmorItemsSubCategory { + private final Gui armorItemsSubCategory; + + public Gui getUI() { + return this.armorItemsSubCategory; + } + + public ArmorItemsSubCategory(Player player, SubCategoryType subCategoryType) { + this.armorItemsSubCategory = new Gui(2, "Armor Items"); + this.armorItemsSubCategory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.armorItemsSubCategory.setItem(8, new GuiItem(createBackButton(), event -> { + player.closeInventory(); + ArmorSetsInventory armorSetsInventory = new ArmorSetsInventory(player); + armorSetsInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 2.0F); + })); + + + for(ArmorSet armorSet : CrankedArmor.getInstance().getArmorSetRegister().getArmorSets()) { + ItemBuilder itemBuilder = new ItemBuilder(subCategoryType.getMaterial(), subCategoryType.getName().replace("%set%", armorSet.getDisplayName())); + this.armorItemsSubCategory.addItem(new GuiItem(itemBuilder.colorizeName().build(), event -> { + if(player.hasPermission("cranked.admin")) runEvent(armorSet, player, subCategoryType); + })); + } + } + + private void runEvent(ArmorSet armorSet, Player player, SubCategoryType subCategoryType) { + player.playSound(player.getLocation(), Sound.CHICKEN_EGG_POP, 2.0F, 2.0F); + switch(subCategoryType) { + case PLAIN: + armorSet.givePlayerArmorSetLootbox(player, false, false); + break; + case ENCHANTED_MAX: + armorSet.givePlayerArmorSetLootbox(player, true, false); + break; + case ENCHANTED_RANDOM: + armorSet.givePlayerArmorSetLootbox(player, true, true); + break; + } + } + + private ItemStack createBackButton() { + return new ItemBuilder(Material.ARROW, "&c<-- Go Back").setGlowing().colorize().build(); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorSetSubCategory.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorSetSubCategory.java new file mode 100644 index 0000000..f4331b3 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorSetSubCategory.java @@ -0,0 +1,75 @@ +package net.crankedpvp.crankedarmor.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.struct.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class ArmorSetSubCategory { + private final Gui armorSetsInventory; + + public Gui getUI() { + return this.armorSetsInventory; + } + + public ArmorSetSubCategory(Player player, String setName) { + this.armorSetsInventory = new Gui(2, "Armor Set: " + setName); + this.armorSetsInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.armorSetsInventory.setItem(8, new GuiItem(createBackButton(), event -> { + player.closeInventory(); + ArmorSetsInventory armorSetsInventory = new ArmorSetsInventory(player); + armorSetsInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 2.0F); + })); + + + ArmorSet armorSet = CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID(setName); + armorSet.getSetItemsWithData().forEach(itemStack -> this.armorSetsInventory.addItem(new GuiItem(itemStack, event -> { + if(player.hasPermission("cranked.admin")) player.getInventory().addItem(event.getCurrentItem()); + }))); + if(armorSet instanceof Weapon) { + if(armorSet instanceof Sword) this.armorSetsInventory.addItem(new GuiItem(armorSet.tryBuildSword(), event -> { + if(player.hasPermission("cranked.admin")) player.getInventory().addItem(event.getCurrentItem()); + })); + if(armorSet instanceof Axe) this.armorSetsInventory.addItem(new GuiItem(armorSet.tryBuildAxe(), event -> { + if(player.hasPermission("cranked.admin")) player.getInventory().addItem(event.getCurrentItem()); + })); + if(armorSet instanceof Bow) this.armorSetsInventory.addItem(new GuiItem(armorSet.tryBuildBow(), event -> { + if(player.hasPermission("cranked.admin")) player.getInventory().addItem(event.getCurrentItem()); + })); + + } + if(player.hasPermission("cranked.admin")) this.armorSetsInventory.addItem(new GuiItem(collectSetButton(setName), event -> armorSet.getSetItemsWithData().forEach(itemStack -> player.getInventory().addItem(itemStack)))); + if(player.hasPermission("cranked.admin")) this.armorSetsInventory.addItem(new GuiItem(getPlainLootboxButton(setName), event -> armorSet.givePlayerArmorSetLootbox(player, false, false))); + if(player.hasPermission("cranked.admin")) this.armorSetsInventory.addItem(new GuiItem(getEnchantedLootboxButton(setName), event -> armorSet.givePlayerArmorSetLootbox(player, true, false))); + if(player.hasPermission("cranked.admin")) this.armorSetsInventory.addItem(new GuiItem(getEnchantedLootboxButtonRandom(setName), event -> armorSet.givePlayerArmorSetLootbox(player, true, true))); + } + + private ItemStack createBackButton() { + return new ItemBuilder(Material.ARROW, "&c<-- Go Back").setGlowing().colorize().build(); + } + + private ItemStack collectSetButton(String setName) { + return new ItemBuilder(Material.REDSTONE_TORCH_ON, "&aCollect Full Armor Set", "&7Click this button to collect the", "&7full " + setName + " armor set").colorize().build(); + } + + private ItemStack getPlainLootboxButton(String setName) { + return new ItemBuilder(Material.CHEST, "&6Set Lootbox: &fPlain", "&7Click this button to collect the", "&7plain armor lootbox for the " + setName + " armor set").colorize().build(); + } + + private ItemStack getEnchantedLootboxButtonRandom(String setName) { + return new ItemBuilder(Material.ENDER_CHEST, "&6Set Lootbox: &dEnchanted &7(Random Level Enchants)", "&7Click this button to collect the", "&7enchanted armor lootbox for the " + setName + " armor set").colorize().build(); + } + + private ItemStack getEnchantedLootboxButton(String setName) { + return new ItemBuilder(Material.ENDER_CHEST, "&6Set Lootbox: &dEnchanted", "&7Click this button to collect the", "&7enchanted armor lootbox for the " + setName + " armor set").colorize().build(); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorSetsInventory.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorSetsInventory.java new file mode 100644 index 0000000..d58b469 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/ArmorSetsInventory.java @@ -0,0 +1,94 @@ +package net.crankedpvp.crankedarmor.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; + +public class ArmorSetsInventory { + private final Gui armorSetsInventory; + + public Gui getUI() { + return this.armorSetsInventory; + } + + Collection armorSets = CrankedArmor.getInstance().getArmorSetRegister().getArmorSets(); + public ArmorSetsInventory(Player player) { + this.armorSetsInventory = new Gui(4, "Armor Sets"); + this.armorSetsInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + List armorSetList = new ArrayList<>(armorSets); + armorSetList.sort(Comparator.comparing(armorSet -> { + if(!(armorSet instanceof Weighable)) return 0; + return ((Weighable) armorSet).getWeight(); + })); + //armorSetList.removeIf(armorSet -> armorSet instanceof Weighable && ((Weighable)armorSet).getWeight() <= 0); + + this.armorSetsInventory.getFiller().fillTop(GuiUtil.createFillerGuiItem()); + this.armorSetsInventory.getFiller().fillBottom(GuiUtil.createFillerGuiItem()); + this.armorSetsInventory.setItem(1, 5, new GuiItem(getSetHierarchyItem())); + for(ArmorSet armorSet : armorSetList) { + this.armorSetsInventory.addItem(new GuiItem(armorSet.getDisplayItem(), event -> { + player.closeInventory(); + ArmorSetSubCategory armorSetSubCategory = new ArmorSetSubCategory(player, armorSet.getID()); + armorSetSubCategory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + })); + } + /* + + if(player.hasPermission("cranked.admin")) { + addBundleButton(player); + addPremadeBundleButton(player); + //addEnchantedRandomSetLootboxSubCategoryButton(player); + } + + */ + } + + private ItemStack getSetHierarchyItem() { + return new ItemBuilder(Material.LADDER, "&d&lSets Ladder", + "&7Below is an ordered list of sets.", + "&7It shows which sets are the worst, and which", + "&7are the best. It also shows you each sets", + "&7abilities and effects.").colorize().build(); + } + + private void addBundleButton(Player player) { + ItemBuilder itemBuilder = new ItemBuilder(Material.CHEST, "&f&lPlain Set Lootboxes", "&7Click to view the plain set", "&7lootboxes"); + this.armorSetsInventory.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + ArmorItemsSubCategory armorItemsSubCategory = new ArmorItemsSubCategory(player, SubCategoryType.PLAIN); + armorItemsSubCategory.getUI().open(player); + })); + } + + + private void addEnchantedRandomSetLootboxSubCategoryButton(Player player) { + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, "&d&lEnchanted Random Set Lootboxes", "&7Click to view the enchanted random", "&7set lootboxes"); + this.armorSetsInventory.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + ArmorItemsSubCategory armorItemsSubCategory = new ArmorItemsSubCategory(player, SubCategoryType.ENCHANTED_RANDOM); + armorItemsSubCategory.getUI().open(player); + })); + } + + private void addPremadeBundleButton(Player player) { + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, "&d&lEnchanted Max Set Lootboxes", "&7Click to view the enchanted max", "&7set lootboxes"); + this.armorSetsInventory.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + ArmorItemsSubCategory armorItemsSubCategory = new ArmorItemsSubCategory(player, SubCategoryType.ENCHANTED_MAX); + armorItemsSubCategory.getUI().open(player); + })); + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/SubCategoryType.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/SubCategoryType.java new file mode 100644 index 0000000..e6cf36e --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/inventory/SubCategoryType.java @@ -0,0 +1,21 @@ +package net.crankedpvp.crankedarmor.inventory; + +import lombok.Getter; +import org.bukkit.Material; + +@Getter +public enum SubCategoryType { + PLAIN(Material.CHEST, "&e&lPlain Armor Set (%set%&e&l)"), + ENCHANTED_MAX(Material.ENDER_CHEST, "&d&lMax Enchanted Set (%set%&d&l)"), + ENCHANTED_RANDOM(Material.ENDER_CHEST, "&d&lRandom Enchanted Set (%set%&d&l)") + ; + + private final Material material; + private final String name; + + SubCategoryType(Material material, String name) { + this.material = material; + this.name = name; + + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/language/Language.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/language/Language.java new file mode 100644 index 0000000..55a2a41 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/language/Language.java @@ -0,0 +1,105 @@ +package net.crankedpvp.crankedarmor.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + ADMIN_COMMAND_HELP, + ADMIN_COMMAND_HEROIC_HELP, + INVALID_ARMOR_SET, + ADMIN_RELOADING, + ADMIN_RELOADED, + PER_PIECE_HEROIC_REDUCTION, + HEROIC_WEAPON_DAMAGE_INCREASE, + WEIGHTED_PVP_GO_BELOW_0, + WEIGHTED_PVP_DAMAGE_MULTIPLIER, + + NO_SET_DAMAGE_REDUCTION + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return value != null ? value : this.name(); + } + + public String getValue(UnaryOperator function) { + return value != null ? function.apply(value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(getValue(function)); + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/language/LanguageHandler.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/language/LanguageHandler.java new file mode 100644 index 0000000..204a88a --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.crankedarmor.language; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final CrankedArmor plugin; + + public LanguageHandler(CrankedArmor plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/AntiHarvesterListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/AntiHarvesterListener.java new file mode 100644 index 0000000..abac46c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/AntiHarvesterListener.java @@ -0,0 +1,31 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +import java.util.Arrays; +import java.util.List; + +public class AntiHarvesterListener implements Listener { + + private final static List disallowedMaterials = Arrays.asList(Material.DIRT, Material.GRASS); + + @EventHandler + public void onHarvest(PlayerInteractEvent event) { + if(event.getClickedBlock() == null) return; + if(event.getPlayer() == null) return; + if(ItemUtils.isAirOrNull(event.getItem())) return; + if(!event.getItem().getType().name().endsWith("_HOE")) return; + if(event.getAction() == Action.RIGHT_CLICK_BLOCK) { + if(disallowedMaterials.contains(event.getClickedBlock().getType())) return; + } + if(!CrankedArmorAPI.isWeapon(event.getItem())) return; + event.setCancelled(true); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicArmorDamageListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicArmorDamageListener.java new file mode 100644 index 0000000..65e9f3a --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicArmorDamageListener.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.language.Language; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; + +public class HeroicArmorDamageListener implements Listener { + + private static final DamageHandler damageHandler = CrankedUtils.instance.getDamageHandler(); + + @EventHandler + public void onPlayerReceiveDamage(EntityDamageByEntityEvent event) { + if(event.getEntity() == null || event.getDamager() == null) return; + if(!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + int heroicPieces = (int) Arrays.stream(player.getInventory().getArmorContents()).filter(CrankedArmorAPI::isArmorHeroic).count(); + if(heroicPieces < 1) return; + double reductionAmount = Double.parseDouble(Language.PER_PIECE_HEROIC_REDUCTION.getValue()) * heroicPieces; + damageHandler.reduceDamage(reductionAmount, event, "Heroic Pieces: " + heroicPieces); + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicUpgradeListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicUpgradeListener.java new file mode 100644 index 0000000..6f8d4bc --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicUpgradeListener.java @@ -0,0 +1,68 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; + +public class HeroicUpgradeListener implements Listener { + + private final CrankedArmor plugin; + public HeroicUpgradeListener(CrankedArmor plugin) { + this.plugin = plugin; + } + + + @EventHandler + public void heroicUpgradeClickCheckArmor(InventoryClickEvent event) { + if(ItemUtils.isAirOrNull(event.getCurrentItem())) return; + if(ItemUtils.isAirOrNull(event.getCursor())) return; + if(!ItemUtils.isArmor(event.getCurrentItem())) return; + if(!(event.getWhoClicked() instanceof Player)) return; + if(!CrankedArmorAPI.isHeroicArmorUpgrade(event.getCursor())) return; + if(!CrankedArmorAPI.isArmorSet(event.getCurrentItem())) return; + if(CrankedArmorAPI.isArmorHeroic(event.getCurrentItem())) return; + ArmorSet armorSet = CrankedArmorAPI.getSetTypeOnItem(event.getCurrentItem()); + event.setCancelled(true); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + event.setCurrentItem(CrankedArmorAPI.heroifyArmor(event.getCurrentItem(), armorSet)); + } + + @EventHandler + public void heroicUpgradeClickCheckWeapon(InventoryClickEvent event) { + if(ItemUtils.isAirOrNull(event.getCurrentItem())) return; + if(ItemUtils.isAirOrNull(event.getCursor())) return; + if(!ItemUtils.isWeapon(event.getCurrentItem())) return; + if(!(event.getWhoClicked() instanceof Player)) return; + if(!CrankedArmorAPI.isWeapon(event.getCurrentItem())) return; + if(ItemUtils.isTool(event.getCurrentItem())) return; + if(!CrankedArmorAPI.isHeroicWeaponUpgrade(event.getCursor())) return; + if(CrankedArmorAPI.isWeaponHeroic(event.getCurrentItem())) return; + ArmorSet armorSet = CrankedArmorAPI.getArmorSetFromWeaponTypeOfItem(event.getCurrentItem()); + event.setCancelled(true); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + event.setCurrentItem(CrankedArmorAPI.heroifyWeapon(event.getCurrentItem(), armorSet)); + } + + @EventHandler + public void heroicUpgradeClickCheckHook(InventoryClickEvent event) { + if(ItemUtils.isAirOrNull(event.getCurrentItem())) return; + if(ItemUtils.isAirOrNull(event.getCursor())) return; + if(!ItemUtils.isWeapon(event.getCurrentItem())) return; + if(!ItemUtils.isTool(event.getCurrentItem())) return; + if(!(event.getWhoClicked() instanceof Player)) return; + if(!CrankedArmorAPI.isHeroicHookUpgrade(event.getCursor())) return; + if(!CrankedArmorAPI.isWeapon(event.getCurrentItem())) return; + if(CrankedArmorAPI.isWeaponHeroic(event.getCurrentItem())) return; + ArmorSet armorSet = CrankedArmorAPI.getArmorSetFromWeaponTypeOfItem(event.getCurrentItem()); + event.setCancelled(true); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + event.setCurrentItem(CrankedArmorAPI.heroifyHook(event.getCurrentItem(), armorSet)); + } + + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicWeaponDamageListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicWeaponDamageListener.java new file mode 100644 index 0000000..886d17e --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/HeroicWeaponDamageListener.java @@ -0,0 +1,24 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.language.Language; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class HeroicWeaponDamageListener implements Listener { + private static final DamageHandler damageHandler = CrankedUtils.instance.getDamageHandler(); + + @EventHandler + public void onPlayerReceiveDamage(EntityDamageByEntityEvent event) { + if(event.getEntity() == null || event.getDamager() == null) return; + if(!(event.getDamager() instanceof Player)) return; + Player player = (Player) event.getDamager(); + if(!CrankedArmorAPI.isWeaponHeroic(player.getItemInHand())) return; + double increaseAmount = Double.parseDouble(Language.HEROIC_WEAPON_DAMAGE_INCREASE.getValue()); + damageHandler.increaseDamage(increaseAmount, event, "Heroic Weapon"); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/LootboxListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/LootboxListener.java new file mode 100644 index 0000000..3e42c6d --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/LootboxListener.java @@ -0,0 +1,168 @@ +package net.crankedpvp.crankedarmor.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedarmor.struct.*; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GodsetUtils; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.concurrent.ThreadLocalRandom; + +public class LootboxListener implements Listener { + + public LootboxListener() {} + + @EventHandler + public void armorLootboxInteract(PlayerInteractEvent event) { + if(event.getItem() == null || event.getItem().getType() == Material.AIR) return; + if(event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_AIR) return; + if(event.getPlayer() == null) return; + + Player player = event.getPlayer(); + ItemStack itemStack = event.getItem(); + NBTItem nbtItem = new NBTItem(itemStack); + + if(this.hasChecks(nbtItem)) { + if(!this.hasSlots(nbtItem, event.getPlayer())) return; + + event.setCancelled(true); + event.getPlayer().setItemInHand(ItemUtils.decreaseItemStackAmountByOne(event.getItem())); + + String armorSetType = nbtItem.hasKey("armorSetLootboxType") ? nbtItem.getString("armorSetLootboxType") : nbtItem.getString("armorSetBundleType"); + ArmorSet armorSet = ArmorSetRegister.getInstance().getArmorSetFromID(armorSetType); + + if(nbtItem.getString("crankedCustomItem").equals("armorSetLootbox")) { + this.runLootboxCode(nbtItem, armorSet, player); + } else if(nbtItem.getString("crankedCustomItem").equals("armorSetBundle")) { + this.runBundleCode(nbtItem, armorSet, player); + } + + } + } + + private void runBundleCode(NBTItem nbtItem, ArmorSet armorSet, Player player) { + for(ItemStack armorPiece : armorSet.getSetItemsWithData()) { + armorPiece = nbtItem.getBoolean("enchanted") ? nbtItem.getBoolean("random") ? applyRandomEnchants(armorPiece) : applyEnchants(armorPiece) : armorPiece; + if(nbtItem.getBoolean("enchanted")) + armorPiece = getItemWithEditedName(nbtItem, armorSet, armorPiece); + player.getInventory().addItem(armorPiece); + } + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + private void runLootboxCode(NBTItem nbtItem, ArmorSet armorSet, Player player) { + ItemStack randomPiece; + if(ThreadLocalRandom.current().nextInt(100) < 10) { + randomPiece = this.choosePiece(armorSet); + } else { + randomPiece = armorSet.applyData(armorSet.getArmorSet().get(ThreadLocalRandom.current().nextInt(4))); + } + randomPiece = nbtItem.getBoolean("enchanted") ? nbtItem.getBoolean("random") ? applyRandomEnchants(randomPiece) : applyEnchants(randomPiece) : randomPiece; + if(nbtItem.getBoolean("enchanted")) + randomPiece = getItemWithEditedName(nbtItem, armorSet, randomPiece); + + player.getInventory().addItem(randomPiece); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + private ItemStack choosePiece(ArmorSet armorSet) { + if(!(armorSet instanceof Weapon)) { + return armorSet.applyData(armorSet.getArmorSet().get(ThreadLocalRandom.current().nextInt(4))); + } else { + if(armorSet instanceof Sword) { + return armorSet.tryBuildSword(); + } else if(armorSet instanceof Axe) { + return armorSet.tryBuildAxe(); + } else if(armorSet instanceof Bow) { + return armorSet.tryBuildBow(); + } + } + return null; + } + + private ItemStack getItemWithEditedName(NBTItem nbtItem, ArmorSet armorSet, ItemStack itemStack) { + String editName = nbtItem.getBoolean("random") ? + "&f&ki&r"+armorSet.getColorAsString()+"✧&f&ki&r &f&l&nRandomised&r " + armorSet.getDisplayName() + " " + armorSet.getColorAsString() + "&l" + StringUtils.getProperCase(itemStack.getType().name().split("_")[1]) + "&r &f&ki&r"+armorSet.getColorAsString()+"✧&f&ki&r" : + "&f&ki&r"+armorSet.getColorAsString()+"✧&f&ki&r &f&l&nPremade&r " + armorSet.getDisplayName() + " " + armorSet.getColorAsString() + "&l" + StringUtils.getProperCase(itemStack.getType().name().split("_")[1]) + "&r &f&ki&r"+armorSet.getColorAsString()+"✧&f&ki&r"; + + ItemBuilder itemBuilder = new ItemBuilder(itemStack); + itemBuilder.setName(editName); + return itemBuilder.colorize().build(); + } + + private boolean hasSlots(NBTItem nbtItem, Player player) { + int slotsNeeded = nbtItem.getString("crankedCustomItem").equals("armorSetBundle") ? 4 : 1; + if(!InventoryUtils.hasAvaliableSlot(player, slotsNeeded)) { + player.sendMessage(CC.translate("&cYour inventory does not have enough open slots to open this")); + player.playSound(player.getLocation(), Sound.LAVA_POP, 1.0F, 1.0F); + return false; + } + return true; + } + + private boolean hasChecks(NBTItem nbtItem) { + return nbtItem.hasNBTData() && + nbtItem.hasKey("crankedCustomItem") && + (nbtItem.getString("crankedCustomItem").equals("armorSetLootbox") || nbtItem.getString("crankedCustomItem").equals("armorSetBundle")) && + (nbtItem.hasKey("armorSetLootboxType") || nbtItem.hasKey("armorSetBundleType")); + } + + + private ItemStack applyEnchants(ItemStack itemStack) { + EnchantRegister enchantRegister = CrankedEnchants.getInstance().getEnchantRegister(); + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + enchantedItemBuilder.setSlots(10); + enchantedItemBuilder.updateSlotsLore(10); + for(String enchantName : GodsetUtils.enchantments.get(itemStack.getType().name().split("_")[1].toLowerCase())) { + Enchantment enchantment = enchantRegister.getEnchantmentFromID(enchantName); + int level = enchantment.getMax(); + enchantedItemBuilder.addEnchantment(enchantment, level); + } + + enchantedItemBuilder.sortEnchantLore(); + + return enchantedItemBuilder.build(); + } + + private ItemStack applyRandomEnchants(ItemStack itemStack) { + EnchantRegister enchantRegister = CrankedEnchants.getInstance().getEnchantRegister(); + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + for(String enchantName : GodsetUtils.enchantments.get(itemStack.getType().name().split("_")[1].toLowerCase())) { + if(chanceOf(0.33)) continue; + Enchantment enchantment = enchantRegister.getEnchantmentFromID(enchantName); + int level = enchantment.getRandomLevel(); + enchantedItemBuilder.addEnchantment(enchantment, level); + } + + enchantedItemBuilder.sortEnchantLore(); + if(chanceOf(0.3)) enchantedItemBuilder.setProtected(true); + if(chanceOf(0.2)) { + enchantedItemBuilder.updateSlotsLore(10); + enchantedItemBuilder.setSlots(10); + } + + return enchantedItemBuilder.build(); + } + + private static boolean chanceOf(double chance) { + return Math.random() < chance; + } + + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/LowerDamageForNoSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/LowerDamageForNoSet.java new file mode 100644 index 0000000..d8d9636 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/LowerDamageForNoSet.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.language.Language; +import net.crankedpvp.crankedarmor.struct.cache.ArmorSetCache; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; + +public class LowerDamageForNoSet implements Listener { + + private static final DamageHandler damageHandler = CrankedUtils.instance.getDamageHandler(); + + @EventHandler(priority = EventPriority.LOW) + public void onAttack(EntityDamageByEntityEvent event) { + Entity attacker = event.getDamager(); + Entity attacked = event.getEntity(); + if (attacked instanceof Player && attacker instanceof Player) { + + Player pAttacked = ((Player) attacked).getPlayer(); + Player pAttacker = ((Player) attacker).getPlayer(); + + if (!WorldGuardUtils.canPvPInRegion(pAttacked) || !WorldGuardUtils.canPvPInRegion(pAttacker)) return; + + ArmorSetCache cacheAttacker = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer(pAttacker).getCache("armor_set"); + ArmorSetCache cacheAttacked = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer(pAttacked).getCache("armor_set"); + + if(hasFullSetEquipped(pAttacker)) { + if (cacheAttacker == null || cacheAttacker.getCurrentArmorSet() == null) { + damageHandler.reduceDamage(Double.parseDouble(Language.NO_SET_DAMAGE_REDUCTION.getValue()), event, "Attacker Has No Set"); + } + } + + if(hasFullSetEquipped(pAttacked)) { + if (cacheAttacked == null || cacheAttacked.getCurrentArmorSet() == null) { + damageHandler.increaseDamage(Double.parseDouble(Language.NO_SET_DAMAGE_REDUCTION.getValue()), event, "Victim Has No Set"); + } + } + } + } + + private boolean hasFullSetEquipped(Player player) { + return Arrays.stream(player.getInventory().getArmorContents()).filter(itemStack -> !ItemUtils.isAirOrNull(itemStack)).count() == 4; + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/PlayerListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/PlayerListener.java new file mode 100644 index 0000000..93c467c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/PlayerListener.java @@ -0,0 +1,139 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.Weapon; +import net.crankedpvp.crankedarmor.struct.cache.ArmorSetCache; +import net.crankedpvp.crankedutils.events.ArmorEquipEvent; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class PlayerListener implements Listener { + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(PlayerJoinEvent event) { + Bukkit.getScheduler().runTaskLater(CrankedArmor.getInstance(), () -> { + CrankedArmorAPI.refreshArmorSets(event.getPlayer()); + }, 30L); + + } + + @EventHandler + public void onDeath(PlayerDeathEvent event) { + if (event.getEntity() != null) { + Bukkit.getScheduler().runTaskLater(CrankedArmor.getInstance(), () -> { + CrankedArmorAPI.refreshArmorSets(event.getEntity()); + }, 30L); + } + } + + /* + @EventHandler(priority = EventPriority.HIGH) + public void onArmorChange(ArmorEquipEvent event) { + ArmorSetCache cache = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer(event.getPlayer()).getCache("armor_set"); + if (event.getOldArmorPiece() != null && event.getOldArmorPiece().getType() != Material.AIR) { + if (CrankedArmorAPI.hasSetTypeOnItem(event.getOldArmorPiece())) + cache.removeArmorSet(CrankedArmorAPI.getSetTypeOnItem(event.getOldArmorPiece())); + } + if (event.getNewArmorPiece() != null && event.getNewArmorPiece().getType() != Material.AIR) { + if (CrankedArmorAPI.hasSetTypeOnItem(event.getNewArmorPiece())) + cache.addArmorSet(CrankedArmorAPI.getSetTypeOnItem(event.getNewArmorPiece())); + } + } + + */ + + @EventHandler(priority = EventPriority.HIGH) + public void onArmorChange(ArmorEquipEvent event) { + ArmorSetCache cache = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer(event.getPlayer()).getCache("armor_set"); + //cache.refresh(); + Bukkit.getScheduler().runTaskLater(CrankedArmor.getInstance(), cache::refresh, 1L); + } + + @EventHandler(priority = EventPriority.LOW) + public void onReceiveDamage(EntityDamageByEntityEvent event) { + Entity attacker = event.getDamager(); + Entity attacked = event.getEntity(); + if (attacked instanceof Player) { + if (!WorldGuardUtils.canPvPInRegion(attacked.getLocation()) || !WorldGuardUtils.canPvPInRegion(attacker.getLocation())) return; + ArmorSetCache cache = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer((Player) attacked).getCache("armor_set"); + if(cache == null) return; + if (cache.getCurrentArmorSet() == null) return; + cache.getCurrentArmorSet().onAttacked((Player) attacked, attacker, event); + + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onSendDamage(EntityDamageByEntityEvent event) { + Entity attacker = event.getDamager(); + Entity attacked = event.getEntity(); + if (attacker instanceof Player) { + if (!WorldGuardUtils.canPvPInRegion(attacked.getLocation()) || !WorldGuardUtils.canPvPInRegion(attacker.getLocation())) return; + ArmorSetCache cache = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer((Player) attacker).getCache("armor_set"); + if(cache == null) return; + if (cache.getCurrentArmorSet() == null) return; + cache.getCurrentArmorSet().onAttack((Player) attacker, attacked, event); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void checkWeaponAttacked(EntityDamageByEntityEvent event) { + if(event.getEntity() == null) return; + if(event.getDamager() == null) return; + + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if(CrankedArmorAPI.isPlayersWeaponSameAsSet(player)) { + ArmorSet armorSet = CrankedArmorAPI.getCurrentArmorSet(player); + if(armorSet == null) + return; + if(!(armorSet instanceof Weapon)) + return; + armorSet.onWeaponAttacked(player, event.getDamager(), event); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void checkWeaponAttack(EntityDamageByEntityEvent event) { + if(event.getEntity() == null) return; + if(event.getDamager() == null) return; + if (!(event.getDamager() instanceof Player)) return; + Player player = (Player) event.getDamager(); + if(CrankedArmorAPI.isPlayersWeaponSameAsSet(player)) { + ArmorSet armorSet = CrankedArmorAPI.getCurrentArmorSet(player); + if(armorSet == null) + return; + if(!(armorSet instanceof Weapon)) + return; + + armorSet.onWeaponAttack(player, event.getEntity(), event); + } + } + + /* + @EventHandler(priority = EventPriority.HIGH) + public void blockPlace(BlockPlaceEvent event) { + if (RavagerArmorSet.antiBlockPlace.contains(event.getPlayer().getUniqueId())) { + event.setCancelled(true); + event.getPlayer().sendMessage(CC.translate("&9&l* RAVAGER SWORD &7[Cancelled Block Place] &9&l*")); + } + } + + */ +} \ No newline at end of file diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/SpectreSetListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/SpectreSetListener.java new file mode 100644 index 0000000..d745696 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/SpectreSetListener.java @@ -0,0 +1,23 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.armorsets.cranked.SpectreArmorSet; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class SpectreSetListener implements Listener { + @EventHandler + public void onDamaged(EntityDamageByEntityEvent e) { + if (e.getEntity() instanceof Player) { + Player attacked = (Player) e.getEntity(); + if (CrankedArmorAPI.getCurrentArmorSet(attacked) != null && CrankedArmorAPI.getCurrentArmorSet(attacked).getID().equals("spectre")) { + SpectreArmorSet spectreSet = (SpectreArmorSet) CrankedArmorAPI.getCurrentArmorSet(attacked); + if (spectreSet.immuneList.contains(attacked.getUniqueId())) { + e.setCancelled(true); + } + } + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/SpiritSetListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/SpiritSetListener.java new file mode 100644 index 0000000..6b001b1 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/SpiritSetListener.java @@ -0,0 +1,17 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedutils.enums.ArmorType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerItemDamageEvent; + +public class SpiritSetListener implements Listener { + @EventHandler + public void onArmorDamage(PlayerItemDamageEvent e) { + if (CrankedArmorAPI.getCurrentArmorSet(e.getPlayer()) != null && CrankedArmorAPI.getCurrentArmorSet(e.getPlayer()).getID().equals("spirit")) { + e.setDamage((int) (e.getDamage()*0.5)); + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/WeightedPvPListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/WeightedPvPListener.java new file mode 100644 index 0000000..74f8238 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/WeightedPvPListener.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedarmor.listeners; + +import net.crankedpvp.crankedarmor.language.Language; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.cache.ArmorSetCache; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.interfaces.Weighable; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class WeightedPvPListener implements Listener { + private static final DamageHandler damageHandler = CrankedUtils.instance.getDamageHandler(); + + + @EventHandler(priority = EventPriority.LOW) + public void onAttack(EntityDamageByEntityEvent event) { + Entity attacker = event.getDamager(); + Entity attacked = event.getEntity(); + if (attacked instanceof Player && attacker instanceof Player) { + Player pAttacked = ((Player) attacked).getPlayer(); + Player pAttacker = ((Player) attacker).getPlayer(); + if (!WorldGuardUtils.canPvPInRegion(pAttacked) || !WorldGuardUtils.canPvPInRegion(pAttacker)) return; + ArmorSetCache cacheAttacker = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer(pAttacker).getCache("armor_set"); + ArmorSetCache cacheAttacked = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer(pAttacked).getCache("armor_set"); + if(cacheAttacker == null || cacheAttacked == null) return; + if (cacheAttacker.getCurrentArmorSet() == null || cacheAttacked.getCurrentArmorSet() == null) return; + if (cacheAttacker.getCurrentArmorSet() instanceof Weighable && cacheAttacked.getCurrentArmorSet() instanceof Weighable) { + Weighable setAttacker = (Weighable) cacheAttacker.getCurrentArmorSet(); + Weighable setAttacked = (Weighable) cacheAttacked.getCurrentArmorSet(); + + int weightAttacker = setAttacker.getWeight(); + int weightAttacked = setAttacked.getWeight(); + + int weightDifference = weightAttacker - weightAttacked; + double weightMultiplier = Double.parseDouble(Language.WEIGHTED_PVP_DAMAGE_MULTIPLIER.getValue()); + if (weightDifference < 0 && !Boolean.parseBoolean(Language.WEIGHTED_PVP_GO_BELOW_0.getValue())) { + weightDifference = 0; + } + + damageHandler.increaseDamage(weightDifference*weightMultiplier, event, "Set Weight (" + weightDifference + " weight diff.)"); + } + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/bard/BardChangeHeldSlotListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/bard/BardChangeHeldSlotListener.java new file mode 100644 index 0000000..4dbae0c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/bard/BardChangeHeldSlotListener.java @@ -0,0 +1,35 @@ +package net.crankedpvp.crankedarmor.listeners.bard; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.bard.BardEffectRegister; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerItemHeldEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.stream.Collectors; + +public class BardChangeHeldSlotListener implements Listener { + + @EventHandler + public void changePlayersHeldSlot(PlayerItemHeldEvent event) { + ItemStack itemStack = event.getPlayer().getInventory().getItem(event.getNewSlot()); + if(ItemUtils.isAirOrNull(itemStack)) return; + if(!CrankedArmorAPI.canUseBardEffects(event.getPlayer())) return; + + BardEffectRegister bardEffectRegister = BardEffectRegister.getInstance(); + String bardEffectName = itemStack.getType().name(); + if(!bardEffectRegister.isBardEffect(bardEffectName)) return; + + List nearByPlayers = PlayerUtils.getNearbyPlayers(event.getPlayer(), 10).stream().filter(player -> FactionUtils.inSameFaction(event.getPlayer(), player)).collect(Collectors.toList()); + bardEffectRegister.getBardEffectFromName(bardEffectName).runEffectWhenHeld(nearByPlayers); + + } + + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/bard/BardClickSlotListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/bard/BardClickSlotListener.java new file mode 100644 index 0000000..0c5bd43 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/bard/BardClickSlotListener.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedarmor.listeners.bard; + +import net.crankedpvp.combatlog.CombatTagAPI; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.bard.BardEffectRegister; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class BardClickSlotListener implements Listener { + + @EventHandler + public void clickBardBuff(PlayerInteractEvent event) { + if(!(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) return; + ItemStack itemStack = event.getItem(); + if(ItemUtils.isAirOrNull(itemStack)) return; + if(!CrankedArmorAPI.canUseBardEffects(event.getPlayer())) return; + if(!WorldGuardUtils.canPvPInRegion(event.getPlayer())) return; + BardEffectRegister bardEffectRegister = BardEffectRegister.getInstance(); + String bardEffectName = itemStack.getType().name(); + if (!bardEffectRegister.isBardEffect(bardEffectName)) return; + if(CooldownUtils.isCooldownActive(event.getPlayer(), "BardCooldown")) { + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ANVIL_LAND, 3.0f, 3.0f); + new ActionBarUtils(CC.translate("&6Bard: &cCooldown: &f" + CooldownUtils.getFormattedCooldown(event.getPlayer(), "BardCooldown"))).sendToPlayer(event.getPlayer()); + event.getPlayer().sendMessage(CC.translate("&6&lBard &8" + Arrow.arrow() + "&cYou are still on cooldown for " + CooldownUtils.getFormattedCooldown(event.getPlayer(), "BardCooldown"))); + return; + } + CombatTagAPI.putPlayerInCombat(event.getPlayer()); + bardEffectRegister.getBardEffectFromName(bardEffectName).runEffectWhenClicked(event.getPlayer()); + event.getPlayer().setItemInHand(ItemUtils.decreaseItemStackAmountByOne(itemStack)); + } + + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/mage/MageClickSlotListener.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/mage/MageClickSlotListener.java new file mode 100644 index 0000000..e9d7ccb --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/listeners/mage/MageClickSlotListener.java @@ -0,0 +1,41 @@ +package net.crankedpvp.crankedarmor.listeners.mage; + +import net.crankedpvp.combatlog.CombatTagAPI; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.mage.MageEffectRegister; +import net.crankedpvp.crankedutils.utils.ActionBarUtils; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class MageClickSlotListener implements Listener { + + @EventHandler + public void clickBardBuff(PlayerInteractEvent event) { + if(!(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) return; + ItemStack itemStack = event.getItem(); + if(ItemUtils.isAirOrNull(itemStack)) return; + if(!CrankedArmorAPI.canUseMageEffects(event.getPlayer())) return; + MageEffectRegister mageEffectRegister = MageEffectRegister.getInstance(); + String mageEffectName = itemStack.getType().name(); + if (!mageEffectRegister.isMageEffect(mageEffectName)) return; + if(CooldownUtils.isCooldownActive(event.getPlayer(), "MageCooldown")) { + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ANVIL_LAND, 3.0f, 3.0f); + new ActionBarUtils(CC.translate("&2Mage: &cCooldown: &f" + CooldownUtils.getFormattedCooldown(event.getPlayer(), "MageCooldown"))).sendToPlayer(event.getPlayer()); + event.getPlayer().sendMessage(CC.translate("&2&lMage &8" + Arrow.arrow() + "&cYou are still on cooldown for " + CooldownUtils.getFormattedCooldown(event.getPlayer(), "MageCooldown"))); + return; + } + CombatTagAPI.putPlayerInCombat(event.getPlayer()); + mageEffectRegister.getMageEffectFromName(mageEffectName).runEffectWhenClicked(event.getPlayer()); + event.getPlayer().setItemInHand(ItemUtils.decreaseItemStackAmountByOne(itemStack)); + } + + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffect.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffect.java new file mode 100644 index 0000000..6ba8dfe --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffect.java @@ -0,0 +1,13 @@ +package net.crankedpvp.crankedarmor.mage; + +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; + +public abstract class MageEffect implements Listener { + + public abstract String getName(); + public abstract int getClickedDuration(); + public abstract int getCooldown(); + + public abstract void runEffectWhenClicked(Player player); +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffectCooldown.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffectCooldown.java new file mode 100644 index 0000000..4995726 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffectCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.mage; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class MageEffectCooldown extends CurrentCooldown { + public MageEffectCooldown(int durationInSeconds) { + super("MageCooldown", durationInSeconds); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffectRegister.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffectRegister.java new file mode 100644 index 0000000..e64c916 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/MageEffectRegister.java @@ -0,0 +1,79 @@ +package net.crankedpvp.crankedarmor.mage; + + +import lombok.Getter; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.mage.effects.*; +import org.bukkit.Bukkit; + +import java.util.*; + +public class MageEffectRegister { + + @Getter + private static MageEffectRegister instance; + private final Map mageEffects; + + + public MageEffectRegister() { + instance = this; + this.mageEffects = new HashMap<>(); + } + + public void initialize() { + this.registerAll(new Coal(), new GoldenNugget(), new InkSack(), new RottenFlesh(), new Seeds(), new SpiderEye()); + } + + public void registerAll(MageEffect... bardEffects) { + for (MageEffect bardEffect : bardEffects) { + this.register(bardEffect); + } + } + + public void register(MageEffect bardEffect) { + try { + this.mageEffects.put(bardEffect.getName().toUpperCase(Locale.ROOT), bardEffect); + CrankedArmor.getInstance().getServer().getPluginManager().registerEvents(bardEffect, CrankedArmor.getInstance()); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register mage effect " + bardEffect.getName()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.mageEffects.clear(); + } + + public void unregister(MageEffect bardEffect) { + this.mageEffects.remove(bardEffect.getName()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isMageEffect(String name) { + return (this.getBardEffectFromID(name) != null); + } + + public MageEffect getBardEffectFromID(String name) { + return this.mageEffects.get(name.toUpperCase(Locale.ROOT)); + } + + public MageEffect getMageEffectFromName(String name) { + name = this.getBardEffectIDFromName(name); + if (this.mageEffects.get(name) == null) { + return this.mageEffects.get("SUGAR"); + } + return this.mageEffects.get(name.toUpperCase(Locale.ROOT)); + } + + public String getBardEffectIDFromName(String name) { + return name.replace(" ", "").toUpperCase(Locale.ROOT); + } + + public Collection getMageEffects() { + return Collections.unmodifiableCollection(this.mageEffects.values()); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/Coal.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/Coal.java new file mode 100644 index 0000000..76f5850 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/Coal.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedarmor.mage.effects; + +import net.crankedpvp.crankedarmor.mage.MageEffect; +import net.crankedpvp.crankedarmor.mage.MageEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class Coal extends MageEffect { + private final static int POTION_LEVEL = 2; + + @Override + public String getName() { + return "COAL"; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenClicked(Player player) { + CooldownUtils.registerCooldown(player, new MageEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!WorldGuardUtils.canPvPInRegion(nearbyPlayer)) continue; + if(FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.WEAKNESS, POTION_LEVEL, "MageClickedWeakness", getClickedDuration()); + new ActionBarUtils(CC.translate("&2Mage&8: &7Weakness " + RomanNumeral.convertToRoman(POTION_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/GoldenNugget.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/GoldenNugget.java new file mode 100644 index 0000000..4a1e9c7 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/GoldenNugget.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedarmor.mage.effects; + +import net.crankedpvp.crankedarmor.mage.MageEffect; +import net.crankedpvp.crankedarmor.mage.MageEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class GoldenNugget extends MageEffect { + private final static int POTION_LEVEL = 2; + + @Override + public String getName() { + return "GOLD_NUGGET"; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenClicked(Player player) { + CooldownUtils.registerCooldown(player, new MageEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!WorldGuardUtils.canPvPInRegion(nearbyPlayer)) continue; + if(FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.SLOW, POTION_LEVEL, "MageClickedSlowness", getClickedDuration()); + new ActionBarUtils(CC.translate("&2Mage&8: &8Slowness " + RomanNumeral.convertToRoman(POTION_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + + + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/InkSack.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/InkSack.java new file mode 100644 index 0000000..e1e5949 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/InkSack.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedarmor.mage.effects; + +import net.crankedpvp.crankedarmor.mage.MageEffect; +import net.crankedpvp.crankedarmor.mage.MageEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class InkSack extends MageEffect { + private final static int POTION_LEVEL = 1; + + @Override + public String getName() { + return "INK_SACK"; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenClicked(Player player) { + CooldownUtils.registerCooldown(player, new MageEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!WorldGuardUtils.canPvPInRegion(nearbyPlayer)) continue; + if(FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.POISON, POTION_LEVEL, "MageClickedPoison", getClickedDuration()); + new ActionBarUtils(CC.translate("&2Mage&8: &aPoison " + RomanNumeral.convertToRoman(POTION_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/RottenFlesh.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/RottenFlesh.java new file mode 100644 index 0000000..cba2eae --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/RottenFlesh.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedarmor.mage.effects; + +import net.crankedpvp.crankedarmor.mage.MageEffect; +import net.crankedpvp.crankedarmor.mage.MageEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class RottenFlesh extends MageEffect { + private final static int POTION_LEVEL = 2; + + @Override + public String getName() { + return "ROTTEN_FLESH"; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenClicked(Player player) { + CooldownUtils.registerCooldown(player, new MageEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!WorldGuardUtils.canPvPInRegion(nearbyPlayer)) continue; + if(FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.HUNGER, POTION_LEVEL, "MageClickedHunger", getClickedDuration()); + new ActionBarUtils(CC.translate("&2Mage&8: &eHunger " + RomanNumeral.convertToRoman(POTION_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/Seeds.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/Seeds.java new file mode 100644 index 0000000..ab77747 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/Seeds.java @@ -0,0 +1,42 @@ +package net.crankedpvp.crankedarmor.mage.effects; + + +import net.crankedpvp.crankedarmor.mage.MageEffect; +import net.crankedpvp.crankedarmor.mage.MageEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class Seeds extends MageEffect { + + private final static int POTION_LEVEL = 2; + + @Override + public String getName() { + return "SEEDS"; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenClicked(Player player) { + CooldownUtils.registerCooldown(player, new MageEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!WorldGuardUtils.canPvPInRegion(nearbyPlayer)) continue; + if(FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.CONFUSION, POTION_LEVEL, "MageClickedNausea", getClickedDuration()); + new ActionBarUtils(CC.translate("&2Mage&8: &7Nausea " + RomanNumeral.convertToRoman(POTION_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/SpiderEye.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/SpiderEye.java new file mode 100644 index 0000000..8ae6f36 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/mage/effects/SpiderEye.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedarmor.mage.effects; + +import net.crankedpvp.crankedarmor.mage.MageEffect; +import net.crankedpvp.crankedarmor.mage.MageEffectCooldown; +import net.crankedpvp.crankedutils.utils.*; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class SpiderEye extends MageEffect { + private final static int POTION_LEVEL = 2; + + @Override + public String getName() { + return "SPIDER_EYE"; + } + + @Override + public int getClickedDuration() { + return 7; + } + + @Override + public int getCooldown() { + return 20; + } + + + @Override + public void runEffectWhenClicked(Player player) { + CooldownUtils.registerCooldown(player, new MageEffectCooldown(this.getCooldown())); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(player, 10)) { + if(!WorldGuardUtils.canPvPInRegion(nearbyPlayer)) continue; + if(FactionUtils.inSameFaction(player, nearbyPlayer)) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.WITHER, POTION_LEVEL, "MageClickedWither", getClickedDuration()); + new ActionBarUtils(CC.translate("&2Mage&8: &8Wither " + RomanNumeral.convertToRoman(POTION_LEVEL) + " &7(" + getClickedDuration() + "s) &8" + Arrow.arrow() + " &7From: &f" + player.getName())).sendToPlayer(nearbyPlayer); + } + + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/managers/HeadlessAbilityManager.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/managers/HeadlessAbilityManager.java new file mode 100644 index 0000000..bc93621 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/managers/HeadlessAbilityManager.java @@ -0,0 +1,115 @@ +package net.crankedpvp.crankedarmor.managers; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.cooldowns.old.HeadlessAbilityCooldown; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class HeadlessAbilityManager implements Listener { + private final Map headless; + + public HeadlessAbilityManager() { + this.headless = new HashMap<>(); + } + + public void activateAbility(Player attacker, Player attacked) { + if (CooldownUtils.isCooldownActive(attacked, "headlessAbility")) return; + CooldownUtils.registerCooldown(attacked, new HeadlessAbilityCooldown("headlessAbility", 300)); + attacker.sendMessage(CC.translate("&6&l** HEADLESS ABILITY &7[" + attacked.getName() + "] &6&l**")); + attacked.sendMessage(CC.translate("&6&l** HEADLESS ABILITY &7[&c" + attacker.getName() + "&7] &6&l**")); + + if (attacked.getInventory().getHelmet() != null) { + headless.put(attacked.getUniqueId(), attacked.getInventory().getHelmet().clone()); + } else { + headless.put(attacked.getUniqueId(), null); + + } + ItemStack pumpkin = new ItemBuilder(Material.JACK_O_LANTERN).setName("&6&lHeadless Ability").addLoreLine("&7&o" + attacker.getName() + "'s Nightmare Armorset Ability.").addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).colorize().build(); + pumpkin = CrankedArmorAPI.addWineArmorOverride(pumpkin, 3); + attacked.getInventory().setHelmet(pumpkin); + Bukkit.getScheduler().runTaskLater(CrankedArmor.getInstance(), () -> { + if(!headless.containsKey(attacked.getUniqueId())) return; + attacked.getInventory().setHelmet(headless.get(attacked.getUniqueId())); + attacked.sendMessage(CC.translate("&6&l** HEADLESS ABILITY &7(Expired) &6&l**")); + headless.remove(attacked.getUniqueId()); + }, 5 * 20L); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamageWhileHeadlessed(EntityDamageByEntityEvent event) { + if(event.getEntity() == null) return; + if(!(event.getEntity() instanceof Player)) return; + + Player victim = ((Player) event.getEntity()); + if(this.headless.containsKey(victim.getUniqueId())) { + CrankedUtils.instance.getDamageHandler().increaseDamage(30, event, "HeadlessAbilityDmg"); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onDeath(PlayerDeathEvent event) { + + if (headless.containsKey(event.getEntity().getUniqueId())) { + event.getDrops().add(headless.get(event.getEntity().getUniqueId())); + event.getDrops().removeIf(item -> item.getType() == Material.JACK_O_LANTERN); + event.getEntity().getInventory().setHelmet(null); + headless.remove(event.getEntity().getUniqueId()); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onKick(PlayerKickEvent event) { + if (headless.containsKey(event.getPlayer().getUniqueId())) { + event.getPlayer().getInventory().setHelmet(headless.get(event.getPlayer().getUniqueId())); + headless.remove(event.getPlayer().getUniqueId()); + + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onQuit(PlayerQuitEvent event) { + if (headless.containsKey(event.getPlayer().getUniqueId())) { + event.getPlayer().getInventory().setHelmet(headless.get(event.getPlayer().getUniqueId())); + headless.remove(event.getPlayer().getUniqueId()); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onArmorSwitch(PlayerInteractEvent event) { + if (headless.containsKey(event.getPlayer().getUniqueId()) ) { + if (event.getItem() != null && event.getItem().getType().name().endsWith("_HELMET")) { + event.setCancelled(true); + } + } + } + + @EventHandler + public void onClickHelmet(InventoryClickEvent event) { + if (headless.containsKey(event.getWhoClicked().getUniqueId())) { + if (event.getClickedInventory() == event.getWhoClicked().getInventory() && event.getSlot() == 39) { + event.setCancelled(true); + } + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/ArmorSet.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/ArmorSet.java new file mode 100644 index 0000000..3e154fc --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/ArmorSet.java @@ -0,0 +1,323 @@ +package net.crankedpvp.crankedarmor.struct; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.armorsets.current.KothArmorSet; +import net.crankedpvp.crankedarmor.cooldowns.ArmorSetCooldownCache; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.HookUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import net.crankedpvp.crankedutils.utils.cache.CachedPlayer; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +public abstract class ArmorSet implements Listener { + + @Getter + private final DamageHandler damageHandler; + + public ArmorSet() { + this.damageHandler = CrankedUtils.instance.getDamageHandler(); + } + + public abstract String getName(); + + protected abstract ItemStack getHelmet(); + + protected abstract ItemStack getChestplate(); + + protected abstract ItemStack getLeggings(); + + protected abstract ItemStack getBoots(); + + public abstract List getArmorLore(); + + public abstract Material getDisplayMaterial(); + + public abstract String getDisplayName(); + + public void onAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) {} + + public void onAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) {} + + public void onWeaponAttack(Player attacker, Entity attacked, EntityDamageByEntityEvent event) {} + + public void onWeaponAttacked(Player attacked, Entity attacker, EntityDamageByEntityEvent event) {} + + public void onEquip(Player player) {} + + public void onUnequip(Player player) {} + + public List getArmorSet() { + return Arrays.asList(this.getHelmet(), this.getChestplate(), this.getLeggings(), this.getBoots()); + } + + public String getID() { + return this.getName().toLowerCase().replace(" ", ""); + } + + public void givePlayerArmorSet(Player player) { + getSetItemsWithData().forEach(itemStack -> player.getInventory().addItem(itemStack)); + } + + public void givePlayerHeroifiedArmorSet(Player player) { + getSetItemsWithData().forEach(itemStack -> player.getInventory().addItem(CrankedArmorAPI.heroifyArmor(itemStack, this))); + } + + public List getSetItemsWithData() { + return this.getArmorSet().stream().map(this::applyData).collect(Collectors.toList()); + } + + public ItemStack applyData(ItemStack itemStack) { + ItemBuilder itemBuilder = new ItemBuilder(itemStack).addLore(this.getArmorLore()); + NBTItem nbtItem = new NBTItem(itemBuilder.build()); + NBTCompound cosmicData = nbtItem.getOrCreateCompound("cosmicData"); + cosmicData.setString("armorSetType", this.getName()); + nbtItem.setString("armorSet", this.getID()); + return nbtItem.getItem(); + } + + + public ItemStack getDisplayItem() { + ItemBuilder itemBuilder = new ItemBuilder(getDisplayMaterial(), "&f&lArmor Set: &r" + this.getDisplayName(), this.getArmorLore()); + itemBuilder.addLore("", "&7&oClick to view this armor set category"); + return itemBuilder.colorize().build(); + } + + public String getColorAsString() { + if(this instanceof KothArmorSet) return "&f"; + return this.getDisplayName().split("&l")[0]; + } + + public List getEquipMessage() { + List message = new ArrayList<>(); + message.add(CC.translate("&3&lSets &8➥ &7You have &aequipped &7the " + getDisplayName() + " &7armorset!")); + return message; + } + + public String getNameWithColor() { + return this.getColorAsString() + StringUtils.getProperCase(this.getName()); + } + + public ItemStack buildHeroicArmorUpgrade(int chance) { + if(!(this instanceof Heroic)) { + CrankedArmor.getInstance().getServer().getLogger().info(this.getName() + " is not heroicable"); + return null; + } + + ItemBuilder itemBuilder = new ItemBuilder(Material.INK_SACK, 1, (short) 12); + itemBuilder.setName("&b&lHeroic (&3&lArmor&b&l) Upgrade"); + itemBuilder.setLore( + "&fHold the power of heroic armor,", + "&fSlaying enemies without any issue.", + "", + "&eAbilities:", + "&f • Upgrade diamond armor to heroic", + "", + "&7&oAttach this item to any armor", + "&7&oto give it a visual override!", + "", + "&7To attach, place this item on armor", + "&7Once applied, it cannot be removed!" + ); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "heroicArmorUpgrade"); + //nbtItem.setString("heroicType", this.getID()); + return nbtItem.getItem(); + } + + public ItemStack buildHeroicWeaponUpgrade(int chance) { + if(!(this instanceof Heroic)) { + CrankedArmor.getInstance().getServer().getLogger().info(this.getName() + " is not heroicable"); + return null; + } + + ItemBuilder itemBuilder = new ItemBuilder(Material.INK_SACK, 1, (short) 1); + itemBuilder.setName("&c&lHeroic (&4&lWeapon&c&l) Upgrade"); + itemBuilder.setLore( + "&fHold the power of a heroic weapon,", + "&fSlaying enemies without any issue.", + "", + "&eAbilities:", + "&f • Upgrade a weapon to a heroic one", + "", + "&7&oAttach this item to any weapon", + "&7&oto give it a visual override!", + "", + "&7To attach, place this item on a weapon", + "&7Once applied, it cannot be removed!" + ); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "heroicWeaponUpgrade"); + //nbtItem.setString("heroicType", this.getID()); + return nbtItem.getItem(); + } + + public ItemStack buildHeroicHookUpgrade(int chance) { + if(!(this instanceof Heroic)) { + CrankedArmor.getInstance().getServer().getLogger().info(this.getName() + " is not heroicable"); + return null; + } + + ItemBuilder itemBuilder = new ItemBuilder(Material.INK_SACK, 1, (short) 14); + itemBuilder.setName("&6&lHeroic (&e&lGold Hook&6&l) Upgrade"); + itemBuilder.setLore( + "&fHold the power of a heroic hook,", + "&fSlaying enemies without any issue.", + "", + "&eAbilities:", + "&f • Upgrade a hook to a heroic one", + "", + "&7&oAttach this item to any hook", + "&7&oto give it a visual override!", + "", + "&7To attach, place this item on a hook", + "&7Once applied, it cannot be removed!" + ); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "heroicHookUpgrade"); + //nbtItem.setString("heroicType", this.getID()); + return nbtItem.getItem(); + } + + public ItemStack tryBuildSword() { + if(!(this instanceof Weapon))return null; + if(!(this instanceof Sword)) return null; + Weapon weapon = (Weapon) this; + Sword sword = (Sword) this; + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_SWORD, sword.getSwordName(), weapon.getWeaponLore()); + itemBuilder.addEnchantment(Enchantment.DAMAGE_ALL, 5); + itemBuilder.addEnchantment(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + NBTCompound cosmicData = nbtItem.getOrCreateCompound("cosmicData"); + cosmicData.setString("weaponType", this.getID()); + nbtItem.setString("weaponType", this.getID()); + return nbtItem.getItem(); + } + + public ItemStack tryBuildAxe() { + if(!(this instanceof Weapon))return null; + if(!(this instanceof Axe)) return null; + Weapon weapon = (Weapon) this; + Axe axe = (Axe) this; + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_AXE, axe.getAxeName(), weapon.getWeaponLore()); + itemBuilder.addEnchantment(Enchantment.DAMAGE_ALL, 5); + itemBuilder.addEnchantment(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + NBTCompound cosmicData = nbtItem.getOrCreateCompound("cosmicData"); + cosmicData.setString("weaponType", this.getID()); + nbtItem.setString("weaponType", this.getID()); + return nbtItem.getItem(); + } + + public ItemStack tryBuildHook() { + if(!(this instanceof Weapon))return null; + Weapon weapon = (Weapon) this; + + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_HOE, "&8» " + this.getColorAsString() + "&lThe Diamond Hook &8«", weapon.getWeaponLore()); + itemBuilder.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 6); + itemBuilder.addEnchantment(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + NBTCompound cosmicData = nbtItem.getOrCreateCompound("cosmicData"); + cosmicData.setString("weaponType", this.getID()); + nbtItem.setString("weaponType", this.getID()); + return HookUtils.applyHookData(nbtItem.getItem()); + } + + public ItemStack tryBuildBow() { + if(!(this instanceof Weapon))return null; + if(!(this instanceof Bow)) return null; + Weapon weapon = (Weapon) this; + Bow bow = (Bow) this; + ItemBuilder itemBuilder = new ItemBuilder(Material.BOW, bow.getBowName(), weapon.getWeaponLore()); + itemBuilder.addEnchantment(Enchantment.ARROW_INFINITE, 1); + itemBuilder.addEnchantment(org.bukkit.enchantments.Enchantment.DURABILITY, 3); + itemBuilder.addEnchantment(Enchantment.ARROW_DAMAGE, 5); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + NBTCompound cosmicData = nbtItem.getOrCreateCompound("cosmicData"); + cosmicData.setString("weaponType", this.getID()); + nbtItem.setString("weaponType", this.getID()); + return nbtItem.getItem(); + } + + public void givePlayerArmorSetLootbox(Player player, boolean enchanted, boolean random) { + String color = getColorAsString(); + String enchantedString = "&f&ki&r"+color+"✧&f&ki&r &f&lPremade " + this.getDisplayName() + " Piece &f&l&nGenerator&r &f&ki&r"+color+"✧&f&ki&r"; + String regularString = "&f&ki&r"+color+"✧&f&ki&r " + this.getDisplayName() + " Piece &f&l&nGenerator&r &f&ki&r"+color+"✧&f&ki&r"; + String name = enchanted ? enchantedString : regularString; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, name, "&7Right-Click this armor set lootbox", + "&7to receive a random armor piece", + "&7from the " + this.getDisplayName().replace("&l", "").toLowerCase(Locale.ROOT) + " &7set collection", + ""); + itemBuilder.addLoreLine("&f&lRandom Loot (&71 Item&f&l)"); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + if(this instanceof Weapon) { + if(this instanceof Sword) itemBuilder.addLoreLine("&f&l * 1x " + ((Sword)this).getSwordName()); + if(this instanceof Axe) itemBuilder.addLoreLine("&f&l * 1x " + ((Axe)this).getAxeName()); + if(this instanceof Bow) itemBuilder.addLoreLine("&f&l * 1x " + ((Bow)this).getBowName()); + } + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetLootbox"); + nbtItem.setString("armorSetLootboxType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + public void givePlayerArmorSetBundle(Player player, boolean enchanted, boolean random) { + String color = this.getDisplayName().split("&l")[0]; + String enchantedString = "&f&ki&r"+color+"☣&f&ki&r &f&lPremade " + this.getDisplayName() + " Godset &f&ki&r"+color+"☣&f&ki&r"; + String regularString = "&f&ki&r"+color+"☣&f&ki&r " + this.getDisplayName() + " Set Bundle &f&ki&r"+color+"☣&f&ki&r"; + String name = enchanted ? enchantedString : regularString; + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_PORTAL_FRAME, name, + "&7Right-Click this bundle of treasures", + "&7to receive ALL of the following rewards", + "").setGlowing(); + itemBuilder.addLoreLine("&f&lBonus Loot (&74 Items&f&l)"); + itemBuilder.addLoreLine("&f&l * 1x " + this.getBoots().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getLeggings().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getChestplate().getItemMeta().getDisplayName()); + itemBuilder.addLoreLine("&f&l * 1x " + this.getHelmet().getItemMeta().getDisplayName()); + + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "armorSetBundle"); + nbtItem.setString("armorSetBundleType", getID()); + nbtItem.setBoolean("enchanted", enchanted); + nbtItem.setBoolean("random", random); + player.getInventory().addItem(nbtItem.getItem()); + } + + public void registerCooldown(Player player, int cooldown) { + CachedPlayer cacheManager = CacheManager.getInstance().getCachedPlayer(player); + cacheManager.registerCache(new ArmorSetCooldownCache(this, cooldown)); + + } + + public boolean isOnCooldown(Player player) { + CachedPlayer cacheManager = CacheManager.getInstance().getCachedPlayer(player); + if (!cacheManager.hasCache("armor_cooldown_" + this.getID())) return false; + return ((ArmorSetCooldownCache) cacheManager.getCache("armor_cooldown_" + this.getID())).isActive(); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/ArmorSetRegister.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/ArmorSetRegister.java new file mode 100644 index 0000000..6fd14b5 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/ArmorSetRegister.java @@ -0,0 +1,123 @@ +package net.crankedpvp.crankedarmor.struct; + +import lombok.Getter; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.armorsets.current.*; +import org.bukkit.Bukkit; + +import java.util.*; + +public class ArmorSetRegister { + + @Getter + private static ArmorSetRegister instance; + private final Map sets; + + + public ArmorSetRegister() { + instance = this; + this.sets = new HashMap<>(); + } + + public void initialize() { + + this.registerAll( + new GoblinArmorSet(), + + new PhantomArmorSet(), + new YetiArmorSet(), + new YijkiArmorSet(), + + new DragonArmorSet(), + + new KothArmorSet(), + + new AssassinArmorSet(), + new NightmareArmorSet(), + + new WraithArmorSet(), + + new DracoArmorSet(), + new ReaperArmorSet() + ); + + /* + this.registerAll( + new CosmicPhantomSet(), new CosmicDragonSet(), new CosmicYetiSet(), new CosmicYijkiSet(), new CosmicTravelerSet(), new CosmicKothSet() + ); + + */ + + /* + this.registerAll( + new KothArmorSet(), new GoblinArmorSet(), new DragonArmorSet(), new PhantomArmorSet(), new YijkiArmorSet(), new YetiArmorSet(), new AssassinArmorSet(), new NightmareArmorSet(), new WraithArmorSet(), new DracoArmorSet(), new ReaperArmorSet() + ); + + */ + //this.registerAll(new BardArmorSet()); + //this.register(new MageArmorSet()); + + + + + //cadia sets + //this.registerAll(new DiabloArmorSet(), new FortuneArmorSet(), new InfernoArmorSet(), new CadiaKothArmorSet(), new LeviathanArmorSet(), new MarksmanArmorSet(), new OrcArmorSet(), + //new PirateArmorSet(), new RavagerArmorSet(), new RoverArmorSet(), new WraithArmorSet()); + } + + public void registerAll(ArmorSet... armorSets) { + for (ArmorSet set : armorSets) { + this.register(set); + } + } + + public void register(ArmorSet set) { + try { + this.sets.put(set.getID(), set); + CrankedArmor.getInstance().getServer().getPluginManager().registerEvents(set, CrankedArmor.getInstance()); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register armor set " + set.getID()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.sets.clear(); + } + + public void unregister(ArmorSet set) { + this.sets.remove(set.getID()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isArmorSet(String name) { + return (this.getArmorSetFromID(name) != null); + } + + public ArmorSet getArmorSetFromID(String name) { + if (this.sets.get(name.toLowerCase()) == null) { + return this.sets.get("phantom"); + } + return this.sets.get(name.toLowerCase()); + } + + public ArmorSet getArmorSetFromName(String name) { + name = this.getArmorIDFromName(name); + if (this.sets.get(name.toLowerCase()) == null) { + return this.sets.get("phantom"); + } + return this.sets.get(name.toLowerCase()); + } + + public String getArmorIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getArmorSets() { + return Collections.unmodifiableCollection(this.sets.values()); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Axe.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Axe.java new file mode 100644 index 0000000..b276f8b --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Axe.java @@ -0,0 +1,5 @@ +package net.crankedpvp.crankedarmor.struct; + +public interface Axe { + String getAxeName(); +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Bow.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Bow.java new file mode 100644 index 0000000..73e374a --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Bow.java @@ -0,0 +1,5 @@ +package net.crankedpvp.crankedarmor.struct; + +public interface Bow { + String getBowName(); +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Heroic.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Heroic.java new file mode 100644 index 0000000..3bbe8f8 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Heroic.java @@ -0,0 +1,8 @@ +package net.crankedpvp.crankedarmor.struct; + + +import org.bukkit.Color; + +public interface Heroic { + Color getColor(); +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Sword.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Sword.java new file mode 100644 index 0000000..81f5c04 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Sword.java @@ -0,0 +1,5 @@ +package net.crankedpvp.crankedarmor.struct; + +public interface Sword { + String getSwordName(); +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Weapon.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Weapon.java new file mode 100644 index 0000000..13f9696 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/Weapon.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedarmor.struct; + +import org.bukkit.Material; + +import java.util.List; + +public interface Weapon { + List getWeaponLore(); +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/annotations/ConfigValue.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/annotations/ConfigValue.java new file mode 100644 index 0000000..16bba2e --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/annotations/ConfigValue.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedarmor.struct.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * don't forget to not make the field final when using this annotation + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigValue { + + String path() default "set."; + String name() default ""; + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/cache/ArmorSetCache.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/cache/ArmorSetCache.java new file mode 100644 index 0000000..0e550d4 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/cache/ArmorSetCache.java @@ -0,0 +1,108 @@ +package net.crankedpvp.crankedarmor.struct.cache; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedutils.utils.cache.Cache; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.UUID; + +@Getter +@Setter +public class ArmorSetCache extends Cache { + + private final HashMap armorSets; + private ArmorSet currentArmorSet; + private final UUID uuid; + + public ArmorSetCache(Player player) { + super("armor_set"); + this.uuid = player.getUniqueId(); + this.armorSets = new HashMap<>(); + this.currentArmorSet = null; + } + + public void refresh() { + Player player = Bukkit.getPlayer(uuid); + if(player == null) return; + + this.clear(); + if(hasFullSetEquipped(player)) { + for (ItemStack armorContent : player.getInventory().getArmorContents()) { + if (CrankedArmorAPI.hasSetTypeOnItem(armorContent)) { + this.addArmorSet(CrankedArmorAPI.getSetTypeOnItem(armorContent)); + } + } + } + } + + private boolean hasFullSetEquipped(Player player) { + return Arrays.stream(player.getInventory().getArmorContents()).filter(itemStack -> !ItemUtils.isAirOrNull(itemStack)).count() == 4; + } + + public void addArmorSet(ArmorSet type) { + Player player = Bukkit.getPlayer(uuid); + if (!this.armorSets.containsKey(type)) { + this.armorSets.put(type, 1); + + if (this.armorSets.get(type) == 4) { + this.currentArmorSet = type; + for (String s : type.getEquipMessage()) { + player.sendMessage(s); + } + type.onEquip(player); + } + } else { + this.armorSets.put(type, this.armorSets.get(type) + 1); + if (this.armorSets.containsKey(type) && this.armorSets.get(type) == 4 || (this.armorSets.containsKey(type) && this.armorSets.get(type) == 4)) { + this.currentArmorSet = type; + + for (String s : type.getEquipMessage()) { + player.sendMessage(s); + } + type.onEquip(player); + } + } + + } + + public void removeArmorSet(ArmorSet type) { + if (this.armorSets.containsKey(type)) { + Player player = Bukkit.getPlayer(uuid); + int amount = this.armorSets.get(type); + if (amount - 1 == 0) { + this.armorSets.remove(type); + } else { + this.armorSets.put(type, this.armorSets.get(type) - 1); + } + + + if (this.currentArmorSet != null) { + this.currentArmorSet.onUnequip(player); + } + + if (this.armorSets.containsKey(type) && this.armorSets.get(type) != 4) { + this.currentArmorSet = null; + + } + + } + + } + + public void clear() { + this.currentArmorSet = null; + this.armorSets.clear(); + } + + public boolean hasFullArmorSet() { + return this.currentArmorSet != null; + } +} \ No newline at end of file diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/config/ArmorConfig.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/config/ArmorConfig.java new file mode 100644 index 0000000..cf8be20 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/config/ArmorConfig.java @@ -0,0 +1,119 @@ +package net.crankedpvp.crankedarmor.struct.config; + +import lombok.AccessLevel; +import lombok.Getter; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; + +@Getter +public class ArmorConfig { + + @Getter(value = AccessLevel.PRIVATE) + private final CrankedArmor plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + private final ArmorSet armorSet; + + public ArmorConfig(CrankedArmor plugin, String path, ArmorSet armorSet) { + this.plugin = plugin; + this.path = path; + this.armorSet = armorSet; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public void setupConfigFile() { + this.createDefaultFile(); + this.config = YamlConfiguration.loadConfiguration(configFile); + + this.loadVariables(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path); + e.printStackTrace(); + } + return false; + } + + public void createDefaultFile() { + if (!configFile.exists()) { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path); + e.printStackTrace(); + } + } + } + + public void reloadConfig() { + config = YamlConfiguration.loadConfiguration(configFile); + this.loadVariables(); + } + + public void loadConfigFromDisk() { + try { + config.load(configFile); + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path); + e.printStackTrace(); + } + } + + public void loadVariables() { + boolean needSave = false; + for (Field field : this.armorSet.getClass().getDeclaredFields()) { + + try { + field.setAccessible(true); + + if (field.isAnnotationPresent(ConfigValue.class)) { + ConfigValue annotationValue = field.getAnnotation(ConfigValue.class); + + String name = annotationValue.name().equals("") ? field.getName() : annotationValue.name(); + + String path = annotationValue.path().endsWith(".") ? annotationValue.path() : annotationValue.path() + "."; + + if (!this.config.contains(path + name)) { + this.config.set(path + name, field.get(this.armorSet)); + needSave = true; + continue; + } + + Object fieldValue = this.config.get(path + name); + + if (fieldValue instanceof String) fieldValue = CC.translate((String) fieldValue); + + field.set(this.armorSet, fieldValue); + } + } catch (IllegalAccessException | NullPointerException | IllegalArgumentException e) { + Bukkit.getConsoleSender().sendMessage(CC.translate("&c[CrankedEnchants] - Error invalid config value for enchant" + armorSet.getName())); + } + } + if (needSave) { + saveConfig(); + reloadConfig(); + } + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/config/ArmorConfigManager.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/config/ArmorConfigManager.java new file mode 100644 index 0000000..ccd57de --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/struct/config/ArmorConfigManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedarmor.struct.config; + +import lombok.Getter; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class ArmorConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public ArmorConfigManager(CrankedArmor plugin) { + for (ArmorSet enchantment : plugin.getArmorSetRegister().getArmorSets()) { + ArmorConfig armorConfig = new ArmorConfig(plugin, "sets/" + enchantment.getID() + ".yml", enchantment); + configs.put(enchantment, armorConfig); + } + } + + public void setupFiles() { + configs.values().forEach(ArmorConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(ArmorConfig::reloadConfig); + } + + public ArmorConfig getAbstractConfig(ArmorSet armorSet) { + return configs.get(armorSet); + } + + public FileConfiguration getConfig(ArmorSet armorSet) { + return getAbstractConfig(armorSet).getConfig(); + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/DiabloEffectTask.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/DiabloEffectTask.java new file mode 100644 index 0000000..7d18b12 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/DiabloEffectTask.java @@ -0,0 +1,107 @@ +package net.crankedpvp.crankedarmor.tasks; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.EulerAngle; + +import java.util.*; + +public class DiabloEffectTask extends BukkitRunnable { + + private final Player player; + private final List armorStands; + private int counter; + private final DamageHandler damageHandler; + private final DiabloUpdateLocationsTask diabloUpdateLocationsTask; + + public DiabloEffectTask(Player player, DamageHandler damageHandler) { + this.player = player; + armorStands = new ArrayList<>(); + this.counter = 0; + this.damageHandler = damageHandler; + spawnAllSwords(6); + this.diabloUpdateLocationsTask = new DiabloUpdateLocationsTask(player.getUniqueId(), armorStands); + diabloUpdateLocationsTask.runTaskTimer(CrankedArmor.getInstance(), 0L, 1); + } + + @Override + public void run() { + if (player.isDead() || !WorldGuardUtils.canPvPInRegion(player)) { + clearSwords(); + diabloUpdateLocationsTask.cancel(); + this.cancel(); + return; + } + if (counter == 5) { + clearSwords(); + diabloUpdateLocationsTask.cancel(); + this.cancel(); + return; + } + update(); + counter++; + } + + public void update() { + if (armorStands.isEmpty()) clearSwords(); + ArmorStand armorStand = armorStands.get(0); + if (!armorStand.isDead()) { + damageHandler.damage(player, 10, "&4&lDiablo Devour"); + player.sendMessage(CC.translate("&4&l* DIABLO DEVOUR &7[-10HP] &4&l*")); + armorStand.remove(); + armorStands.remove(0); + } + } + + public void clearSwords() { + for (ArmorStand sword : armorStands) { + sword.remove(); + } + armorStands.clear(); + } + + public void spawnAllSwords(int amount) { + Location playerLocation = player.getLocation(); + double x = playerLocation.getX(); + double y = playerLocation.getY() + 1; + double z = playerLocation.getZ(); + double angle = (2 * Math.PI) / 5; + for (int i = 0; i < amount; i++) { + double x1 = x + (1 * Math.cos(angle * i)); + double z1 = z + (1 * Math.sin(angle * i)); + Location location = new Location(playerLocation.getWorld(), x1, y + 1.5, z1); + spawnArmorStand(location); + } + + } + + + + public ArmorStand spawnArmorStand(Location location) { + ArmorStand armorStand = (ArmorStand) location.getWorld().spawnEntity(location, EntityType.ARMOR_STAND); + armorStand.setVisible(false); + armorStand.setGravity(false); + armorStand.setCanPickupItems(false); + armorStand.setSmall(true); + armorStand.setItemInHand(new ItemStack(Material.STONE_SWORD)); + armorStand.setRightArmPose(new EulerAngle(Math.toRadians(90), Math.toRadians(180), 0)); + armorStands.add(armorStand); + return armorStand; + } + + + + +} + + diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/DiabloUpdateLocationsTask.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/DiabloUpdateLocationsTask.java new file mode 100644 index 0000000..196632c --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/DiabloUpdateLocationsTask.java @@ -0,0 +1,48 @@ +package net.crankedpvp.crankedarmor.tasks; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.List; +import java.util.UUID; + +@AllArgsConstructor + +public class DiabloUpdateLocationsTask extends BukkitRunnable { + + private final UUID uuid; + @Getter + private final List armorStands; + + + @Override + public void run() { + if (armorStands.isEmpty()) { + this.cancel(); + } + updateLocations(); + } + + public void updateLocations() { + Player player = Bukkit.getPlayer(uuid); + Location playerLocation = player.getLocation(); + double x = playerLocation.getX(); + double y = playerLocation.getY() + 1; + double z = playerLocation.getZ(); + double angle = (2 * Math.PI) / 5; + List armorStands = getArmorStands(); + for (int i = 0; i < armorStands.size(); i++) { + ArmorStand armorStand = armorStands.get(i); + double x1 = x + (1 * Math.cos(angle * i)); + double z1 = z + (1 * Math.sin(angle * i)); + Location location = new Location(playerLocation.getWorld(), x1, y + 1.5, z1); + armorStand.teleport(location); + } + } + +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/InfernoBleedTask.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/InfernoBleedTask.java new file mode 100644 index 0000000..506829a --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/InfernoBleedTask.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedarmor.tasks; + +import net.crankedpvp.crankedutils.CrankedUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class InfernoBleedTask extends BukkitRunnable { + public static List bleedPlayers = new ArrayList<>(); + @Override + public void run() { + for (UUID uuid : bleedPlayers) { + Player player = Bukkit.getPlayer(uuid); + if (player == null || !player.isOnline()) { + bleedPlayers.remove(uuid); + continue; + } + CrankedUtils.getInstance().getDamageHandler().damage(player, 2, "&6&lInfernoBleed"); + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/PirateFireEffectTask.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/PirateFireEffectTask.java new file mode 100644 index 0000000..810f06a --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/PirateFireEffectTask.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedarmor.tasks; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; +import xyz.xenondevs.particle.utils.ParticleUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class PirateFireEffectTask extends BukkitRunnable { + public static List firePlayers = new ArrayList<>(); + @Override + public void run() { + for (UUID uuid : firePlayers) { + Player player = Bukkit.getPlayer(uuid); + if (player == null || !player.isOnline()) { + firePlayers.remove(uuid); + continue; + } + new ParticleBuilder(ParticleEffect.FLAME, player.getLocation()).setAmount(100).setSpeed(0.15F).display(); + } + } +} diff --git a/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/RoverLanternTask.java b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/RoverLanternTask.java new file mode 100644 index 0000000..e5e0d29 --- /dev/null +++ b/Armor/src/main/java/net/crankedpvp/crankedarmor/tasks/RoverLanternTask.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedarmor.tasks; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class RoverLanternTask extends BukkitRunnable { + public static Map lanterned = new HashMap<>(); + @Override + public void run() { + for (Map.Entry entry : lanterned.entrySet()) { + UUID uuid = entry.getKey(); + ArmorStand armorStand = entry.getValue(); + Player player = Bukkit.getPlayer(uuid); + if (player == null || !player.isOnline()) { + stop(uuid); + continue; + } + Location location = player.getLocation(); + armorStand.teleport(new Location(location.getWorld(), location.getX(), location.getY()+2.25, location.getZ())); + } + } + + public static void stop(UUID uuid) { + if (lanterned.containsKey(uuid)) { + lanterned.get(uuid).remove(); + lanterned.remove(uuid); + } + } +} diff --git a/Armor/src/main/resources/language.yml b/Armor/src/main/resources/language.yml new file mode 100644 index 0000000..872cced --- /dev/null +++ b/Armor/src/main/resources/language.yml @@ -0,0 +1,32 @@ +INVALID_ARMOR_SET: '&c&l(!)&c Invalid armor set name.' +ADMIN_COMMAND_HELP: + - '&8--- &3Cranked &fArmor Sets &8---' + - '&3/ca &fset &7 [player]' + - '&3/ca &feset &7 [player]' + - '&3/ca &fhook &7 [player]' + - '&3/ca &fehook &7 [player]' + - '&3/ca &fweapon &7 [player]' + - '&3/ca &feweapon &7 [player]' + - '&3/ca &flootbox &7 [player]' + - '&3/ca &felootbox &7 [player]' + - '&3/ca &fbundle &7 [player]' + - '&3/ca &febundle &7 [player]' + - '&3/ca &fsets' +ADMIN_RELOADING: '&3&l(!) &7Reloading configs now...' +ADMIN_RELOADED: '&3&l(!) &7Reloaded configs and other cool stuff. Took &3%took%ms&7.' +ADMIN_COMMAND_HEROIC_HELP: + - '&8--- &3Cranked &fArmor Sets &8---' + - '&3/hca &farmorupgrade &7[player]' + - '&3/hca &fweaponupgrade [player]' + - '&3/hca &fhookupgrade &7[player]' + - '&3/hca &fhook &7 [player]' + - '&3/hca &fehook &7 [player]' + - '&3/hca &fweapon &7 [player]' + - '&3/hca &feweapon &7 [player]' + - '&3/hca &fset &7 [player]' + - '&3/hca &feset &7 [player]' +PER_PIECE_HEROIC_REDUCTION: 5 +HEROIC_WEAPON_DAMAGE_INCREASE: 10 +WEIGHTED_PVP_GO_BELOW_0: false +WEIGHTED_PVP_DAMAGE_MULTIPLIER: 7.5 +NO_SET_DAMAGE_REDUCTION: 50 diff --git a/Armor/src/main/resources/plugin.yml b/Armor/src/main/resources/plugin.yml new file mode 100644 index 0000000..45f7bb3 --- /dev/null +++ b/Armor/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedArmor +main: net.crankedpvp.crankedarmor.CrankedArmor +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedEnchants \ No newline at end of file diff --git a/AsyncHitDetection/pom.xml b/AsyncHitDetection/pom.xml new file mode 100644 index 0000000..2e19346 --- /dev/null +++ b/AsyncHitDetection/pom.xml @@ -0,0 +1,92 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + AsyncHitDetection + + + 8 + 8 + + + + + jitpack.io + https://jitpack.io + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + funkemunky-releases + https://nexus.funkemunky.cc/content/repositories/releases/ + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + + shade + + + false + false + + + io.github.retrooper:packetevents + + plugin.yml + + + + + + io.github.retrooper.packetevents + net.crankedpvp.hitdetection.libs.packetevents + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + + src/main/resources + true + + + + + + + io.github.retrooper + packetevents + v1.8.4 + + + + diff --git a/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/PacketProcessor.java b/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/PacketProcessor.java new file mode 100644 index 0000000..5ee037c --- /dev/null +++ b/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/PacketProcessor.java @@ -0,0 +1,80 @@ +package net.crankedpvp.hitdetection; + + +import io.github.retrooper.packetevents.event.impl.PacketPlayReceiveEvent; +import io.github.retrooper.packetevents.packettype.PacketType; +import io.github.retrooper.packetevents.packetwrappers.play.in.useentity.WrappedPacketInUseEntity; +import io.github.retrooper.packetevents.packetwrappers.play.out.entitystatus.WrappedPacketOutEntityStatus; +import net.crankedpvp.hitdetection.util.KnockbackUtil; +import net.crankedpvp.hitdetection.util.KnockbackUtil_8; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class PacketProcessor { + public static final String handlerName = "transactions"; + + public static PacketProcessor INSTANCE; + private final Map delay = new HashMap<>(); + public final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); + private KnockbackUtil knockbackUtil; + + public PacketProcessor() { + INSTANCE = this; + } + + public void load() { + knockbackUtil = new KnockbackUtil_8(); + } + + public void onPacketPlayReceive(PacketPlayReceiveEvent event) { + if (event.getPacketId() == PacketType.Play.Client.USE_ENTITY) { + Player player = event.getPlayer(); + WrappedPacketInUseEntity useEntity = new WrappedPacketInUseEntity(event.getNMSPacket()); + Entity entity = useEntity.getEntity(); + WrappedPacketInUseEntity.EntityUseAction action = useEntity.getAction(); + if (action == WrappedPacketInUseEntity.EntityUseAction.ATTACK + && entity.getType() == EntityType.PLAYER) { + if (delay.containsKey(player.getName())) { + long s = ((System.currentTimeMillis() - delay.get(player.getName())) / 1000) * 20; + if (s < 5) { + event.setCancelled(true); + return; + } + } + + WrappedPacketOutEntityStatus status = new WrappedPacketOutEntityStatus(entity, (byte) 2); + delay.put(player.getName(), System.currentTimeMillis()); + applyKnockback(player, (Player) entity, status); + event.setCancelled(true); + } + } + + } + + public void damageEntity(Player player, Entity target) { + knockbackUtil.damageEntity(player, target); + } + + + public void applyKnockback(Player player, Player damaged, WrappedPacketOutEntityStatus status) { + executorService.execute(() -> knockbackUtil.applyKnockback(player, damaged, status)); + } + + public void g(Player player, double d0, double d1, double d2) { + knockbackUtil.g(player, d0, d1, d2); + } + + public void injectPlayer(Player player) { + knockbackUtil.injectPlayer(player); + } + + public void ejectPlayer(Player player) { + knockbackUtil.ejectPlayer(player); + } +} \ No newline at end of file diff --git a/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/Transactions.java b/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/Transactions.java new file mode 100644 index 0000000..f73c3e3 --- /dev/null +++ b/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/Transactions.java @@ -0,0 +1,60 @@ +package net.crankedpvp.hitdetection; + +import io.github.retrooper.packetevents.PacketEvents; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; + +public class Transactions extends JavaPlugin { + public static Transactions INSTANCE; + private final PacketProcessor processor = new PacketProcessor();; + + @Override + public void onLoad() { + INSTANCE = this; + /* + * PacketEvents likes to maintain compatibility with other plugins shading the same API. + * If some other API loaded before you, the create method will return it's PacketEvents instance + * to maintain compatibility, otherwise you will create the instance. + * Set the settings. + */ + PacketEvents.create(this).getSettings().checkForUpdates(false); + /* + * Access the stored instance of the PacketEvents class and load PacketEvents. + * A few settings need to be specified before loading PacketEvents + * as PacketEvents already uses a few in the load method. + * To be safe, just set them all before loading. + */ + PacketEvents.get().load(); + } + + @Override + public void onEnable() { + + //Initiate PacketEvents + PacketEvents.get().init(this); + processor.load(); + + } + + @Override + public void onDisable() { + //Terminate PacketEvents + processor.executorService.shutdown(); + PacketEvents.get().terminate(); + + } + + @EventHandler + public void onJoin(PlayerJoinEvent event) { + processor.injectPlayer(event.getPlayer()); + } + + @EventHandler + public void onQuit(PlayerQuitEvent event) { + processor.ejectPlayer(event.getPlayer()); + } + + +} \ No newline at end of file diff --git a/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/util/KnockbackUtil.java b/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/util/KnockbackUtil.java new file mode 100644 index 0000000..4508d44 --- /dev/null +++ b/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/util/KnockbackUtil.java @@ -0,0 +1,18 @@ +package net.crankedpvp.hitdetection.util; + +import io.github.retrooper.packetevents.packetwrappers.play.out.entitystatus.WrappedPacketOutEntityStatus; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +public interface KnockbackUtil { + + void damageEntity(Player player, Entity target); + + void applyKnockback(Player player, Player target, WrappedPacketOutEntityStatus status); + + void g(Player player, double deltaMotX, double deltaMotY, double deltaMotZ); + + void injectPlayer(Player player); + + void ejectPlayer(Player player); +} \ No newline at end of file diff --git a/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/util/KnockbackUtil_8.java b/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/util/KnockbackUtil_8.java new file mode 100644 index 0000000..30c06d4 --- /dev/null +++ b/AsyncHitDetection/src/main/java/net/crankedpvp/hitdetection/util/KnockbackUtil_8.java @@ -0,0 +1,143 @@ +package net.crankedpvp.hitdetection.util; + +import io.github.retrooper.packetevents.PacketEvents; +import io.github.retrooper.packetevents.event.impl.PacketPlayReceiveEvent; +import io.github.retrooper.packetevents.packetwrappers.NMSPacket; +import io.github.retrooper.packetevents.packetwrappers.play.out.entitystatus.WrappedPacketOutEntityStatus; +import io.github.retrooper.packetevents.utils.nms.NMSUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToMessageDecoder; +import net.crankedpvp.hitdetection.PacketProcessor; +import net.minecraft.server.v1_8_R3.*; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_8_R3.entity.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityCombustByEntityEvent; +import org.bukkit.event.player.PlayerVelocityEvent; + +import java.util.List; + +public class KnockbackUtil_8 implements KnockbackUtil { + @Override + public void damageEntity(Player player, Entity target) { + EntityPlayer ep = ((CraftPlayer)player).getHandle(); + net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity)target).getHandle(); + boolean disablePlayerCrits = false; + float f = (float) ep.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue(); + byte b0 = 0; + float f1; + + if (nmsEntity instanceof EntityLiving) { + f1 = EnchantmentManager.a(ep.bA(), ((EntityLiving) nmsEntity).getMonsterType()); + } else { + f1 = EnchantmentManager.a(ep.bA(), EnumMonsterType.UNDEFINED); + } + + int i = b0 + EnchantmentManager.a(ep); + + if (ep.isSprinting()) { + ++i; + } + + if (f > 0.0F || f1 > 0.0F) { + boolean flag = !disablePlayerCrits && ep.fallDistance > 0.0F && !ep.onGround && !ep.k_() && !ep.V() && !ep.hasEffect(MobEffectList.BLINDNESS) && ep.vehicle == null && nmsEntity instanceof EntityLiving; // PaperSpigot + + if (flag && f > 0.0F) { + f *= 1.5F; + } + + f += f1; + int j = EnchantmentManager.getFireAspectEnchantmentLevel(ep); + + if (nmsEntity instanceof EntityLiving && j > 0 && !nmsEntity.isBurning()) { + // CraftBukkit start - Call a combust event when somebody hits with a fire enchanted item + EntityCombustByEntityEvent combustEvent = new EntityCombustByEntityEvent(ep.getBukkitEntity(), nmsEntity.getBukkitEntity(), 1); + org.bukkit.Bukkit.getPluginManager().callEvent(combustEvent); + + if (!combustEvent.isCancelled()) { + nmsEntity.setOnFire(combustEvent.getDuration()); + } + // CraftBukkit end + } + + nmsEntity.damageEntity(DamageSource.playerAttack(ep), f); + } + } + + @Override + public void applyKnockback(Player player, Player target, WrappedPacketOutEntityStatus status) { + for (Player p : Bukkit.getServer().getOnlinePlayers()) { + CraftPlayer cp = (CraftPlayer) p; + + EntityPlayer ep = ((CraftPlayer) target).getHandle(); + EntityPlayer epa = ((CraftPlayer) player).getHandle(); + + damageEntity(player, target); + + double victimMotX = ep.motX; + double victimMotY = ep.motY; + double victimMotZ = ep.motZ; + + ep.velocityChanged = true; + + g(player, -MathHelper.sin(epa.yaw * 3.1415927F / 180.0F) * 1 * 0.5F * 0.95D * 1, 0.1D * 0.7, + MathHelper.cos(epa.yaw * 3.1415927F / 180.0F) * 1 * 0.5F * 0.95D * 1); + PlayerVelocityEvent event = new PlayerVelocityEvent(ep.getBukkitEntity(), ep.getBukkitEntity().getVelocity()); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + ep.getBukkitEntity().setVelocity(event.getVelocity()); + } + + ep.velocityChanged = false; + ep.motX = victimMotX; + ep.motY = victimMotY; + ep.motZ = victimMotZ; + + PacketEvents.get().getPlayerUtils().sendPacket(p, + status); + + } + } + + @Override + public void g(Player player, double deltaMotX, double deltaMotY, double deltaMotZ) { + EntityPlayer ep = ((CraftPlayer)player).getHandle(); + ep.motX += deltaMotX; + ep.motY += deltaMotY; + ep.motZ += deltaMotZ; + ep.ai = true; + } + + @Override + public void injectPlayer(Player player) { + Channel channel = (Channel) NMSUtils.getChannel(player); + channel.pipeline().addAfter("decoder", PacketProcessor.handlerName, new MessageToMessageDecoder() { + public boolean processIncomingPacket(Channel channel, Object packet) { + PacketPlayReceiveEvent event = new PacketPlayReceiveEvent(player, channel, new NMSPacket(packet)); + PacketProcessor.INSTANCE.onPacketPlayReceive(event); + return event.isCancelled(); + } + + @Override + protected void decode(ChannelHandlerContext ctx, Object packet, List list) throws Exception { + list.add(packet); + + if (!processIncomingPacket(ctx.channel(), packet)) { + list.remove(packet); + ctx.flush(); + } + + } + }); + } + + @Override + public void ejectPlayer(Player player) { + Channel channel = (Channel) NMSUtils.getChannel(player); + if (channel.pipeline().get(PacketProcessor.handlerName) != null) { + channel.pipeline().remove(PacketProcessor.handlerName); + } + } +} \ No newline at end of file diff --git a/AsyncHitDetection/src/main/resources/plugin.yml b/AsyncHitDetection/src/main/resources/plugin.yml new file mode 100644 index 0000000..ccc5f10 --- /dev/null +++ b/AsyncHitDetection/src/main/resources/plugin.yml @@ -0,0 +1,6 @@ +name: HitDetectionPlugin +author: "frash23" +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +main: net.crankedpvp.hitdetection.Transactions diff --git a/Auctionhouse/pom.xml b/Auctionhouse/pom.xml new file mode 100644 index 0000000..2d8cfb6 --- /dev/null +++ b/Auctionhouse/pom.xml @@ -0,0 +1,77 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Auctionhouse + + + 8 + 8 + + + + + mysql + mysql-connector-java + 5.1.49 + + + net.crankedpvp + Utils + + + Core + net.crankedpvp + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + net.crankedpvp + Enchants + 1.0 + + + net.crankedpvp + Trade + 1.0 + compile + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + shade + + + + mysql:mysql-connector-java + + + false + + + + + + + + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/Auction.java b/Auctionhouse/src/main/java/me/recolance/auction/Auction.java new file mode 100644 index 0000000..4a11244 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/Auction.java @@ -0,0 +1,160 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * net.milkbowl.vault.economy.Economy + * org.bukkit.Bukkit + * org.bukkit.command.CommandExecutor + * org.bukkit.entity.Player + * org.bukkit.event.Listener + * org.bukkit.plugin.Plugin + * org.bukkit.plugin.RegisteredServiceProvider + * org.bukkit.plugin.java.JavaPlugin + * org.bukkit.scheduler.BukkitTask + */ +package me.recolance.auction; + +import lombok.SneakyThrows; +import me.recolance.auction.command.CommandHandler; +import me.recolance.auction.controller.ConfirmMenu; +import me.recolance.auction.controller.Controller; +import me.recolance.auction.controller.Events; +import me.recolance.auction.data.DataHandler; +import me.recolance.auction.data.Database; +import me.recolance.auction.data.SafetyToggle; +import me.recolance.auction.menu.BidListener; +import me.recolance.auction.menu.BidManager; +import me.recolance.auction.menu.MenuController; +import me.recolance.auction.tasks.ItemExpireWarnTask; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandExecutor; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; + +import java.io.IOException; + +public class Auction + extends JavaPlugin { + public static Auction plugin; + public static Economy economy; + public static boolean stoppingServer; + + static { + economy = null; + stoppingServer = false; + } + + private SafetyToggle toggles; + private BidManager bidManager; + + public static Auction getPlugin() { + return plugin; + } + + @SneakyThrows + public void onEnable() { + plugin = this; + stoppingServer = false; + this.setupEconomy(); + this.saveDefaultConfig(); + this.toggles = new SafetyToggle(); + if (!Database.openDatabaseConnection()) { + this.getServer().getPluginManager().disablePlugin(this); + return; + } + DataHandler.loadListings(); + this.registration(); + Controller.expireListings(); + Controller.expireOfflineUnclaimedListings(); + this.bidManager = new BidManager(); + try { + this.bidManager.loadBids(this); + } catch (IOException e) { + e.printStackTrace(); + } + this.bidManager.startBidTimer(); + } + + public void onDisable() { + stoppingServer = true; + if (this.bidManager != null) this.bidManager.setProccessAuctionHouse(false); + for (Player p : Bukkit.getOnlinePlayers()) { + String invName = p.getInventory().getTitle(); + if (!invName.equals("Cancelled / Expired Listings") && !invName.equals("Auction House") && !invName.equals("Your Current Listings")) + continue; + p.closeInventory(); + } + int attempts = 0; + while (this.getPendingAsyncTasks() > 0 && attempts++ <= 20) { + Bukkit.getLogger().info("(Auction) There are still " + this.getPendingAsyncTasks() + " pending SQL tasks, sleeping 500ms..."); + try { + Thread.sleep(500L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + if (this.toggles != null) this.toggles.saveFile(); + if (this.bidManager != null) { + try { + this.bidManager.saveBids(false); + } catch (Exception e) { + e.printStackTrace(); + } + } + plugin = null; + Database.closeConnection(); + } + + private int getPendingAsyncTasks() { + int c = 0; + for (BukkitTask bt : Bukkit.getScheduler().getPendingTasks()) { + if (bt.isSync() || !bt.getOwner().equals((Object) plugin)) continue; + ++c; + } + return c; + } + + public void registration() { + this.saveDefaultConfig(); + this.updateConfig(); + this.getServer().getPluginManager().registerEvents((Listener) new BidListener(), (Plugin) this); + this.getServer().getPluginManager().registerEvents((Listener) new MenuController(), (Plugin) this); + this.getServer().getPluginManager().registerEvents((Listener) new Events(), (Plugin) this); + this.getServer().getPluginManager().registerEvents((Listener) new ConfirmMenu(), (Plugin) this); + this.getCommand("ah").setExecutor((CommandExecutor) new CommandHandler()); + new ItemExpireWarnTask().runTaskTimer((Plugin) this, 4800L, 4800L); + } + + private void updateConfig() { + if (!this.getConfig().contains("auction.preventCreativeSale")) { + this.getConfig().set("auction.preventCreativeSale", (Object) false); + } + this.saveConfig(); + } + + private boolean setupEconomy() { + RegisteredServiceProvider economyProvider = this.getServer().getServicesManager().getRegistration(Economy.class); + if (economyProvider != null) { + economy = (Economy) economyProvider.getProvider(); + } + return economy != null; + } + + public boolean hasToggle(Player pl) { + return this.toggles.isToggled(pl); + } + + public SafetyToggle getToggles() { + return this.toggles; + } + + public BidManager getBidManager() { + return this.bidManager; + } + +} diff --git a/Auctionhouse/src/main/java/me/recolance/auction/auction/Listing.java b/Auctionhouse/src/main/java/me/recolance/auction/auction/Listing.java new file mode 100644 index 0000000..92f7cd1 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/auction/Listing.java @@ -0,0 +1,202 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.CosmicSpaceChests.CosmicSpaceChestsAPI + * com.cosmicpvp.CosmicSpaceChests.libs.ItemRarity + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.NumberUtils + * com.rit.sucy.CustomEnchantment + * org.arkhamnetwork.Arkkit.patches.ExpBottles + * org.arkhamnetwork.enchantments.EnchantmentBook + * org.arkhamnetwork.enchantments.util.TieredEnchantments + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + */ +package me.recolance.auction.auction; + + +import me.recolance.auction.data.AuctionItem; +import me.recolance.auction.util.Item; + +import net.crankedpvp.crankedcore.utils.ExpBottleAPI; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.items.BookBuilder; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; +import java.util.UUID; + +public class Listing + implements Comparable, + AuctionItem { + private UUID id; + private long endTime; + private UUID listedBy; + private String listedByName; + private ItemStack item; + private double price; + private DecimalFormat formatter = new DecimalFormat("#,###"); + private boolean valid = true; + private boolean checkedBook; + private Integer bookRarity; + private ChatColor bookTierColor; + private String bookTierName; + private Integer expInBottle; + private Double expPerDollar; + private double pricePerItem = 0.0; + + public Listing(UUID id, long endTime, UUID listedBy, ItemStack item, double price) { + this.id = id; + this.endTime = endTime; + this.listedBy = listedBy; + this.item = item; + this.price = price; + this.listedByName = Bukkit.getOfflinePlayer((UUID) this.listedBy).getName(); + } + + public double getPricePerItem() { + if (this.pricePerItem > 0.0) { + return this.pricePerItem; + } + if (this.item.getAmount() > 1) { + this.pricePerItem = (double) this.getPrice() / (double) this.item.getAmount(); + return this.pricePerItem; + } + this.pricePerItem = this.getPrice(); + return this.pricePerItem; + } + + public int getExpInBottle() { + if (this.expInBottle == null) { + this.expInBottle = ExpBottleAPI.isXpBottle((ItemStack) this.item) ? Integer.valueOf(ExpBottleAPI.getXpAmount((ItemStack) this.item)) : Integer.valueOf(0); + } + return this.expInBottle; + } + + public double getExpPerDollar() { + if (this.expPerDollar == null) { + int exp = this.getExpInBottle(); + this.expPerDollar = exp > 0 ? Double.valueOf((double) this.price / (double) exp) : Double.valueOf(0.0); + } + return this.expPerDollar; + } + + public Integer getBookRarity() { + if (!this.checkedBook) { + this.checkedBook = true; + if (!CrankedEnchantsAPI.isEnchantBook((ItemStack) this.item)) { + return null; + } + Enchantment enchant = new BookBuilder(this.item).getBookEnchantment(); + if (enchant == null) { + return null; + } + this.bookTierColor = ChatColor.valueOf(enchant.getTier().getColor()); + this.bookRarity = enchant.getEnchantTierWeight(); + + this.bookTierName = enchant.getTier().getFormatedName(); + } + + return this.bookRarity; + } + + public ItemStack getMenuDisplayItem() { + String perData = this.getExpInBottle() > 0 ? CC.Gray + " ($" + NumberUtils.formatMoney((double) this.getExpPerDollar()) + " / xp)" : ""; + double perItem = this.getPricePerItem(); + if (perItem != (double) this.getPrice() && perItem > 0.0) { + perData = " ($" + NumberUtils.formatMoney((double) perItem) + " / item)"; + } + return new Item(new ItemStack(this.getItem())).addLore("", "&7-------------------------", "&e&lClick item to buy!", "", "&6Price: &e$" + this.getPrettyPrice() + perData, "&6Seller: &e" + this.getNameOfWhoListed(), "&7-------------------------").get(); + } + + public boolean isExpired() { + return this.endTime <= System.currentTimeMillis(); + } + + public boolean isValid() { + return this.valid; + } + + public void setValid(boolean valid) { + this.valid = valid; + } + + public UUID getId() { + return this.id; + } + + public void setId(UUID id) { + this.id = id; + } + + public long getEndTime() { + return this.endTime; + } + + public void setEndTime(long endTime) { + this.endTime = endTime; + } + + public UUID getWhoListed() { + return this.listedBy; + } + + public void setWhoListed(UUID listedBy) { + this.listedBy = listedBy; + } + + public String getNameOfWhoListed() { + return this.listedByName; + } + + public void setWhoNameOfWhoListed(String name) { + this.listedByName = name; + } + + public ItemStack getItem() { + return this.item; + } + + public void setItem(ItemStack item) { + this.item = item; + } + + public double getPrice() { + return this.price; + } + + public void setPrice(int price) { + this.price = price; + } + + public String getPrettyPrice() { + return this.formatter.format(this.price); + } + + @Override + public int compareTo(Listing o) { + return Long.compare(o.getEndTime(), this.getEndTime()); + } + + @Override + public ItemStack getDisplay() { + return this.getMenuDisplayItem(); + } + + public ChatColor getBookTierColor() { + return this.bookTierColor; + } + + public String getBookTierName() { + return this.bookTierName; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/auction/UnclaimedListing.java b/Auctionhouse/src/main/java/me/recolance/auction/auction/UnclaimedListing.java new file mode 100644 index 0000000..83f4eff --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/auction/UnclaimedListing.java @@ -0,0 +1,62 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + */ +package me.recolance.auction.auction; + +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +public class UnclaimedListing { + private UUID id; + private UUID listedBy; + private ItemStack item; + private long expireTime; + + public UnclaimedListing(UUID id, UUID listedBy, ItemStack item, long expireTime) { + this.id = id; + this.listedBy = listedBy; + this.item = item; + this.expireTime = expireTime; + } + + public boolean isExpired() { + return this.expireTime <= System.currentTimeMillis(); + } + + public UUID getId() { + return this.id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getListedBy() { + return this.listedBy; + } + + public void setListedBy(UUID listedBy) { + this.listedBy = listedBy; + } + + public ItemStack getItem() { + return this.item; + } + + public void setItem(ItemStack item) { + this.item = item; + } + + public long getExpireTime() { + return this.expireTime; + } + + public void setExpireTime(long expireTime) { + this.expireTime = expireTime; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/command/Command.java b/Auctionhouse/src/main/java/me/recolance/auction/command/Command.java new file mode 100644 index 0000000..dc3e7b1 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/command/Command.java @@ -0,0 +1,23 @@ +/* + * Decompiled with CFR 0.150. + */ +package me.recolance.auction.command; + +public enum Command { + AUCTION("&6Auction Menu", "&e/auction", "&7Opens the auction house.", "", "&9Aliases:", "&e- /ah", "&e- /auc", "&e- /auctionhouse"), + SELL("&6Sell An Item", "&e/ah sell ", "&7List the item you are holding on the auction house.", "", ""), + EXPIRED("&6Open Your Expired Items", "&e/ah expired", "&7View and manage your cancelled and expired items.", "", "&9Aliases:", "&e- /ah ex"), + SELLING("&6Open Your Listed Items", "&e/ah listed", "&7View and manage the items you are selling.", "", "&9Aliases:", "&e- /ah selling"), + HELP("&6Auction Help", "&e/ah help", "&7View this help menu.", "", "&9Aliases:", "&e- /ah commands"); + + private String[] desc; + + private Command(String... desc) { + this.desc = desc; + } + + public String[] getDescription() { + return this.desc; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/command/CommandHandler.java b/Auctionhouse/src/main/java/me/recolance/auction/command/CommandHandler.java new file mode 100644 index 0000000..3fbeb06 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/command/CommandHandler.java @@ -0,0 +1,475 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.nbt.NBTTagCompoundBuilder + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.NBTWrapper + * com.google.common.collect.Lists + * me.vaqxine.NetworkManager.NetworkManager + * net.milkbowl.vault.economy.Economy + * org.arkhamnetwork.Arkkit.Arkkit + * org.arkhamnetwork.Arkkit.net.astropvp.armorsets.commands.CommandArkReboot + * org.arkhamnetwork.Arkkit.patches.AntiCrash + * org.arkhamnetwork.Arkkit.patches.ItemID + * org.arkhamnetwork.Arkkit.plugins.ArkPlugins + * org.arkhamnetwork.Arkkit.net.astropvp.armorsets.utils.TimeUtils + * org.arkhamnetwork.CosmicMoneyNotes.ArkhamMoneyNotesAPI + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.GameMode + * org.bukkit.Material + * org.bukkit.command.Command + * org.bukkit.command.CommandExecutor + * org.bukkit.command.CommandSender + * org.bukkit.enchantments.Enchantment + * org.bukkit.entity.Player + * org.bukkit.inventory.ItemStack + */ +package me.recolance.auction.command; + + +import com.google.common.collect.Lists; +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import me.recolance.auction.Auction; +import me.recolance.auction.controller.Controller; +import me.recolance.auction.controller.Events; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.data.SafetyToggle; +import me.recolance.auction.menu.BidManager; +import me.recolance.auction.menu.MenuRenderer; +import me.recolance.auction.menu.bidmenus.AuctionPackageMenu; +import me.recolance.auction.menu.bidmenus.BidCollectionBinMenu; +import me.recolance.auction.menu.bidmenus.BidMenu; +import me.recolance.auction.util.AuctionUtil; +import me.recolance.auction.util.Util; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.utils.MoneyNotesAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.milkbowl.vault.economy.Economy; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +public class CommandHandler + implements CommandExecutor { + private static Economy economy = Auction.economy; + private static HashSet noCustomNamedMaterials; + private static HashSet invisibilityEffectIds; + + public CommandHandler() { + noCustomNamedMaterials = new HashSet(); + noCustomNamedMaterials.add(Material.CHEST); + noCustomNamedMaterials.add(Material.TRAPPED_CHEST); + noCustomNamedMaterials.add(Material.MONSTER_EGG); + noCustomNamedMaterials.add(Material.PAPER); + noCustomNamedMaterials.add(Material.MOB_SPAWNER); + noCustomNamedMaterials.add(Material.EXP_BOTTLE); + noCustomNamedMaterials.add(Material.BOOK); + noCustomNamedMaterials.add(Material.REDSTONE_TORCH_ON); + noCustomNamedMaterials.add(Material.REDSTONE_TORCH_OFF); + noCustomNamedMaterials.add(Material.EYE_OF_ENDER); + noCustomNamedMaterials.add(Material.EMERALD); + noCustomNamedMaterials.add(Material.EMPTY_MAP); + noCustomNamedMaterials.add(Material.PAPER); + noCustomNamedMaterials.add(Material.INK_SACK); + noCustomNamedMaterials.add(Material.ENCHANTED_BOOK); + noCustomNamedMaterials.add(Material.GLOWSTONE_DUST); + noCustomNamedMaterials.add(Material.SUGAR); + noCustomNamedMaterials.add(Material.SULPHUR); + noCustomNamedMaterials.add(Material.MAGMA_CREAM); + noCustomNamedMaterials.add(Material.BONE); + noCustomNamedMaterials.add(Material.getMaterial((int) 99)); + noCustomNamedMaterials.add(Material.getMaterial((int) 100)); + invisibilityEffectIds = new HashSet(); + invisibilityEffectIds.add((short) 8206); + invisibilityEffectIds.add((short) 8238); + invisibilityEffectIds.add((short) 16398); + invisibilityEffectIds.add((short) 16430); + } + + public static boolean canSellItem(ItemStack item) { + double dura; + if (item.getAmount() <= 0) { + return false; + } + Material type = item.getType(); + if (type == Material.STAINED_GLASS_PANE) { + return false; + } + + if (MoneyNotesAPI.isMoneyNote(item)) { + return false; + } + if (type == Material.POTION && invisibilityEffectIds.contains(item.getDurability())) { + return false; + } + if (noCustomNamedMaterials.contains((Object) type) && item.hasItemMeta() && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName() != null && !item.getItemMeta().getDisplayName().contains("\u00a7")) { + return true; + } + + if (CommandHandler.isItemExpired(null, item)) { + return false; + } + if (noCustomNamedMaterials.contains((Object) type) && item.hasItemMeta() && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName() != null && !item.getItemMeta().getDisplayName().contains("\u00a7")) { + return false; + } + return type == Material.AIR; + } + + public static boolean handleAuction(Player player) { + MenuRenderer.openAuction(player); + return true; + } + + private static boolean isItemExpired(Player player, ItemStack item) { + Long expires; + NBTItem wrapper = new NBTItem(item); + NBTCompound builder = wrapper.getCompound("conaxData"); + if (builder != null && builder.hasKey("expiration") && (expires = builder.getLong("expiration")) != null && expires > 0L && expires < System.currentTimeMillis()) { + if (player != null) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You cannot sell expired items!"); + player.sendMessage(CC.Gray + "This item expired " + CC.GrayU + formatDifference((long) ((System.currentTimeMillis() - expires) / 1000L)) + CC.GrayU + " ago!"); + } + return true; + } + return false; + } + + public static boolean handleAuctionSell(Player player, String price) { + double dura; + Long expires; + ItemStack item = player.getItemInHand(); + if (item == null || item.getType() == Material.AIR) { + Util.message(player, "&c&l(!) &cEquip the item you want to sell in your hand."); + return true; + } + if (item.getType() == Material.STAINED_GLASS_PANE) { + Util.message(player, "&cYou cannot sell this item."); + return true; + } + if (!(item.getType() != Material.TRIPWIRE_HOOK || item.hasItemMeta() && item.getItemMeta().hasLore() && (((String) item.getItemMeta().getLore().get(1)).contains("by right-clicking the warchest") || ((String) item.getItemMeta().getLore().get(0)).contains(CC.Gray + "Consumed upon entering a")))) { + Util.message(player, "&cYou cannot sell this item."); + return true; + } + if (item.getType() == Material.CHEST && item.hasItemMeta() && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().contains("???")) { + Util.message(player, "&cYou cannot sell this item."); + return true; + } + if (MoneyNotesAPI.isMoneyNote((ItemStack) item)) { + Util.message(player, "&cYou cannot sell this item."); + return true; + } + if (item.getType() == Material.POTION && invisibilityEffectIds.contains(item.getDurability())) { + Util.message(player, "&cYou cannot sell this item."); + return true; + } + if (noCustomNamedMaterials.contains((Object) item.getType()) && item.hasItemMeta() && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName() != null && !item.getItemMeta().getDisplayName().contains("\u00a7")) { + Util.message(player, "&cYou cannot sell this item."); + return true; + } + if (CommandHandler.isItemExpired(player, item)) { + return true; + } + + NBTItem wrapper = new NBTItem(item); + NBTCompound builder = wrapper.getCompound("conaxData"); + if (builder != null && builder.hasKey("expiration") && (expires = builder.getLong("expiration")) != null && expires > 0L && expires < System.currentTimeMillis()) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You cannot sell expired items!"); + player.sendMessage(CC.Gray + "This item expired " + CC.GrayU + formatDifference((long) ((System.currentTimeMillis() - expires) / 1000L)) + CC.GrayU + " ago!"); + return false; + } + if (item.getType() == Material.POTION && Bukkit.getPluginManager().isPluginEnabled("CosmicFactionUtils") && ((dura = (double) item.getDurability()) == 8198.0 || dura == 8230.0 || dura == 8262.0 || dura == 16390.0 || dura == 16422.0 || dura == 16454.0)) { + Util.message(player, "&cYou cannot sell this item."); + return true; + } + if (item.containsEnchantment(Enchantment.DIG_SPEED) && item.getEnchantmentLevel(Enchantment.DIG_SPEED) > 5) { + Util.message(player, "&cYou cannot sell this item."); + return true; + } + + if (Auction.plugin.getConfig().getBoolean("auction.preventCreativeSale") && player.getGameMode() == GameMode.CREATIVE) { + Util.message(player, "&cYou cannot sell items while in creative."); + } else if (!AuctionUtil.canSellItemPermission(player)) { + Util.message(player, "&cYou cannot list more than " + AuctionUtil.getCurrentlySellingAmount(player) + " item(s) at once."); + Util.message(player, "&7Purchase ranks with &c/buy&7 to list more items concurrently."); + } else if (AuctionUtil.getItemsToCollectAmount(player) >= 6) { + Util.message(player, "&cYou have too many items in your Collection Bin."); + Util.message(player, "&7Claim those items before they vanish, &c/ah expired"); + } else if (!Util.stringIsNumerical(price) && !CommandHandler.isValidAlternatePrice(price)) { + Util.message(player, "&cThat is not a valid price."); + } else if (price.length() > 11) { + Util.message(player, "&cYou can only list something for a max of $99,999,999,999."); + } else { + Controller.attemptSell(player, item, CommandHandler.isValidAlternatePrice(price) ? Util.getMoneyValue(price) : Double.parseDouble(price)); + } + return true; + } + + private static boolean isValidAlternatePrice(String priceString) { + try { + long money = Util.getMoneyValue(priceString); + return money >= 0L && money <= Double.MAX_VALUE; + } catch (Exception e) { + return false; + } + } + + public static boolean handleExpired(Player player) { + MenuRenderer.expired(player); + return true; + } + + public static boolean handleSelling(Player player) { + MenuRenderer.selling(player); + return true; + } + + public static boolean handleHelp(Player player) { + Controller.help(player); + return true; + } + + public static boolean sendNonArg(Player player, Command command) { + if (command == Command.SELL) { + Util.message(player, "&e/ah sell "); + Util.message(player, "&7List the item you are holding on the auction house."); + } else { + Util.message(player, "&cUse /ah help for help."); + } + return true; + } + + public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String commandLabel, String[] argument) { + if (!(sender instanceof Player)) { + return false; + } + Player player = (Player) sender; + if (Auction.stoppingServer || CrankedCore.getInstance().getReboot() != null) { + Util.message(player, "&cYou cannot use the Auction House while the server is rebooting."); + return true; + } + if (Events.isLoading(player)) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "Please wait while your Auction data loads before using /ah!"); + return true; + } + switch (commandLabel.toLowerCase()) { + case "ah": { + int length = argument.length; + if (length < 1) { + return CommandHandler.handleAuction(player); + } + switch (argument[0].toLowerCase()) { + case "sell": { + if (length != 2) { + return CommandHandler.sendNonArg(player, Command.SELL); + } + return CommandHandler.handleAuctionSell(player, argument[1]); + } + case "ex": + case "expired": { + if (length != 1) { + return CommandHandler.sendNonArg(player, Command.EXPIRED); + } + return CommandHandler.handleExpired(player); + } + case "selling": + case "listed": { + if (length != 1) { + return CommandHandler.sendNonArg(player, Command.SELLING); + } + return CommandHandler.handleSelling(player); + } + case "help": + case "commands": { + if (length != 1) { + return CommandHandler.sendNonArg(player, Command.HELP); + } + return CommandHandler.handleHelp(player); + } + case "start": { + return CommandHandler.handleAuction(player); + } + case "togglesafety": + case "toggleconfirm": { + this.handleToggle(player); + return true; + } + case "startbid": + case "hand": + case "auction": + case "auc": { + this.handleStartBid(player, argument); + return true; + } + case "collect": { + new BidCollectionBinMenu(player, Auction.getPlugin().getBidManager().getBidCollectionBin().get(player.getUniqueId())).openGUI(Auction.getPlugin()); + return true; + } + case "bids": { + this.handleOpenBids(player); + return true; + } + case "stfu": + case "aucnotify": { + this.handleAuctionMute(player); + return true; + } + case "test": { + if (!player.isOp()) { + return true; + } + for (int i = 0; i < 60; ++i) { + AuctionBid newBid = new AuctionBid(UUID.randomUUID(), player, Lists.newArrayList(new ItemStack(Material.DIRT)), 1000L, 10L, -1L, 60); + Auction.getPlugin().getBidManager().getActiveAuctionBids().put(newBid.getBidID(), newBid); + } + return true; + } + } + Util.message(player, "&cType /ah help to list auction commands."); + } + case "bid": + case "bids": + case "auction": + case "auc": { + String arg; + if (argument.length > 1 && ((arg = argument[0]).equalsIgnoreCase("stfu") || arg.equalsIgnoreCase("aucnotify"))) { + this.handleToggle(player); + return true; + } + this.handleOpenBids(player); + } + } + return false; + } + + public void handleAuctionMute(Player player) { + if (Auction.getPlugin().getToggles().isBidMessageToggled(player)) { + Auction.getPlugin().getToggles().getNotifytoggles().remove(player.getUniqueId().toString()); + player.sendMessage((Object) ChatColor.GREEN + ChatColor.BOLD.toString() + "(!) " + (Object) ChatColor.GREEN + "You have toggled Auction Bid Notifications: " + (Object) ChatColor.GREEN + ChatColor.BOLD.toString() + "ON"); + } else { + Auction.getPlugin().getToggles().getNotifytoggles().add(player.getUniqueId().toString()); + player.sendMessage((Object) ChatColor.GREEN + ChatColor.BOLD.toString() + "(!) " + (Object) ChatColor.GREEN + "You have toggled Auction Bid Notifications: " + (Object) ChatColor.RED + ChatColor.BOLD.toString() + "OFF"); + } + } + + public void handleOpenBids(Player player) { + List toCollect = Auction.getPlugin().getBidManager().getBidCollectionBin().get(player.getUniqueId()); + if (toCollect != null && !toCollect.isEmpty()) { + player.sendMessage((Object) ChatColor.GRAY + "You have items awaiting collection in your " + CC.Green + "/ah collect!"); + return; + } + new BidMenu(player).openGUI(Auction.getPlugin()); + } + + public void handleStartBid(Player player, String[] arguments) { + Long buyoutPrice; + if (arguments.length < 3) { + player.sendMessage(CC.Red + "Invalid usage: /ah startbid [buyoutPrice]"); + return; + } + List toCollect = Auction.getPlugin().getBidManager().getBidCollectionBin().get(player.getUniqueId()); + if (toCollect != null && !toCollect.isEmpty()) { + player.sendMessage((Object) ChatColor.GRAY + "You have items awaiting collection in your " + CC.Green + "/ah collect!"); + return; + } + Set currentids = Auction.getPlugin().getBidManager().getCurrentBids().get(player.getUniqueId()); + if (currentids != null && currentids.size() >= 3) { + player.sendMessage(CC.RedB + "You can only have 3 Bid Auctions running at a time!"); + return; + } + Long startPrice = this.parseLongOrNull(arguments[1]); + Long incrementPrice = this.parseLongOrNull(arguments[2]); + Long l = buyoutPrice = arguments.length > 3 ? this.parseLongOrNull(arguments[3]) : null; + if (startPrice == null || startPrice < 1L) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You must enter a valid starting bid price!"); + return; + } + if (incrementPrice == null || incrementPrice < 5L) { + player.sendMessage((Object) ChatColor.RED + "You must enter a valid bid increment amount!"); + return; + } + if (buyoutPrice == null && arguments.length > 3 || buyoutPrice != null && buyoutPrice <= startPrice) { + player.sendMessage((Object) ChatColor.RED + "You must enter a valid buyout price greater than the starting bid!"); + return; + } + if (incrementPrice > 250000L) { + player.sendMessage(CC.RedB + "You cannot have an increment price more than $250,000"); + return; + } + BidManager bidManager = Auction.getPlugin().getBidManager(); + AuctionPackageMenu packageMenu = new AuctionPackageMenu(player, startPrice, incrementPrice, buyoutPrice == null ? -1L : buyoutPrice, player.getItemInHand(), successItems -> { + AuctionBid bid = new AuctionBid(UUID.randomUUID(), player, (List) successItems.getLeft(), startPrice, incrementPrice, buyoutPrice == null ? -1L : buyoutPrice, (Integer) successItems.getRight()); + bidManager.getActiveAuctionBids().put(bid.getBidID(), bid); + bidManager.getCurrentBids().computeIfAbsent(player.getUniqueId(), aucs -> new HashSet()).add(bid); + new BidMenu(player).openGUI(Auction.getPlugin()); + player.sendMessage(CC.GreenB + "(AH) " + CC.Gray + "You have started a bid for '" + CC.White + bid.getBidSellDisplayName() + CC.Gray + "' starting at " + CC.GreenB + "$" + CC.Green + Util.formatMoney(startPrice) + "!"); + Bukkit.getLogger().info("[AuctionHouse] " + player.getName() + " has started a bid for " + bid.getSellingItems() + " for $" + bid.getStartingBid() + " Inc=" + bid.getBidIncrementAmount() + " buyNow=" + bid.getBuyoutAmount()); + }); + packageMenu.openGUI(Auction.getPlugin()); + } + + private Long parseLongOrNull(String val) { + Long originalParse = Util.parseLongOrNull(val); + if (originalParse == null) { + try { + originalParse = Util.getMoneyValue(val); + } catch (Exception exception) { + // empty catch block + } + } + return originalParse; + } + + private void handleToggle(Player pl) { + SafetyToggle toggle = Auction.getPlugin().getToggles(); + if (toggle.isToggled(pl)) { + toggle.getToggles().remove(pl.getUniqueId().toString()); + pl.sendMessage((Object) ChatColor.GREEN + ChatColor.BOLD.toString() + "(!) " + (Object) ChatColor.GREEN + "You have toggled Auction Item Sell Confirmation: " + (Object) ChatColor.GREEN + ChatColor.BOLD.toString() + "ON"); + } else { + toggle.getToggles().add(pl.getUniqueId().toString()); + pl.sendMessage((Object) ChatColor.RED + ChatColor.BOLD.toString() + "(!) " + (Object) ChatColor.RED + "You have toggled Auction Item Sell Confirmation: " + (Object) ChatColor.RED + ChatColor.BOLD.toString() + "OFF"); + } + } + + public static String formatDifference(final long time) { + if (time == 0L) { + return "Never"; + } + final long day = TimeUnit.SECONDS.toDays(time); + final long hours = TimeUnit.SECONDS.toHours(time) - day * 24L; + final long minutes = TimeUnit.SECONDS.toMinutes(time) - TimeUnit.SECONDS.toHours(time) * 60L; + final long seconds = TimeUnit.SECONDS.toSeconds(time) - TimeUnit.SECONDS.toMinutes(time) * 60L; + final StringBuilder sb = new StringBuilder(); + if (day > 0L) { + sb.append(day).append(" ").append((day == 1L) ? "day" : "days").append(" "); + } + if (hours > 0L) { + sb.append(hours).append(" ").append((hours == 1L) ? "hour" : "hours").append(" "); + } + if (minutes > 0L) { + sb.append(minutes).append(" ").append((minutes == 1L) ? "minute" : "minutes").append(" "); + } + if (seconds > 0L && sb.length() <= 0) { + sb.append(seconds).append(" ").append((seconds == 1L) ? "second" : "seconds"); + } + final String diff = sb.toString(); + return diff.isEmpty() ? "Now" : diff; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/controller/ConfirmMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/controller/ConfirmMenu.java new file mode 100644 index 0000000..8892bd8 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/controller/ConfirmMenu.java @@ -0,0 +1,171 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.struct.DecimalFormatType + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.NumberUtils + * org.arkhamnetwork.Arkkit.patches.ItemID + * org.arkhamnetwork.Arkkit.plugins.ArkPlugins + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.OfflinePlayer + * org.bukkit.Sound + * org.bukkit.entity.Player + * org.bukkit.event.Event$Result + * org.bukkit.event.EventHandler + * org.bukkit.event.EventPriority + * org.bukkit.event.Listener + * org.bukkit.event.me.astropvp.cratekeys.inventory.InventoryClickEvent + * org.bukkit.event.me.astropvp.cratekeys.inventory.InventoryCloseEvent + * org.bukkit.event.player.PlayerDropItemEvent + * org.bukkit.event.player.PlayerPickupItemEvent + * org.bukkit.me.astropvp.cratekeys.inventory.Inventory + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.metadata.MetadataValue + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.controller; + + +import me.recolance.auction.Auction; +import me.recolance.auction.util.ItemUtils; +import me.recolance.auction.util.Util; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.text.DecimalFormat; + +public class ConfirmMenu + implements Listener { + private static final DecimalFormat formatter = new DecimalFormat("#,###"); + private static final DecimalFormat format = new DecimalFormat("#.##"); + + public static Inventory getConfirmMenu(ItemStack item, double price, double sellFee, double fee) { + Inventory inv = Bukkit.createInventory(null, (int) 9, (String) "Confirm Auction"); + String feeString = CC.RedB + "LISTING FEE: " + CC.RedB + "$" + CC.Red + NumberUtils.formatMoney((double) sellFee) + (CC.Red + " (" + format.format(fee * 100.0) + "%)"); + ItemStack confirm = ItemUtils.buildItem(Material.STAINED_GLASS_PANE, (short) 5, (Object) ChatColor.GREEN + ChatColor.BOLD.toString() + "Confirm Auction Price", (Object) ChatColor.GRAY + "Click to " + (Object) ChatColor.GREEN + ChatColor.BOLD.toString() + "accept" + (Object) ChatColor.GRAY + " the auction price for: ", (Object) ChatColor.WHITE + Util.getItemName(item), " ", (Object) ChatColor.YELLOW + ChatColor.BOLD.toString() + "PRICE: $" + (Object) ChatColor.YELLOW + formatter.format(price), feeString); + ItemStack decline = ItemUtils.buildItem(Material.STAINED_GLASS_PANE, (short) 14, (Object) ChatColor.RED + ChatColor.BOLD.toString() + "Decline Auction Price", (Object) ChatColor.GRAY + "Click to " + (Object) ChatColor.RED + ChatColor.BOLD.toString() + "decline" + (Object) ChatColor.GRAY + " the auction.", "", (Object) ChatColor.YELLOW + ChatColor.BOLD.toString() + "PRICE: $" + (Object) ChatColor.YELLOW + formatter.format(price), feeString); + inv.setItem(0, confirm); + inv.setItem(1, confirm); + inv.setItem(2, confirm); + inv.setItem(3, confirm); + inv.setItem(4, item); + inv.setItem(5, decline); + inv.setItem(6, decline); + inv.setItem(7, decline); + inv.setItem(8, decline); + return inv; + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = false) + public void onInventoryClick(InventoryClickEvent e) { + if (e.getInventory().getTitle().equals("Confirm Auction")) { + e.setCancelled(true); + e.setResult(Event.Result.DENY); + if (e.getClickedInventory() == null || e.getWhoClicked().getOpenInventory().getTopInventory() == null || !e.getClickedInventory().equals((Object) e.getWhoClicked().getOpenInventory().getTopInventory())) { + return; + } + Player p = (Player) e.getWhoClicked(); + if (!p.hasMetadata("auctionConfirm")) { + this.closePlayerInventoryOnClick(p); + return; + } + int slot = e.getRawSlot(); + if (slot < 4) { + ItemStack i = (ItemStack) ((MetadataValue) p.getMetadata("auctionConfirm").get(0)).value(); + double price = ((MetadataValue) p.getMetadata("auctionPrice").get(0)).asDouble(); + p.removeMetadata("auctionConfirm", (Plugin) Auction.getPlugin()); + p.removeMetadata("auctionPrice", (Plugin) Auction.getPlugin()); + double fee = Controller.getSellFee(p, price); + if (fee > 0.0 && !Auction.economy.has((OfflinePlayer) p, fee)) { + p.sendMessage(CC.RedB + "(!) " + CC.Red + "You can no longer afford the fee of " + CC.RedB + "$" + CC.Red + NumberUtils.formatMoney((double) fee)); + this.closePlayerInventoryOnClick(p); + return; + } + + Controller.sell(p, i, price, fee, false); + this.closePlayerInventoryOnClick(p); + } else { + if (slot > 4) { + ItemStack i = (ItemStack) ((MetadataValue) p.getMetadata("auctionConfirm").get(0)).value(); + p.removeMetadata("auctionConfirm", (Plugin) Auction.getPlugin()); + p.removeMetadata("auctionPrice", (Plugin) Auction.getPlugin()); + if (p.getInventory().firstEmpty() != -1) { + p.getInventory().addItem(new ItemStack[]{i}); + } else { + p.getWorld().dropItem(p.getLocation(), i); + } + p.sendMessage(ChatColor.RED.toString() + ChatColor.BOLD.toString() + "(!) " + (Object) ChatColor.RED + "You have cancelled your auction."); + p.playSound(p.getLocation(), Sound.BLAZE_DEATH, 1.0f, 1.2f); + this.closePlayerInventoryOnClick(p); + return; + } + } + } + } + + @EventHandler + public void onPlayerPickupItem(PlayerPickupItemEvent e) { + if (e.getPlayer().hasMetadata("auctionConfirm")) { + e.setCancelled(true); + } + } + + @EventHandler + public void onPlayerDropItem(PlayerDropItemEvent e) { + if (e.getPlayer().hasMetadata("auctionConfirm")) { + e.setCancelled(true); + } + } + + @EventHandler + public void onPlayerCloseInventory(InventoryCloseEvent e) { + if (e.getInventory().getTitle().equals("Confirm Auction") && e.getPlayer().hasMetadata("auctionConfirm")) { + final Player p = (Player) e.getPlayer(); + ItemStack i = (ItemStack) ((MetadataValue) p.getMetadata("auctionConfirm").get(0)).value(); + p.removeMetadata("auctionConfirm", (Plugin) Auction.getPlugin()); + p.removeMetadata("auctionPrice", (Plugin) Auction.getPlugin()); + if (!p.isDead() && p.getInventory().firstEmpty() != -1) { + p.getInventory().addItem(new ItemStack[]{i}); + } else { + p.getWorld().dropItem(p.getLocation(), i); + } + p.sendMessage(ChatColor.RED.toString() + ChatColor.BOLD.toString() + "(!) " + (Object) ChatColor.RED + "You have cancelled your auction."); + p.playSound(p.getLocation(), Sound.BLAZE_DEATH, 1.0f, 1.2f); + Bukkit.getScheduler().runTaskLater((Plugin) Auction.getPlugin(), new Runnable() { + + @Override + public void run() { + p.updateInventory(); + } + }, 1L); + } + } + + private void closePlayerInventoryOnClick(final Player p) { + Bukkit.getScheduler().runTaskLater((Plugin) Auction.getPlugin(), new Runnable() { + + @Override + public void run() { + p.closeInventory(); + } + }, 1L); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/controller/Controller.java b/Auctionhouse/src/main/java/me/recolance/auction/controller/Controller.java new file mode 100644 index 0000000..7a37061 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/controller/Controller.java @@ -0,0 +1,269 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.CosmicUtils + * com.cosmicpvp.cosmicutils.customevents.CustomCosmicPlayerEvent + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.struct.DecimalFormatType + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.HCFOutpostUtils + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.NumberUtils + * me.vaqxine.NetworkManager.NetworkManager + * net.milkbowl.vault.economy.Economy + * org.arkhamnetwork.Arkkit.Arkkit + * org.arkhamnetwork.Arkkit.net.astropvp.armorsets.commands.CommandArkReboot + * org.arkhamnetwork.Arkkit.patches.AntiCrash + * org.arkhamnetwork.Arkkit.patches.ItemID + * org.arkhamnetwork.Arkkit.plugins.ArkPlugins + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.OfflinePlayer + * org.bukkit.Sound + * org.bukkit.entity.Player + * org.bukkit.event.Event + * org.bukkit.inventory.ItemStack + * org.bukkit.metadata.FixedMetadataValue + * org.bukkit.metadata.MetadataValue + * org.bukkit.plugin.Plugin + * org.bukkit.scheduler.BukkitRunnable + */ +package me.recolance.auction.controller; + + +import me.recolance.auction.Auction; +import me.recolance.auction.auction.Listing; +import me.recolance.auction.auction.UnclaimedListing; +import me.recolance.auction.command.Command; +import me.recolance.auction.data.DataHandler; +import me.recolance.auction.data.DataHolder; +import me.recolance.auction.util.AuctionUtil; +import me.recolance.auction.util.Util; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.milkbowl.vault.economy.Economy; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class Controller { + private static Economy economy = Auction.economy; + + public static void purchase(Player player, Listing listing) { + double price = listing.getPrice(); + ItemStack item = listing.getItem(); + economy.withdrawPlayer(Bukkit.getOfflinePlayer((UUID) player.getUniqueId()), (double) price); + economy.depositPlayer(Bukkit.getOfflinePlayer((UUID) listing.getWhoListed()), (double) price); + PlayerUtils.giveOrDropProtectedItem(player, item, 60); + + DataHolder.removeListing(listing); + DataHolder.removePlayerListing(listing.getWhoListed(), listing); + Util.message(player, "&c&l- $" + price); + player.playSound(player.getLocation(), Sound.VILLAGER_HAGGLE, 1.0f, 3.0f); + Player seller = Bukkit.getPlayer((UUID) listing.getWhoListed()); + if (seller != null) { + Util.message(seller, "&e&6" + player.getName() + "&e has &6purchased &eyour listing of &6" + Util.getItemName(item) + "&r&e!"); + Util.message(seller, "&a&l+ $" + price); + seller.playSound(seller.getLocation(), Sound.CHICKEN_EGG_POP, 1.0f, 0.65f); + } + DataHandler.deleteListing(listing, true); + } + + public static void attemptSell(Player player, ItemStack item, double price) { + if (price > Double.MAX_VALUE) { + player.sendMessage((Object) ChatColor.RED + "You cannot list for this amount."); + return; + } + if (price < 0) { + price = 0; + } + if (player.hasMetadata("auctionConfirm") && player.getMetadata("auctionConfirm").size() > 0) { + player.sendMessage(ChatColor.RED.toString() + ChatColor.BOLD.toString() + "(!) " + (Object) ChatColor.RED + "You are creating auctions too quickly!"); + return; + } + double fee = Controller.getSellFee(player, price); + if (!Auction.economy.has((OfflinePlayer) player, fee)) { + player.sendMessage(CC.Red + "(!) " + CC.Red + "You cannot afford the sell fee of " + CC.RedB + "$" + CC.Red + NumberUtils.formatMoney((double) fee)); + return; + } + if (Auction.getPlugin().hasToggle(player)) { + item = player.getItemInHand().clone(); + Controller.sell(player, item, price, fee, true); + } else { + item = player.getItemInHand().clone(); + player.setItemInHand(null); + player.setMetadata("auctionConfirm", (MetadataValue) new FixedMetadataValue((Plugin) Auction.getPlugin(), (Object) item)); + player.setMetadata("auctionPrice", (MetadataValue) new FixedMetadataValue((Plugin) Auction.getPlugin(), (Object) price)); + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 0.8f, 0.8f); + player.openInventory(ConfirmMenu.getConfirmMenu(item, price, fee, Controller.getSellFee(player))); + } + } + + public static double getSellFee(Player player, double cost) { + if (Auction.getPlugin().getConfig().getBoolean("auction.sellFee", true)) { + return Math.min(1000000.0, cost * Controller.getSellFee(player)); + } + return 0.0; + } + + public static double getSellFee(Player player) { + + if (player.hasPermission("enchantments.max.20")) { + return 0.005; + } + if (player.hasPermission("enchantments.max.12")) { + return 0.0075; + } + if (player.hasPermission("enchantments.max.9")) { + return 0.01; + } + if (player.hasPermission("enchantments.max.6")) { + return 0.0125; + } + return 0.015; + } + + public static void sell(Player player, ItemStack item, double price, double fee, boolean removeItem) { + Listing listing = new Listing(UUID.randomUUID(), AuctionUtil.getEndTime(), player.getUniqueId(), item, price); + if (removeItem) { + player.setItemInHand(null); + } + DataHolder.addListing(listing); + DataHolder.addPlayerListing(player.getUniqueId(), listing); + Util.message(player, "&e&l(!) &eYou have &6listed &eyour " + Util.getItemName(item) + "&e on the auction house for &6$" + price + "&e!"); + DataHandler.saveListing(listing, true); + if (fee > 0.0) { + Auction.economy.withdrawPlayer((OfflinePlayer) player, fee); + player.sendMessage(CC.RedB + "(AH Fee) - $" + CC.Red + NumberUtils.formatMoney((double) fee)); + } + } + + public static void cancel(Player player, Listing listing) { + DataHolder.removeListing(listing); + DataHolder.removePlayerListing(listing.getWhoListed(), listing); + UnclaimedListing ucL = new UnclaimedListing(UUID.randomUUID(), listing.getWhoListed(), listing.getItem(), AuctionUtil.getUnclaimedEndTime()); + DataHolder.addUnclaimedListing(listing.getWhoListed(), ucL); + DataHandler.deleteListing(listing, true); + DataHandler.saveUnclaimedListing(ucL, true); + Util.message(player, "&e&l(!) &eYou have &6cancelled &ean auction &6listing&e. Return cancelled and expired listings at &6/ah expired&e."); + } + + public static void adminCancel(Player player, Listing listing) { + DataHolder.removeListing(listing); + DataHolder.removePlayerListing(listing.getWhoListed(), listing); + UnclaimedListing ucL = new UnclaimedListing(UUID.randomUUID(), listing.getWhoListed(), listing.getItem(), AuctionUtil.getUnclaimedEndTime()); + if (Bukkit.getPlayer((UUID) listing.getWhoListed()) != null) { + DataHolder.addUnclaimedListing(listing.getWhoListed(), ucL); + } + DataHandler.deleteListing(listing, true); + DataHandler.saveUnclaimedListing(ucL, true); + Util.message(player, "&c&l(!) &cListing removed."); + } + + public static void expire(Listing listing) { + DataHolder.removeListing(listing); + DataHolder.removePlayerListing(listing.getWhoListed(), listing); + UnclaimedListing ucL = new UnclaimedListing(UUID.randomUUID(), listing.getWhoListed(), listing.getItem(), AuctionUtil.getUnclaimedEndTime()); + if (Bukkit.getPlayer((UUID) listing.getWhoListed()) != null) { + DataHolder.addUnclaimedListing(listing.getWhoListed(), ucL); + } + DataHandler.deleteListing(listing, true); + DataHandler.saveUnclaimedListing(ucL, true); + } + + public static void expireUnclaimed(UnclaimedListing listing) { + DataHolder.removeUnclaimedListing(listing.getListedBy(), listing); + DataHandler.deleteUnclaimedListing(listing, true); + } + + public static void claim(Player player, UnclaimedListing listing) { + DataHolder.getUnclaimedListings().get(player.getUniqueId()).remove(listing); + DataHandler.deleteUnclaimedListing(listing, true); + PlayerUtils.giveOrDropProtectedItem(player, listing.getItem(), 60); + } + + public static void claimAll(Player player) { + int space = Util.getFreeInventorySpace(player); + int i = 0; + ArrayList claim = new ArrayList(); + for (UnclaimedListing listing : DataHolder.getUnclaimedListings().get(player.getUniqueId())) { + if (i >= space && !Util.hasInventorySpace(player)) { + Util.message(player, "&c&l(!) &cYou don't have enough inventory space."); + break; + } + + PlayerUtils.giveOrDropProtectedItem(player, listing.getItem(), 60); + + claim.add(listing); + ++i; + } + for (UnclaimedListing listing : claim) { + DataHolder.removeUnclaimedListing(player.getUniqueId(), listing); + DataHandler.deleteUnclaimedListing(listing, true); + } + Util.message(player, "&e&l(!) &eYou have claimed &6" + i + " &e expired listings."); + } + + public static void help(Player player) { + Util.message(player, ""); + Util.message(player, "&e&l&nAuction House Commands"); + for (Command command : Command.values()) { + Util.message(player, command.getDescription()[1]); + Util.message(player, command.getDescription()[2]); + Util.message(player, ""); + } + player.sendMessage(CC.Yellow + "/ah startbid [buyNowPrice]"); + player.sendMessage(CC.Gray + "Create an auction package for others to bid on!"); + player.sendMessage(""); + player.sendMessage(CC.Yellow + "/ah collect"); + player.sendMessage(CC.Gray + "Collect items from previous bid auctions!"); + player.sendMessage(""); + player.sendMessage(CC.Yellow + "/ah bids"); + player.sendMessage(CC.Gray + "View all active bid auctions!"); + player.sendMessage(""); + player.sendMessage(CC.Yellow + "/ah stfu"); + player.sendMessage(CC.Gray + "Turn off alerts when someone outbids you!"); + player.sendMessage(""); + } + + public static void expireListings() { + new BukkitRunnable() { + + public void run() { + if (Auction.stoppingServer || CrankedCore.getInstance().getReboot() != null) { + return; + } + List listings = DataHolder.getListings(); + if (listings.size() > 0 && listings.get(listings.size() - 1).getEndTime() < System.currentTimeMillis()) { + Listing l = listings.get(listings.size() - 1); + Controller.expire(l); + Bukkit.getLogger().info("[Auction] Expiring auction " + l.getId() + " of " + (Object) l.getItem() + " for " + l.getWhoListed() + " for $" + l.getPrice()); + } + } + }.runTaskTimer((Plugin) Auction.plugin, 100L, 100L); + } + + public static void expireOfflineUnclaimedListings() { + new BukkitRunnable() { + + public void run() { + DataHandler.deleteOverExpiredUnclaimedListing(true); + } + }.runTaskTimer((Plugin) Auction.plugin, 0L, 3600L); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/controller/Events.java b/Auctionhouse/src/main/java/me/recolance/auction/controller/Events.java new file mode 100644 index 0000000..8f56738 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/controller/Events.java @@ -0,0 +1,68 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.Bukkit + * org.bukkit.entity.Player + * org.bukkit.event.EventHandler + * org.bukkit.event.EventPriority + * org.bukkit.event.Listener + * org.bukkit.event.player.PlayerJoinEvent + * org.bukkit.event.player.PlayerQuitEvent + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.controller; + +import me.recolance.auction.Auction; +import me.recolance.auction.auction.UnclaimedListing; +import me.recolance.auction.data.DataHandler; +import me.recolance.auction.data.DataHolder; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.Plugin; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +public class Events + implements Listener { + public static Set loadingUUIDs = new HashSet(); + + public static boolean isLoading(Player player) { + return loadingUUIDs.contains(player.getUniqueId()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerJoinEvent(PlayerJoinEvent event) { + Player player = event.getPlayer(); + UUID uuid = player.getUniqueId(); + List found = DataHolder.getUnclaimedListings().get(uuid); + if (found != null) { + Bukkit.getLogger().info("[AuctionHouse] Skipping loadUnclaimedListings for " + uuid.toString() + " due to already having keys (" + found + ") in unclaimedListings map."); + loadingUUIDs.remove(uuid); + return; + } + if (loadingUUIDs.contains(player.getUniqueId())) { + Bukkit.getLogger().info("[AuctionHouse] Skipping loading of data for " + player.getUniqueId() + " since there is a pending thread already handling it."); + return; + } + loadingUUIDs.add(player.getUniqueId()); + Bukkit.getScheduler().runTaskAsynchronously((Plugin) Auction.getPlugin(), () -> { + DataHandler.loadUnclaimedListings(uuid); + loadingUUIDs.remove(player.getUniqueId()); + }); + } + + @EventHandler + public void onLeave(PlayerQuitEvent event) { + DataHolder.removeUnclaimedListingStore(event.getPlayer().getUniqueId()); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/data/AuctionBid.java b/Auctionhouse/src/main/java/me/recolance/auction/data/AuctionBid.java new file mode 100644 index 0000000..bf36887 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/data/AuctionBid.java @@ -0,0 +1,464 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.CosmicGUI + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.JSONMessage + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.TimeUtils + * com.google.common.collect.Lists + * org.apache.commons.lang.builder.HashCodeBuilder + * org.arkhamnetwork.Arkkit.patches.ItemID + * org.arkhamnetwork.Arkkit.plugins.ArkPlugins + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.OfflinePlayer + * org.bukkit.Sound + * org.bukkit.entity.Player + * org.bukkit.inventory.ItemStack + * org.bukkit.inventory.meta.ItemMeta + * org.bukkit.metadata.FixedMetadataValue + * org.bukkit.metadata.MetadataValue + * org.bukkit.plugin.Plugin + * org.bukkit.plugin.java.JavaPlugin + */ +package me.recolance.auction.data; + + +import com.google.common.collect.Lists; +import me.recolance.auction.Auction; +import me.recolance.auction.menu.BidManager; +import me.recolance.auction.menu.bidmenus.BiddableMenu; +import me.recolance.auction.menu.bidmenus.ConfirmItemMenu; +import me.recolance.auction.menu.bidmenus.PackageViewMenu; +import me.recolance.auction.util.ItemSerialization; +import me.recolance.auction.util.Util; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.JSONMessage; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import org.apache.commons.lang.builder.HashCodeBuilder; + +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +public class AuctionBid { + private static final long AUCTION_LENGTH_TIME = TimeUnit.SECONDS.toSeconds(60L); + private static final long ANTI_SNIPE_TIME = TimeUnit.SECONDS.toMillis(2L); + private transient List sellingItems = Lists.newArrayList(); + private List serializedStringVersion = Lists.newArrayList(); + private UUID bidID; + private UUID sellerUUID; + private double startingBid; + private double buyoutAmount; + private long currentBid; + private long bidIncrementAmount; + private UUID currentHighestBidder; + private String currentBidderName; + private String sellerName; + private long auctionStart; + private long lastBidTime; + private int secondsLeftInAuction = 0; + private Set bidders = new HashSet(); + private boolean expired = false; + + public AuctionBid(UUID bidID, Player seller, List itemsToSell, long startingBid, long bidIncrementAmount, long buyoutAmount, int duration) { + this.bidID = bidID; + this.sellerUUID = seller.getUniqueId(); + this.sellerName = seller.getName(); + this.sellingItems = itemsToSell; + this.startingBid = startingBid; + this.bidIncrementAmount = bidIncrementAmount; + this.secondsLeftInAuction = duration; + this.auctionStart = System.currentTimeMillis(); + this.buyoutAmount = buyoutAmount; + this.serializeItems(); + } + + public void serializeItems() { + for (ItemStack selling : this.sellingItems) { + this.serializedStringVersion.add(ItemSerialization.itemToStringBase64(selling)); + } + } + + public void deserialize() { + this.sellingItems = Lists.newArrayList(); + if (this.serializedStringVersion != null) { + for (String serialized : this.serializedStringVersion) { + this.sellingItems.add(ItemSerialization.itemFromBase64(serialized)); + } + } + } + + public boolean isSeller(Player player) { + if (player.getName().equals("iFamasssxD") || player.getName().equals("Merchant")) { + return false; + } + return player.getUniqueId().equals(this.sellerUUID); + } + + public boolean isPackageDeal() { + return this.sellingItems.size() > 1; + } + + public void placePlayerBid(Player bidder, long bidAmount) { + if (this.expired) { + bidder.sendMessage((Object) ChatColor.RED + "Item Auction no longer valid!"); + return; + } + if (this.currentHighestBidder != null) { + OfflinePlayer player = Bukkit.getOfflinePlayer((UUID) this.currentHighestBidder); + Auction.economy.depositPlayer(player, (double) this.currentBid); + if (player instanceof Player && !Auction.getPlugin().getToggles().isBidMessageToggled((Player) player)) { + ((Player) player).sendMessage((Object) ChatColor.RED + ChatColor.BOLD.toString() + "(AH) " + CC.Red + bidder.getName() + CC.RedB + " OUTBID " + CC.Red + "you on " + CC.White + "'" + this.getBidSellDisplayName() + CC.White + "'" + CC.Red + " - " + CC.RedB + "$" + Util.formatMoney(bidAmount) + "!"); + } + } + bidder.playSound(bidder.getLocation(), Sound.ORB_PICKUP, 0.4f, 1.1f); + bidder.sendMessage(CC.GreenB + "(AH) " + CC.Gray + "You have placed the highest bid for " + CC.GreenB + "$" + CC.Green + Util.formatMoney(bidAmount) + "!"); + Auction.economy.withdrawPlayer((OfflinePlayer) bidder, (double) bidAmount); + this.currentBid = bidAmount; + this.currentBidderName = bidder.getName(); + this.currentHighestBidder = bidder.getUniqueId(); + this.lastBidTime = System.currentTimeMillis(); + this.bidders.add(bidder.getUniqueId()); + } + + public void buyNow(Player buyer) { + if (this.expired) { + return; + } + if (!Auction.economy.has((OfflinePlayer) buyer, this.buyoutAmount)) { + return; + } + this.expired = true; + Auction.getPlugin().getBidManager().removeAuctionBid(this); + if (this.currentHighestBidder != null) { + OfflinePlayer originalBuyer = Bukkit.getOfflinePlayer((UUID) this.currentHighestBidder); + if (originalBuyer != null && originalBuyer instanceof Player) { + ((Player) originalBuyer).sendMessage(CC.RedB + "(AH) " + CC.GreenB + this.currentBidderName + CC.Gray + " purchased " + CC.GreenU + this.sellerName + "'s" + CC.Gray + " auction of '" + this.getBidSellDisplayName() + CC.Gray + "' for " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.buyoutAmount) + CC.Gray + "!"); + } + if (originalBuyer != null) { + Bukkit.getLogger().info("Returning $" + this.currentBid + " to " + originalBuyer.getName() + " due to " + buyer.getName() + " buying out item!"); + Auction.economy.depositPlayer(originalBuyer, (double) this.currentBid); + } + } + Auction.economy.withdrawPlayer((OfflinePlayer) buyer, this.buyoutAmount); + OfflinePlayer seller = Bukkit.getOfflinePlayer((UUID) this.sellerUUID); + Auction.economy.depositPlayer(seller, this.buyoutAmount); + if (seller instanceof Player) { + Player onlinePlayer = (Player) seller; + onlinePlayer.sendMessage(CC.GreenB + "(AH) " + CC.GreenB + buyer.getName() + CC.Gray + " has purchased your '" + this.getBidSellDisplayName() + CC.Gray + "' for " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.buyoutAmount) + "!"); + } + this.transferItemsToOwner(buyer.getUniqueId()); + } + + public void expire() { + List sellerBin = Auction.getPlugin().getBidManager().getBidCollectionBin().computeIfAbsent(this.sellerUUID, newBin -> Lists.newArrayList()); + for (ItemStack item : this.sellingItems) { + sellerBin.add(item); + } + Auction.getPlugin().getBidManager().removeAuctionBid(this); + } + + public ItemStack getAuctionDisplayItem(boolean watchlist) { + boolean canBuyout; + ItemStack toShow = null; + List lore = Lists.newArrayList(); + if (this.isPackageDeal()) { + lore.add(""); + lore.add((Object) ChatColor.GOLD + "Bundle of " + CC.GoldB + this.getSellingItems().size() + "x " + CC.Gold + "Items:"); + for (ItemStack item : this.getSellingItems()) { + lore.add(" " + CC.GoldB + "* " + (item.getAmount() > 1 ? item.getAmount() + "x " : "") + CC.White + Util.getItemName(item)); + } + toShow = this.getSellingItems().get(0); + } else { + ItemStack item = this.getSellingItems().get(0); + if (item != null && item.hasItemMeta() && item.getItemMeta().hasLore()) { + lore = item.getItemMeta().getLore(); + } + if (item != null) { + toShow = item; + } + } + if (toShow == null) { + toShow = new ItemStack(Material.DIRT); + } + lore.add(""); + lore.add((Object) ChatColor.GRAY + "--------------------------"); + lore.add(""); + lore.add(CC.Gold + "Starting Bid: " + CC.YellowB + "$" + CC.Yellow + Util.formatMoney(this.getStartingBid())); + String color = this.getBidIncrementAmount() >= 100000L ? CC.Red : CC.Yellow; + lore.add(CC.Gold + "Bid Increment: " + color + CC.Bold + "$" + color + Util.formatMoney(this.getBidIncrementAmount())); + lore.add(CC.Gold + "Current Bid: " + CC.YellowB + "$" + CC.Yellow + Util.formatMoney(this.getCurrentBid())); + if (this.getCurrentBidderName() != null) { + lore.add(CC.Gold + "Highest Bidder: " + CC.Yellow + this.getCurrentBidderName()); + } + if (canBuyout = this.getBuyoutAmount() > 1.0 && (double) this.getCurrentBid() < this.getBuyoutAmount()) { + lore.add(CC.Gold + "Buy Now for " + CC.YellowB + "$" + Util.formatMoney(this.getBuyoutAmount())); + } + lore.add(CC.Gold + "Seller: " + CC.Yellow + this.getSellerName()); + if (watchlist || this.getSecondsLeftInAuction() > 0) { + lore.add(CC.Gold + "Auction Ending in " + CC.GoldB + (this.getSecondsLeftInAuction() <= 0 ? "1s" : TimeUtils.formatSeconds((long) this.getSecondsLeftInAuction()))); + } + lore.add(""); + lore.add(CC.Yellow + "Left-Click" + CC.Gray + " to bid on this item"); + lore.add(CC.Yellow + "Middle-Click " + CC.Gray + "to enter custom bid"); + if (canBuyout) { + lore.add(CC.Yellow + "Shift-LClick " + CC.Gray + "to buy it now"); + } + if (watchlist) { + lore.add(CC.Yellow + "Shift-RClick " + CC.Gray + "to add to watchlist"); + } else { + lore.add(CC.Yellow + "Shift-RClick " + CC.Gray + "to remove from watchlist"); + } + if (this.isPackageDeal()) { + lore.add(CC.Yellow + "Right-Click" + CC.Gray + " to view package contents"); + } + lore.add((Object) ChatColor.GRAY + "--------------------------"); + toShow = toShow.clone(); + ItemMeta im = toShow.getItemMeta(); + im.setLore(lore); + toShow.setItemMeta(im); + return toShow; + } + + public Runnable getRightClickLogic(BiddableMenu parent, Player player) { + return () -> { + if (this.isExpired()) { + player.sendMessage(CC.Red + "That item is no longer available!"); + parent.redraw(); + return; + } + if (this.isPackageDeal()) { + new PackageViewMenu(player, this, parent).openGUI(Auction.getPlugin()); + } + }; + } + + public Runnable getLeftClickLogic(BiddableMenu parent, Player player) { + return () -> { + if (this.isExpired()) { + player.sendMessage((Object) ChatColor.RED + "That item is no longer available!"); + parent.redraw(); + return; + } + if (this.isSeller(player)) { + player.sendMessage(CC.RedB + "You cannot bid on your own items!"); + return; + } + if (this.getCurrentHighestBidder() != null && this.getCurrentHighestBidder().equals(player.getUniqueId())) { + player.sendMessage(CC.Green + "You are already the highest bidder!"); + return; + } + long nextBid = (long) ((this.getCurrentBid() == 0L ? this.getStartingBid() : (double) this.getCurrentBid()) + (double) this.getBidIncrementAmount()); + if (!Auction.economy.has((OfflinePlayer) player, (double) nextBid)) { + player.sendMessage(CC.Gray + "You cannot afford a bid of " + CC.GreenB + "$" + CC.Green + Util.formatMoney(nextBid)); + return; + } + if (parent.lastBid != 0L && System.currentTimeMillis() - parent.lastBid <= 1000L) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "Please wait at least 1 second before placing another bid!"); + return; + } + parent.lastBid = System.currentTimeMillis(); + if (!Auction.getPlugin().getToggles().isToggled(player) && !this.bidders.contains(player.getUniqueId())) { + new ConfirmItemMenu(player, "Confirm First Time Bid", nextBid, this, confirm -> { + this.placePlayerBid(player, nextBid); + parent.forceUpdate = true; + parent.openGUI(Auction.getPlugin()); + }, deny -> parent.openGUI(Auction.getPlugin())).openGUI(Auction.getPlugin()); + } else { + this.placePlayerBid(player, nextBid); + parent.forceUpdate = true; + parent.redraw(); + } + }; + } + + public Runnable getShiftLeftClickLogic(CosmicGUI parent, Player player) { + return () -> { + if (this.getBuyoutAmount() <= 0.0) { + player.sendMessage(CC.RedB + "You can only bid on this item!"); + return; + } + if (this.isSeller(player)) { + player.sendMessage(CC.RedB + "You cannot bid on your own items!"); + return; + } + if (this.isExpired()) { + player.sendMessage(CC.RedB + "That item is no longer available!"); + parent.redraw(); + return; + } + if (!Auction.economy.has((OfflinePlayer) player, this.getBuyoutAmount())) { + player.sendMessage(CC.Gray + "You cannot afford a bid of " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.getBuyoutAmount())); + return; + } + long buyout = (long) this.getBuyoutAmount(); + new ConfirmItemMenu(player, "Buy it Now?", buyout, this, ConfirmItemMenu.getConfirmCallback(this, player, buyout, true), deny -> parent.openGUI((JavaPlugin) Auction.getPlugin())).openGUI(Auction.getPlugin()); + }; + } + + public Runnable getMiddleClickLogic(CosmicGUI menuViewing, Player player) { + return () -> { + if (this.isSeller(player)) { + player.sendMessage(CC.RedB + "You cannot bid on your own items!"); + return; + } + if (this.isExpired()) { + player.sendMessage(CC.RedB + "That item is no longer available!"); + menuViewing.redraw(); + return; + } + player.setMetadata("auctionBidding", (MetadataValue) new FixedMetadataValue((Plugin) Auction.getPlugin(), (Object) this.getBidID().toString())); + player.closeInventory(); + player.sendMessage(CC.GreenB + "(!) " + CC.Green + "Please enter a " + CC.GreenU + "custom bid" + CC.Green + " amount" + (this.getBuyoutAmount() > 1.0 && (double) this.getCurrentBid() < this.getBuyoutAmount() ? " " + CC.GreenB + CC.Underline + "OR" + CC.Green + " enter '" + Util.formatMoney(this.getBuyoutAmount()) + "' to Buy Now!" : "!")); + }; + } + + public void onTick() { + if (this.expired) { + Bukkit.getLogger().info("Called onTick for expired auctionBid: " + this.bidID + " Seller: " + this.sellerName); + return; + } + if (this.secondsLeftInAuction <= 0) { + this.expired = true; + Player seller = Bukkit.getPlayer((UUID) this.sellerUUID); + if (this.currentBid <= 0L || this.currentHighestBidder == null) { + Bukkit.getLogger().info("Expiring bid for " + this.getSellerUUID() + " due to noone placing a bid: " + this.getSellingItems()); + if (seller != null) { + seller.sendMessage(CC.RedB + "(AH) " + CC.Red + "Auction Bid expired for '" + this.getBidSellDisplayName() + CC.Red + "'!"); + seller.sendMessage(CC.Gray + "You can access your expired bid auction items in " + CC.GrayU + "/ah collect" + CC.Gray + "!"); + } + this.expire(); + } else if (System.currentTimeMillis() - this.lastBidTime <= ANTI_SNIPE_TIME) { + this.secondsLeftInAuction = 10; + if (seller != null) { + seller.sendMessage(CC.YellowB + "(AH) ANTI SNIPE ACTIVATED - " + CC.Yellow + "Adding 10s to bid..."); + } + this.expired = false; + } else { + OfflinePlayer buyer = Bukkit.getOfflinePlayer((UUID) this.currentHighestBidder); + Auction.economy.depositPlayer((OfflinePlayer) (seller == null ? Bukkit.getOfflinePlayer((UUID) this.sellerUUID) : seller), (double) this.currentBid); + String displayName = this.getBidSellDisplayName(); + if (seller != null) { + String finishedString = CC.GreenB + "SOLD: \n"; + for (ItemStack toSell : this.sellingItems) { + finishedString = finishedString + CC.GoldB + " * " + CC.White + Util.getItemName(toSell) + "\n"; + } + JSONMessage message = new JSONMessage(CC.GreenB + "(AH) " + CC.Gray + "Your auction for '", ChatColor.GRAY); + message.addHoverData(displayName, finishedString); + message.addText(null, CC.Gray + "' was purchased by " + CC.GreenU + this.currentBidderName + CC.Gray + " for " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.currentBid) + CC.Gray + " after " + CC.GreenB + Util.timeToDHMSString(System.currentTimeMillis() - this.auctionStart) + "!", ChatColor.GRAY); + message.sendToPlayer(seller); + } + if (buyer != null && buyer instanceof Player) { + Player pl = (Player) buyer; + pl.sendMessage(""); + pl.sendMessage(CC.GreenB + "(AH) " + CC.Gray + "You have purchased '" + displayName + CC.Gray + "' from " + CC.GreenB + this.sellerName + CC.Gray + " for " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.currentBid) + "!"); + pl.sendMessage(CC.Gray + "Collect your winning Auction Item(s) from your " + CC.GrayU + "/ah collect"); + } + this.transferItemsToOwner(this.currentHighestBidder); + this.bidders.forEach(playerUUID -> { + if (playerUUID.equals(this.currentHighestBidder)) { + return; + } + Player onlineOrOffline = Bukkit.getPlayer((UUID) playerUUID); + if (onlineOrOffline != null) { + onlineOrOffline.sendMessage(CC.RedB + "(AH) " + CC.GreenB + this.currentBidderName + CC.Gray + " has won " + CC.GreenU + this.sellerName + "'s" + CC.Gray + " auction for '" + displayName + CC.Gray + "' bidding " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.currentBid) + CC.Gray + " and outbidding " + CC.GreenB + CC.Underline + (this.bidders.size() - 1) + CC.Gray + " bidders!"); + } + }); + } + } else { + --this.secondsLeftInAuction; + } + } + + public void transferItemsToOwner(UUID owner) { + BidManager manager = Auction.getPlugin().getBidManager(); + List binItems = manager.getBidCollectionBin().computeIfAbsent(owner, newBin -> Lists.newArrayList()); + for (ItemStack sellingItem : this.sellingItems) { + ItemStack won; + ItemStack withoutID = won = sellingItem; + + binItems.add(withoutID); + } + Bukkit.getLogger().info("Transfering " + binItems.size() + " items to " + owner + "'s bid bin from " + this.sellerName + "'s Auction: " + this.sellingItems); + } + + public String getBidSellDisplayName() { + if (this.sellingItems.size() > 1) { + return CC.GreenB + this.sellingItems.size() + "x Item Package"; + } + return Util.getItemName(this.sellingItems.get(0)); + } + + public boolean equals(Object obj) { + AuctionBid other; + if (obj instanceof AuctionBid && (other = (AuctionBid) obj).getBidID() != null && other.getBidID().equals(this.getBidID()) && this.getSellerUUID() != null && this.getSellerUUID().equals(other.getSellerUUID())) { + return true; + } + return super.equals(obj); + } + + public int hashCode() { + return new HashCodeBuilder(17, 37).append((Object) this.bidID).append((Object) this.sellerUUID).toHashCode(); + } + + public List getSellingItems() { + return this.sellingItems; + } + + public UUID getBidID() { + return this.bidID; + } + + public UUID getSellerUUID() { + return this.sellerUUID; + } + + public double getStartingBid() { + return this.startingBid; + } + + public double getBuyoutAmount() { + return this.buyoutAmount; + } + + public long getCurrentBid() { + return this.currentBid; + } + + public long getBidIncrementAmount() { + return this.bidIncrementAmount; + } + + public UUID getCurrentHighestBidder() { + return this.currentHighestBidder; + } + + public String getCurrentBidderName() { + return this.currentBidderName; + } + + public String getSellerName() { + return this.sellerName; + } + + public int getSecondsLeftInAuction() { + return this.secondsLeftInAuction; + } + + public boolean isExpired() { + return this.expired; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/data/AuctionItem.java b/Auctionhouse/src/main/java/me/recolance/auction/data/AuctionItem.java new file mode 100644 index 0000000..243ef0d --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/data/AuctionItem.java @@ -0,0 +1,14 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + */ +package me.recolance.auction.data; + +import org.bukkit.inventory.ItemStack; + +public interface AuctionItem { + public ItemStack getDisplay(); +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/data/BidInformation.java b/Auctionhouse/src/main/java/me/recolance/auction/data/BidInformation.java new file mode 100644 index 0000000..cc7f5f5 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/data/BidInformation.java @@ -0,0 +1,29 @@ +/* + * Decompiled with CFR 0.150. + */ +package me.recolance.auction.data; + +public class BidInformation { + private String playerName; + private long bidStart; + private long maxBid; + + public BidInformation(String playerName, long bidStart, long maxBid) { + this.playerName = playerName; + this.bidStart = bidStart; + this.maxBid = maxBid; + } + + public String getPlayerName() { + return this.playerName; + } + + public long getBidStart() { + return this.bidStart; + } + + public long getMaxBid() { + return this.maxBid; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/data/DataHandler.java b/Auctionhouse/src/main/java/me/recolance/auction/data/DataHandler.java new file mode 100644 index 0000000..b378992 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/data/DataHandler.java @@ -0,0 +1,406 @@ +// Decompiled with: FernFlower +// Class Version: 8 +package me.recolance.auction.data; + + +import com.google.common.collect.Lists; +import com.google.common.io.BaseEncoding; +import me.recolance.auction.Auction; +import me.recolance.auction.auction.Listing; +import me.recolance.auction.auction.UnclaimedListing; +import me.recolance.auction.menu.categories.AuctionCategory; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.minecraft.server.v1_8_R3.NBTCompressedStreamTools; +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.MaterialData; +import org.bukkit.scheduler.BukkitRunnable; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + +public class DataHandler { + private static List auctionCategories = Lists.newLinkedList(); + private static long nextCategoryCalculation; + private static List subCategoryItems = null; + + public static void generateTables(Connection connection) throws SQLException { + try (PreparedStatement listings = connection.prepareStatement("CREATE TABLE IF NOT EXISTS listings(id VARCHAR(255) NOT NULL,listed_by VARCHAR(255) NOT NULL,item TEXT NOT NULL,price INT NOT NULL,end_time BIGINT NOT NULL,PRIMARY KEY (id))"); + PreparedStatement expired = connection.prepareStatement("CREATE TABLE IF NOT EXISTS expired(id VARCHAR(255) NOT NULL,player VARCHAR(255) NOT NULL,item TEXT NOT NULL,expire_time BIGINT NOT NULL,PRIMARY KEY (id))")) { + listings.execute(); + expired.execute(); + generateIndex(connection); + } + } + + private static void generateIndex(Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement("CREATE INDEX IDX_EXPIRED ON expired (player)")) { + statement.execute(); + } catch (SQLException e) { + if (e.getErrorCode() != 1061) throw e; + } + } + + public static void loadListings() throws SQLException { + Connection connection = Database.getConnection(); + + try (PreparedStatement load = connection.prepareStatement("SELECT * FROM listings"); + ResultSet set = load.executeQuery()) { + + while(set.next()) { + UUID playerId = UUID.fromString(set.getString("listed_by")); + Listing listing = new Listing(UUID.fromString(set.getString("id")), set.getLong("end_time"), playerId, fromString(set.getString("item")), set.getBigDecimal("price").doubleValue()); + DataHolder.addListing(listing); + DataHolder.addPlayerListing(playerId, listing); + } + + List listings = DataHolder.getListings(); + Collections.sort(listings, new Comparator() { + public int compare(Listing l1, Listing l2) { + return Long.valueOf(l1.getEndTime()).compareTo(l2.getEndTime()); + } + }); + Collections.reverse(listings); + } + + } + + public static List getSubCategoryItems() { + if (subCategoryItems == null) { + subCategoryItems = Lists.newArrayList(ItemUtils.armor); + subCategoryItems.addAll(Arrays.asList(ItemUtils.weapons)); + subCategoryItems.addAll(Arrays.asList(ItemUtils.tools)); + subCategoryItems.addAll(Arrays.asList(Material.BOOK, Material.MOB_SPAWNER, Material.TNT, Material.PAPER)); + } + + return subCategoryItems; + } + + private static boolean isSubCategoryItem(MaterialData data, ItemStack item) { + Material type = data.getItemType(); + boolean contains = getSubCategoryItems().contains(type); + Material dataType = data.getItemType(); + String display = item.getItemMeta().getDisplayName(); + return !contains && dataType == Material.EMERALD && item.getItemMeta().hasDisplayName() && display.startsWith(CC.RedB + "Soul Gem [") ? true : contains; + } + + public static List getAuctionCategories() { + if (nextCategoryCalculation == 0L || nextCategoryCalculation <= System.currentTimeMillis()) { + auctionCategories.clear(); + long start = System.currentTimeMillis(); + Map subCategoryCategories = new HashMap(); + new HashMap(); + Map bookCategories = new HashMap(); + Map matchingItemNames = new HashMap(); + DataHolder.getListings().forEach((item) -> { + if (item.isValid() && !item.isExpired()) { + ItemStack selling = item.getItem().clone(); + String name = ItemUtils.getDisplayName(selling); + if (name == null) { + name = StringUtils.capitaliseAllWords(item.toString().toLowerCase().replace("_", " ")); + } + + if (selling.getEnchantments().size() > 0) { + selling.getEnchantments().forEach((ench, level) -> { + selling.removeEnchantment(ench); + }); + } + + selling.setAmount(1); + MaterialData type = selling.getData(); + Material mat = type.getItemType(); + if (isSubCategoryItem(type, selling)) { + String subCategoryName = CC.White + StringUtils.capitaliseAllWords(mat.name().toLowerCase().replace("_", " ")); + if (name.startsWith(CC.RedB + "Soul Gem") && mat == Material.EMERALD) { + subCategoryName = CC.RedB + "Soul Gems"; + } else if (item.getBookRarity() != null) { + subCategoryName = CC.White + "Enchant Books"; + } + + String finalSubCategoryName = subCategoryName; + String finalSubCategoryName1 = subCategoryName; + AuctionCategory category = (AuctionCategory)subCategoryCategories.computeIfAbsent(mat, (e) -> { + return new AuctionCategory(finalSubCategoryName, ChatColor.stripColor(finalSubCategoryName1), (new ItemBuilder(selling)).setName(finalSubCategoryName1).build(), Lists.newArrayList(), (Listing)null, Lists.newLinkedList(), 10); + }); + if (item.getBookRarity() != null) { + String bookName = item.getBookTierColor() + item.getBookTierName() + " Enchant Books"; + AuctionCategory bookCategory = (AuctionCategory)bookCategories.computeIfAbsent(item.getBookRarity(), (e) -> { + return new AuctionCategory(bookName, ChatColor.stripColor(bookName), (new ItemBuilder(selling)).setName(bookName).build(), Lists.newArrayList(), (Listing)null, Lists.newLinkedList(), item.getBookRarity()); + }); + bookCategory.getCategoryItems().add(item); + if (!category.getSubCategories().contains(bookCategory)) { + category.getSubCategories().add(bookCategory); + } + + return; + } + + category.getCategoryItems().add(item); + return; + } + + String finalName = name; + String finalName1 = name; + ((AuctionCategory)matchingItemNames.computeIfAbsent(name, (e) -> { + return new AuctionCategory(finalName, ChatColor.stripColor(finalName1), selling, Lists.newArrayList(), (Listing)null, Lists.newLinkedList(), 10); + })).getCategoryItems().add(item); + } + + }); + auctionCategories.addAll(matchingItemNames.values()); + auctionCategories.addAll(subCategoryCategories.values()); + auctionCategories.forEach(AuctionCategory::sortCategoryItems); + auctionCategories.forEach(AuctionCategory::sortSubCategories); + Collections.sort(auctionCategories, AuctionCategory::compareTo); + Auction.getPlugin().getLogger().info("Took " + (System.currentTimeMillis() - start) + "ms to calculate auction categories " + auctionCategories.size() + " Listings: " + DataHolder.getListings().size()); + } + + auctionCategories.removeIf((cat) -> { + cat.getCategoryItems().removeIf((item) -> { + return item.isExpired() || !item.isValid(); + }); + return cat.getCategoryItems().isEmpty() && cat.getSubCategories().isEmpty(); + }); + return auctionCategories; + } + + public static void loadUnclaimedListings(UUID playerId) { + Connection connection = Database.getConnection(); + + try { + PreparedStatement statement = connection.prepareStatement("SELECT id, item, expire_time FROM expired WHERE player=?"); + statement.setString(1, playerId.toString()); + ResultSet set = statement.executeQuery(); + + while(set.next()) { + UnclaimedListing uL = new UnclaimedListing(UUID.fromString(set.getString("id")), playerId, fromString(set.getString("item")), set.getLong("expire_time")); + DataHolder.addUnclaimedListing(playerId, uL); + } + + statement.close(); + } catch (SQLException var5) { + var5.printStackTrace(); + } + + } + + public static void saveAllListings(boolean async) { + Connection connection = Database.getConnection(); + + try { + PreparedStatement statement = connection.prepareStatement("REPLACE INTO listings(id, listed_by, item, price, end_time) VALUES (?,?,?,?,?)"); + Iterator var3 = DataHolder.getListings().iterator(); + + while(var3.hasNext()) { + Listing l = (Listing)var3.next(); + statement.setString(1, l.getId().toString()); + statement.setString(2, l.getWhoListed().toString()); + statement.setString(3, toString(l.getItem())); + statement.setBigDecimal(4, new BigDecimal(l.getPrice())); + statement.setLong(5, l.getEndTime()); + statement.addBatch(); + } + + if (async) { + asyncExecuteBatch(statement); + } else { + statement.executeBatch(); + statement.close(); + } + } catch (SQLException var5) { + var5.printStackTrace(); + } + + } + + public static void saveListing(Listing listing, boolean async) { + Connection connection = Database.getConnection(); + + try { + PreparedStatement statement = connection.prepareStatement("REPLACE INTO listings(id, listed_by, item, price, end_time) VALUES (?,?,?,?,?)"); + statement.setString(1, listing.getId().toString()); + statement.setString(2, listing.getWhoListed().toString()); + statement.setString(3, toString(listing.getItem())); + statement.setBigDecimal(4, new BigDecimal(listing.getPrice())); + statement.setLong(5, listing.getEndTime()); + if (async) { + asyncExecute(statement); + } else { + statement.execute(); + statement.close(); + } + } catch (SQLException var4) { + var4.printStackTrace(); + } + + } + + public static void saveUnclaimedListing(UnclaimedListing listing, boolean async) { + Connection connection = Database.getConnection(); + + try { + PreparedStatement statement = connection.prepareStatement("REPLACE INTO expired(id, player, item, expire_time) VALUES (?,?,?,?)"); + statement.setString(1, listing.getId().toString()); + statement.setString(2, listing.getListedBy().toString()); + statement.setString(3, toString(listing.getItem())); + statement.setLong(4, listing.getExpireTime()); + if (async) { + asyncExecute(statement); + } else { + statement.execute(); + statement.close(); + } + } catch (SQLException var4) { + var4.printStackTrace(); + } + + } + + public static void deleteListing(Listing listing, boolean async) { + Connection connection = Database.getConnection(); + + try { + PreparedStatement statement = connection.prepareStatement("DELETE FROM listings WHERE id=?"); + statement.setString(1, listing.getId().toString()); + if (async) { + asyncExecute(statement); + } else { + statement.execute(); + statement.close(); + } + } catch (SQLException var4) { + var4.printStackTrace(); + } + + } + + public static void deleteUnclaimedListing(UnclaimedListing listing, boolean async) { + Connection connection = Database.getConnection(); + + try { + PreparedStatement statement = connection.prepareStatement("DELETE FROM expired WHERE id=?"); + statement.setString(1, listing.getId().toString()); + if (async) { + asyncExecute(statement); + } else { + statement.execute(); + statement.close(); + } + } catch (SQLException var4) { + var4.printStackTrace(); + } + + } + + public static void deleteOverExpiredUnclaimedListing(boolean async) { + Connection connection = Database.getConnection(); + + try { + PreparedStatement statement = connection.prepareStatement("DELETE FROM expired WHERE expire_time listings = new ArrayList(); + private static HashMap> playerListings = new HashMap(); + private static HashMap> unclaimedListings = new HashMap(); + + public static List getListings() { + return listings; + } + + public static void setListings(List list) { + listings = list; + } + + public static void addListing(Listing listing) { + DataHolder.getListings().add(0, listing); + } + + public static void removeListing(Listing listing) { + listing.setValid(false); + listings.remove(listing); + } + + public static HashMap> getPlayerListings() { + return playerListings; + } + + public static void setPlayerListings(HashMap> list) { + playerListings = list; + } + + public static void addPlayerListing(UUID playerId, Listing listing) { + if (!DataHolder.getPlayerListings().containsKey(playerId)) { + ArrayList listings = new ArrayList(); + listings.add(listing); + DataHolder.getPlayerListings().put(playerId, listings); + } else { + playerListings.get(playerId).add(listing); + } + } + + public static void removePlayerListing(UUID playerId, Listing listing) { + if (!DataHolder.getPlayerListings().containsKey(playerId)) { + return; + } + DataHolder.getPlayerListings().get(playerId).remove(listing); + } + + public static HashMap> getUnclaimedListings() { + return unclaimedListings; + } + + public static void setUnclaimedListings(HashMap> uList) { + unclaimedListings = uList; + } + + public static void addUnclaimedListing(UUID playerId, UnclaimedListing listing) { + if (!DataHolder.getUnclaimedListings().containsKey(playerId)) { + ArrayList listings = new ArrayList(); + listings.add(listing); + DataHolder.getUnclaimedListings().put(playerId, listings); + } else { + DataHolder.getUnclaimedListings().get(playerId).add(listing); + } + } + + public static void removeUnclaimedListing(UUID playerId, UnclaimedListing listing) { + if (!DataHolder.getUnclaimedListings().containsKey(playerId)) { + return; + } + DataHolder.getUnclaimedListings().get(playerId).remove(listing); + } + + public static void removeUnclaimedListingStore(UUID playerId) { + DataHolder.getUnclaimedListings().remove(playerId); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/data/Database.java b/Auctionhouse/src/main/java/me/recolance/auction/data/Database.java new file mode 100644 index 0000000..146a644 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/data/Database.java @@ -0,0 +1,70 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.configuration.file.FileConfiguration + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.data; + +import me.recolance.auction.Auction; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.Plugin; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.logging.Level; + +public class Database { + private static Connection connection; + private static Plugin plugin; + private static FileConfiguration config; + + static { + plugin = Auction.plugin; + config = plugin.getConfig(); + } + + public static boolean openDatabaseConnection() { + try { + try { + Class.forName("com.mysql.cj.jdbc.Driver"); + } catch (ClassNotFoundException ignored) { + Class.forName("com.mysql.jdbc.Driver"); + } + connection = DriverManager.getConnection("jdbc:mysql://" + config.getString("sql.host") + ":" + config.getString("sql.port") + "/" + config.getString("sql.database"), config.getString("sql.user"), config.getString("sql.pass")); + DataHandler.generateTables(connection); + return true; + } catch (ClassNotFoundException | SQLException e) { + plugin.getLogger().log(Level.SEVERE, "Could not initialize the auction database", e); + closeConnection(); + return false; + } + } + + public static void closeConnection() { + if (connection == null) return; + try { + connection.close(); + } catch (SQLException e) { + System.out.println("COULD NOT CLOSE CONNECTION!"); + e.printStackTrace(); + } finally { + connection = null; + } + } + + public static Connection getConnection() { + try { + if (connection == null || connection.isClosed()) { + if (!Database.openDatabaseConnection()) { + throw new IllegalStateException("Auction database is unavailable"); + } + } + } catch (SQLException e) { + throw new IllegalStateException("Could not check auction database connection", e); + } + return connection; + } +} diff --git a/Auctionhouse/src/main/java/me/recolance/auction/data/ItemStackDeserializer.java b/Auctionhouse/src/main/java/me/recolance/auction/data/ItemStackDeserializer.java new file mode 100644 index 0000000..8e17bfe --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/data/ItemStackDeserializer.java @@ -0,0 +1,29 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * net.minecraft.util.com.google.gson.JsonDeserializationContext + * net.minecraft.util.com.google.gson.JsonDeserializer + * net.minecraft.util.com.google.gson.JsonElement + * net.minecraft.util.com.google.gson.JsonObject + * net.minecraft.util.com.google.gson.JsonParseException + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + */ +package me.recolance.auction.data; + +import com.google.gson.*; +import me.recolance.auction.util.ItemSerialization; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Type; + +public class ItemStackDeserializer implements JsonDeserializer { + public ItemStack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + JsonObject object; + if (jsonElement instanceof JsonObject && (object = (JsonObject) jsonElement).has("b64")) { + return ItemSerialization.itemFromBase64(object.get("b64").getAsString()); + } + return null; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/data/ItemStackSerializer.java b/Auctionhouse/src/main/java/me/recolance/auction/data/ItemStackSerializer.java new file mode 100644 index 0000000..db215ab --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/data/ItemStackSerializer.java @@ -0,0 +1,29 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * net.minecraft.util.com.google.gson.JsonElement + * net.minecraft.util.com.google.gson.JsonObject + * net.minecraft.util.com.google.gson.JsonSerializationContext + * net.minecraft.util.com.google.gson.JsonSerializer + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + */ +package me.recolance.auction.data; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import me.recolance.auction.util.ItemSerialization; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Type; + +public class ItemStackSerializer implements JsonSerializer { + public JsonElement serialize(ItemStack itemStack, Type type, JsonSerializationContext jsonSerializationContext) { + JsonObject element = new JsonObject(); + element.addProperty("b64", ItemSerialization.itemToStringBase64(itemStack)); + return element; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/data/SafetyToggle.java b/Auctionhouse/src/main/java/me/recolance/auction/data/SafetyToggle.java new file mode 100644 index 0000000..f816374 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/data/SafetyToggle.java @@ -0,0 +1,63 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.configuration.file.YamlConfiguration + * org.bukkit.entity.Player + */ +package me.recolance.auction.data; + +import me.recolance.auction.Auction; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class SafetyToggle { + private List toggles = new ArrayList(); + private List notifytoggles = new ArrayList(); + private File file = new File(Auction.getPlugin().getDataFolder(), "toggles.yml"); + private YamlConfiguration config; + + public SafetyToggle() { + if (!this.file.exists()) { + try { + this.file.createNewFile(); + } catch (Exception e) { + e.printStackTrace(); + } + } + this.config = YamlConfiguration.loadConfiguration((File) this.file); + this.toggles = this.config.getStringList("toggles"); + this.notifytoggles = this.config.getStringList("notify-toggles"); + } + + public boolean isToggled(Player player) { + return this.toggles.contains(player.getUniqueId().toString()); + } + + public boolean isBidMessageToggled(Player player) { + return this.notifytoggles.contains(player.getUniqueId().toString()); + } + + public void saveFile() { + try { + this.config.set("toggles", this.toggles); + this.config.set("notify-toggles", this.notifytoggles); + this.config.save(this.file); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public List getToggles() { + return this.toggles; + } + + public List getNotifytoggles() { + return this.notifytoggles; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/BidListener.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/BidListener.java new file mode 100644 index 0000000..38c9352 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/BidListener.java @@ -0,0 +1,145 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.CC + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.OfflinePlayer + * org.bukkit.entity.Player + * org.bukkit.event.Event$Result + * org.bukkit.event.EventHandler + * org.bukkit.event.EventPriority + * org.bukkit.event.Listener + * org.bukkit.event.me.astropvp.cratekeys.inventory.InventoryClickEvent + * org.bukkit.event.player.AsyncPlayerChatEvent + * org.bukkit.event.player.PlayerInteractEntityEvent + * org.bukkit.event.player.PlayerJoinEvent + * org.bukkit.metadata.MetadataValue + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.menu; + +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.bidmenus.BidMenu; +import me.recolance.auction.menu.bidmenus.ConfirmItemMenu; +import me.recolance.auction.util.Util; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.util.UUID; + +public class BidListener + implements Listener { + private static String auctionBiddingMetadata = "auctionBidding"; + + @EventHandler + public void onItemClick(InventoryClickEvent event) { + if (event.getInventory().getName().equals("Active Bids") || event.getInventory().getName().equals("Enter Auction Package Items") || event.getInventory().getName().endsWith("'s Package Items") || event.getInventory().getName().equals("Auction Bid Collection") || event.getInventory().getName().equals("Confirm Purchase Now") || event.getInventory().getName().equals("Confirm Bid Now") || event.getInventory().getName().startsWith("Buy It Now") || event.getInventory().getName().equals("Confirm First Time Bid") || event.getInventory().getName().equals("Bidding Watchlist")) { + event.setCancelled(true); + event.setResult(Event.Result.DENY); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerInteract(PlayerInteractEntityEvent event) { + Player clicked; + if (event.getRightClicked() instanceof Player && (clicked = (Player) event.getRightClicked()).getName().endsWith("Auctioneer") && clicked.hasMetadata("NPC")) { + event.setCancelled(true); + event.getPlayer().chat("/ah"); + } + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + Auction.getPlugin().getBidManager().setProccessAuctionHouse(true); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onAsyncPLayerChatEvent(AsyncPlayerChatEvent event) { + Player pl = event.getPlayer(); + if (pl.hasMetadata(auctionBiddingMetadata)) { + event.setCancelled(true); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> { + boolean buyout; + UUID uuid = UUID.fromString(((MetadataValue) pl.getMetadata(auctionBiddingMetadata).get(0)).asString()); + if (uuid == null) { + pl.removeMetadata(auctionBiddingMetadata, (Plugin) Auction.getPlugin()); + pl.sendMessage(CC.RedB + "Auction no longer valid!"); + return; + } + String msg = ChatColor.stripColor((String) event.getMessage()); + BidManager bidManager = Auction.getPlugin().getBidManager(); + AuctionBid bid = bidManager.getActiveAuctionBids().get(uuid); + if (bid == null || bid.isExpired()) { + pl.sendMessage((Object) ChatColor.RED + "Auction no longer valid!"); + pl.removeMetadata(auctionBiddingMetadata, (Plugin) Auction.getPlugin()); + return; + } + if (msg.equalsIgnoreCase("cancel")) { + pl.sendMessage((Object) ChatColor.RED + "Auction bid cancelled!"); + pl.removeMetadata(auctionBiddingMetadata, (Plugin) Auction.getPlugin()); + return; + } + Long bidAmount = Util.parseLongOrNull(msg); + if (bidAmount == null) { + try { + bidAmount = Util.getMoneyValue(msg); + } catch (Exception exception) { + // empty catch block + } + } + if (bidAmount == null || bidAmount <= 0L) { + pl.sendMessage(CC.Red + "You must enter a valid bid!"); + return; + } + if (bid.getCurrentBid() >= bidAmount) { + pl.sendMessage((Object) ChatColor.RED + "Your bid must be higher than the current bid!"); + pl.sendMessage(CC.RedB + "Current Bid: $" + CC.Red + Util.formatMoney(bid.getCurrentBid())); + pl.sendMessage((Object) ChatColor.GRAY + "Type '" + CC.Red + "cancel" + CC.Gray + "' to cancel this auction bid!"); + return; + } + if ((double) bid.getCurrentBid() < bid.getStartingBid() && (double) bidAmount.longValue() < bid.getStartingBid()) { + pl.sendMessage(CC.Red + "You must bid atleast the starting bid amount!"); + pl.sendMessage(CC.RedB + "Starting Bid: $" + CC.Red + Util.formatMoney(bid.getStartingBid())); + return; + } + if (!Auction.economy.has((OfflinePlayer) pl, (double) bidAmount.longValue())) { + pl.sendMessage(CC.Red + "You cannot afford that bid!"); + pl.sendMessage(CC.Red + "Current Balance: " + CC.RedB + "$" + CC.Red + Util.formatMoney(Auction.economy.getBalance((OfflinePlayer) pl))); + return; + } + long nextBid = bid.getCurrentBid() + bid.getBidIncrementAmount(); + if (nextBid > bidAmount) { + pl.sendMessage((Object) ChatColor.RED + "Your bid must be higher than the current bid with the bid increment!"); + pl.sendMessage(CC.RedB + "Required Bid: $" + CC.Red + Util.formatMoney(nextBid)); + return; + } + boolean bl = buyout = bid.getBuyoutAmount() > 0.0 && (double) bidAmount.longValue() == bid.getBuyoutAmount(); + if (buyout && (double) bid.getCurrentBid() >= bid.getBuyoutAmount()) { + pl.sendMessage(CC.RedB + "Buyout no longer available for that item!"); + pl.removeMetadata(auctionBiddingMetadata, (Plugin) Auction.getPlugin()); + return; + } + pl.removeMetadata(auctionBiddingMetadata, (Plugin) Auction.getPlugin()); + long finalBidAmount = bidAmount; + new ConfirmItemMenu(pl, "Confirm " + (buyout ? "Purchase" : "Bid") + " Now", finalBidAmount, bid, ConfirmItemMenu.getConfirmCallback(bid, pl, finalBidAmount, buyout), deny -> new BidMenu(pl).openGUI(Auction.getPlugin())).openGUI(Auction.getPlugin()); + }); + } + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/BidManager.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/BidManager.java new file mode 100644 index 0000000..1f955b8 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/BidManager.java @@ -0,0 +1,233 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.CosmicGUI + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.JSONUtils + * com.google.common.collect.Lists + * net.minecraft.util.com.google.common.reflect.TypeToken + * net.minecraft.util.com.google.gson.Gson + * net.minecraft.util.com.google.gson.GsonBuilder + * net.minecraft.util.com.google.gson.JsonDeserializationContext + * net.minecraft.util.com.google.gson.JsonDeserializer + * net.minecraft.util.com.google.gson.JsonElement + * net.minecraft.util.com.google.gson.JsonParseException + * net.minecraft.util.com.google.gson.JsonPrimitive + * net.minecraft.util.com.google.gson.JsonSerializationContext + * net.minecraft.util.com.google.gson.JsonSerializer + * net.minecraft.util.io.netty.util.internal.ConcurrentSet + * org.bukkit.Bukkit + * org.bukkit.Material + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.plugin.Plugin + * org.bukkit.plugin.java.JavaPlugin + * org.bukkit.scheduler.BukkitRunnable + * org.bukkit.scheduler.BukkitTask + */ +package me.recolance.auction.menu; + + +import com.google.common.collect.Lists; +import com.google.common.reflect.TypeToken; +import com.google.gson.*; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.data.ItemStackDeserializer; +import me.recolance.auction.data.ItemStackSerializer; +import me.recolance.auction.menu.bidmenus.BiddableMenu; +import me.recolance.auction.util.ItemSerialization; +import net.crankedpvp.crankedutils.utils.JSONUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +public class BidManager { + private final Map> currentBids = new HashMap>(); + private final HashMap> bidCollectionBin = new HashMap(); + private final Type activeToken = new TypeToken>() { + }.getType(); + private final Type bidBinToken = new TypeToken>>() { + }.getType(); + private final Type watchlistToken = new TypeToken>>() { + }.getType(); + private final Type item = new TypeToken>() { + }.getType(); + private final Gson gson = new GsonBuilder().registerTypeAdapter(Material.class, new JsonSerializer() { + + public JsonElement serialize(Material material, Type type, JsonSerializationContext jsonSerializationContext) { + return new JsonPrimitive(material.name()); + } + }).registerTypeAdapter(Material.class, new JsonDeserializer() { + + public Material deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + if (jsonElement instanceof JsonPrimitive) { + return Material.getMaterial(jsonElement.getAsString()); + } + return null; + } + }).registerTypeAdapter(ItemStack.class, new ItemStackSerializer()).registerTypeAdapter(ItemStack.class, new ItemStackDeserializer()).enableComplexMapKeySerialization().create(); + private ConcurrentHashMap activeAuctionBids = new ConcurrentHashMap(); + private Map> watchlists = new ConcurrentHashMap>(); + private File activeAuctionFile; + private File bidCollectionBinFile; + private File watchlistFile; + private BukkitTask task; + private boolean proccessAuctionHouse = false; + private List loaded; + + public void loadBids(JavaPlugin plugin) throws IOException { + this.activeAuctionFile = JSONUtils.getOrCreateFile(plugin.getDataFolder(), "activeAuctions.json"); + this.bidCollectionBinFile = JSONUtils.getOrCreateFile(plugin.getDataFolder(), "bidCollectionBids.json"); + this.watchlistFile = JSONUtils.getOrCreateFile(plugin.getDataFolder(), "watchlistFile.json"); + HashMap> serializedList = (HashMap) JSONUtils.fromJson(this.bidCollectionBinFile, this.bidBinToken, this.gson); + Set auctions = (Set) JSONUtils.fromJson(this.activeAuctionFile, this.activeToken, this.gson); + + if (auctions != null) { + auctions.forEach(auc -> { + if (auc == null || auc.isExpired()) { + return; + } + auc.deserialize(); + this.activeAuctionBids.put(auc.getBidID(), (AuctionBid) auc); + }); + } + + if (this.activeAuctionBids == null) { + this.activeAuctionBids = new ConcurrentHashMap(); + } + if (serializedList != null) { + serializedList.forEach((id, list) -> this.bidCollectionBin.put(id, list.stream().map(ItemSerialization::itemFromBase64).collect(Collectors.toList()))); + } + + this.watchlists = (Map) JSONUtils.fromJson(this.watchlistFile, this.watchlistToken); + if (this.watchlists == null) { + this.watchlists = new ConcurrentHashMap>(); + } + this.watchlists.forEach((owner, ids) -> ids.stream().filter(aucID -> !this.activeAuctionBids.containsKey(aucID)).forEach(((ConcurrentSet) ids)::remove)); + this.activeAuctionBids.forEach((auctionId, bid) -> { + Set bids = this.currentBids.computeIfAbsent(bid.getSellerUUID(), e -> new HashSet()); + bids.add(bid); + }); + Bukkit.getScheduler().scheduleSyncDelayedTask(Auction.getPlugin(), () -> { + this.proccessAuctionHouse = true; + }, 1200L); + Bukkit.getScheduler().scheduleSyncRepeatingTask(Auction.getPlugin(), () -> { + try { + this.saveBids(true); + } catch (IOException e) { + e.printStackTrace(); + } + }, 1200L, 6000L); + if (Bukkit.getOnlinePlayers().size() > 0) { + this.proccessAuctionHouse = true; + } + } + + public void startBidTimer() { + if (this.task != null) { + this.task.cancel(); + } + this.task = new BukkitRunnable() { + + public void run() { + if (!BidManager.this.proccessAuctionHouse) { + return; + } + for (Map.Entry bidEntry : BidManager.this.activeAuctionBids.entrySet()) { + try { + AuctionBid bid = (AuctionBid) bidEntry.getValue(); + boolean expired = bid.isExpired(); + bid.onTick(); + if (!bid.isExpired() || expired) continue; + BidManager.this.removeAuctionBid(bid); + Bukkit.getLogger().info("Removing expired auction bid " + bid.getSellerName() + " for " + bid.getBidSellDisplayName()); + } catch (Exception e) { + Bukkit.getLogger().info("ERROR onTick inside bid: " + ((AuctionBid) bidEntry.getValue()).getSellerName() + " ( " + ((AuctionBid) bidEntry.getValue()).getBidID() + ") Selling: " + ((AuctionBid) bidEntry.getValue()).getBidSellDisplayName() + " Items: " + ((AuctionBid) bidEntry.getValue()).getSellingItems()); + if (((AuctionBid) bidEntry.getValue()).isExpired()) { + BidManager.this.activeAuctionBids.remove(bidEntry.getKey()); + } + e.printStackTrace(); + } + } + CosmicGUI.activeGUIs.forEach((uuid, gui) -> { + BiddableMenu bidMenu; + if (gui instanceof BiddableMenu && (bidMenu = (BiddableMenu) gui).getPlayer() != null && bidMenu.getPlayer().getOpenInventory() != null && bidMenu.getPlayer().getOpenInventory().getTopInventory() != null && bidMenu.getPlayer().getOpenInventory().getTopInventory().getName().equals(((BiddableMenu) gui).getTitle())) { + gui.redraw(); + } + }); + } + }.runTaskTimer(Auction.getPlugin(), 20L, 20L); + } + + public void removeAuctionBid(AuctionBid bid) { + this.activeAuctionBids.remove(bid.getBidID()); + Set bids = this.currentBids.get(bid.getSellerUUID()); + if (bids != null) { + bids.remove(bid); + } + Bukkit.getLogger().info("Removing bid " + bid.getBidID() + " from " + bid.getSellerName()); + } + + public void saveBids(boolean async) throws IOException { + if (async && Bukkit.isPrimaryThread()) { + ConcurrentHashMap copy = new ConcurrentHashMap(this.activeAuctionBids); + HashMap> binCopy = new HashMap>(this.bidCollectionBin); + CompletableFuture.runAsync(() -> { + try { + this.saveBids(copy, binCopy); + } catch (IOException e) { + e.printStackTrace(); + } + }); + return; + } + this.saveBids(this.activeAuctionBids, this.bidCollectionBin); + } + + public void saveBids(ConcurrentHashMap bids, HashMap> collectionBins) throws IOException { + ArrayList bis = Lists.newArrayList(bids.values()); + HashMap serializedCollectionBins = new HashMap(); + collectionBins.forEach((id, itemList) -> serializedCollectionBins.put(id, itemList.stream().map(ItemSerialization::itemToStringBase64).collect(Collectors.toList()))); + JSONUtils.saveJSONToFile(this.bidCollectionBinFile, serializedCollectionBins, this.bidBinToken, this.gson); + JSONUtils.saveJSONToFile(this.activeAuctionFile, bis, this.activeToken, this.gson); + JSONUtils.saveJSONToFile(this.watchlistFile, this.watchlists, this.watchlistToken, this.gson); + } + + public Map> getCurrentBids() { + return this.currentBids; + } + + public ConcurrentHashMap getActiveAuctionBids() { + return this.activeAuctionBids; + } + + public HashMap> getBidCollectionBin() { + return this.bidCollectionBin; + } + + public Map> getWatchlists() { + return this.watchlists; + } + + public boolean isProccessAuctionHouse() { + return this.proccessAuctionHouse; + } + + public void setProccessAuctionHouse(boolean proccessAuctionHouse) { + this.proccessAuctionHouse = proccessAuctionHouse; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuButton.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuButton.java new file mode 100644 index 0000000..410a9c0 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuButton.java @@ -0,0 +1,167 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * net.minecraft.server.v1_8_R3.ItemStack + * net.minecraft.server.v1_8_R3.NBTTagCompound + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.craftbukkit.v1_8_R3.me.astropvp.cratekeys.inventory.CraftItemStack + * org.bukkit.enchantments.Enchantment + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.me.astropvp.cratekeys.inventory.meta.ItemMeta + * org.bukkit.me.astropvp.cratekeys.inventory.meta.SkullMeta + */ +package me.recolance.auction.menu; + +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class MenuButton { + private static List attributeItems; + + static { + int[] idWithAttribute; + attributeItems = new ArrayList(); + for (int item : idWithAttribute = new int[]{256, 257, 258, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 283, 284, 285, 286, 373, 387, 403, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2267}) { + attributeItems.add(item); + } + } + + private ItemStack item; + + public MenuButton() { + this.item = new ItemStack(Material.AIR, 1); + } + + public MenuButton(ItemStack item) { + this.item = item; + } + + private static boolean typeHasAttribute(int id) { + return attributeItems.contains(id); + } + + public MenuButton name(String name) { + ItemMeta meta = this.item.getItemMeta(); + meta.setDisplayName(ChatColor.translateAlternateColorCodes((char) '&', (String) name)); + this.item.setItemMeta(meta); + return this; + } + + public MenuButton lore(String... lore) { + ItemMeta meta = this.item.getItemMeta(); + ArrayList loreList = new ArrayList(); + if (meta.hasLore()) { + loreList.addAll(meta.getLore()); + } + for (String line : lore) { + loreList.add(ChatColor.translateAlternateColorCodes((char) '&', (String) line)); + } + meta.setLore(loreList); + this.item.setItemMeta(meta); + return this; + } + + public MenuButton lore(List lore) { + ItemMeta meta = this.item.getItemMeta(); + ArrayList loreList = new ArrayList(); + if (meta.hasLore()) { + loreList.addAll(meta.getLore()); + } + for (String line : lore) { + loreList.add(ChatColor.translateAlternateColorCodes((char) '&', (String) line)); + } + meta.setLore(loreList); + this.item.setItemMeta(meta); + return this; + } + + public MenuButton lore(String loreLine) { + ItemMeta meta = this.item.getItemMeta(); + ArrayList loreList = new ArrayList(); + if (meta.hasLore()) { + loreList.addAll(meta.getLore()); + } + loreList.add(ChatColor.translateAlternateColorCodes((char) '&', (String) loreLine)); + meta.setLore(loreList); + this.item.setItemMeta(meta); + return this; + } + + public MenuButton skull(UUID uuid) { + return this.skull(Bukkit.getOfflinePlayer((UUID) uuid).getName()); + } + + public MenuButton skull(String name) { + SkullMeta meta = (SkullMeta) this.item.getItemMeta(); + meta.setOwner(name); + this.item.setItemMeta((ItemMeta) meta); + return this; + } + + public MenuButton amount(int amount) { + this.item.setAmount(amount); + return this; + } + + public MenuButton type(Material material) { + return this.type(material.getId()); + } + + public MenuButton type(int typeId) { + this.item.setTypeId(typeId); + return this; + } + + public MenuButton durability(int durability) { + this.item.setDurability((short) durability); + return this; + } + + public ItemStack get() { + if (MenuButton.typeHasAttribute(this.item.getTypeId())) { + net.minecraft.server.v1_8_R3.ItemStack stack = CraftItemStack.asNMSCopy((ItemStack) this.item); + NBTTagCompound compound = stack.getTag(); + if (compound == null) { + compound = new NBTTagCompound(); + stack.setTag(compound); + compound = stack.getTag(); + } + compound.setInt("HideFlags", 63); + stack.setTag(compound); + this.item = CraftItemStack.asCraftMirror((net.minecraft.server.v1_8_R3.ItemStack) stack); + } + return this.item; + } + + public MenuButton addGlow() { + this.item.addUnsafeEnchantment(Enchantment.DURABILITY, -1); + net.minecraft.server.v1_8_R3.ItemStack stack = CraftItemStack.asNMSCopy((ItemStack) this.item); + NBTTagCompound compound = stack.getTag(); + if (compound == null) { + compound = new NBTTagCompound(); + stack.setTag(compound); + compound = stack.getTag(); + } + if (!compound.hasKey("HideFlags")) { + compound.setInt("HideFlags", 1); + } + stack.setTag(compound); + this.item = CraftItemStack.asCraftMirror((net.minecraft.server.v1_8_R3.ItemStack) stack); + return this; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuController.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuController.java new file mode 100644 index 0000000..a37c512 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuController.java @@ -0,0 +1,343 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * net.milkbowl.vault.economy.Economy + * org.bukkit.Bukkit + * org.bukkit.Material + * org.bukkit.entity.Player + * org.bukkit.event.Event$Result + * org.bukkit.event.EventHandler + * org.bukkit.event.EventPriority + * org.bukkit.event.Listener + * org.bukkit.event.inventory.ClickType + * org.bukkit.event.inventory.InventoryClickEvent + * org.bukkit.event.inventory.InventoryCloseEvent + * org.bukkit.event.inventory.InventoryDragEvent + * org.bukkit.inventory.Inventory + * org.bukkit.inventory.ItemStack + * org.bukkit.plugin.Plugin + * org.bukkit.scheduler.BukkitRunnable + */ +package me.recolance.auction.menu; + +import me.recolance.auction.Auction; +import me.recolance.auction.auction.Listing; +import me.recolance.auction.auction.UnclaimedListing; +import me.recolance.auction.controller.Controller; +import me.recolance.auction.data.DataHolder; +import me.recolance.auction.menu.bidmenus.BidMenu; +import me.recolance.auction.menu.categories.CategoryMainMenu; +import me.recolance.auction.util.Util; +import net.crankedpvp.crankedutils.utils.CC; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +public class MenuController + implements Listener { + private static HashMap closeSecurity = new HashMap(); + private static HashMap timer = new HashMap(); + private static Economy economy = Auction.economy; + + @EventHandler(priority = EventPriority.LOWEST) + public void onClick(InventoryClickEvent event) { + ItemStack item; + Player player = (Player) event.getWhoClicked(); + Inventory inventory = event.getInventory(); + if (closeSecurity.containsKey(player.getUniqueId()) && closeSecurity.get(player.getUniqueId()) == inventory) { + event.setCancelled(true); + return; + } + if (!MenuHelper.isViewing(player)) { + return; + } + if (!timer.containsKey(player.getUniqueId())) { + timer.put(player.getUniqueId(), System.currentTimeMillis()); + } else if (System.currentTimeMillis() - timer.get(player.getUniqueId()) < 350L) { + event.setCancelled(true); + return; + } + timer.put(player.getUniqueId(), System.currentTimeMillis()); + if (event.getCurrentItem() != null && !event.getClickedInventory().equals((Object) player.getOpenInventory().getTopInventory())) { + event.setCancelled(true); + event.setResult(Event.Result.DENY); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), ((Player) player)::closeInventory, 1L); + Util.message(player, "&e&l(!) &eTo list an item for sale on the &6/ah&e use &6/ah sell &e, to list an item up for auction use &6/ah startbid&e."); + return; + } + int slot = event.getRawSlot(); + if (MenuUtil.isCancellableClick(inventory, slot, event.getClick())) { + event.setCancelled(true); + event.setResult(Event.Result.DENY); + player.updateInventory(); + } + if ((item = event.getCurrentItem()) == null || item.getType() == Material.AIR) { + return; + } + switch (MenuHelper.getViewing(player)) { + case AUCTION: { + if (slot < 45 && slot >= 0) { + List vL = MenuHelper.getViewingListings(player); + if (vL == null) { + Bukkit.getLogger().info("[AuctionHouse] Player " + player.getName() + " has a null vL object, closing inventory."); + player.closeInventory(); + return; + } + Listing l = vL.get(slot); + if (event.getClick() == ClickType.SHIFT_RIGHT && player.hasPermission("auction.admin.expire")) { + Controller.adminCancel(player, l); + MenuRenderer.renderAuctionPage(MenuHelper.getViewingPage(player), inventory, player); + break; + } + if (!DataHolder.getListings().contains(l)) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "This item is no longer available."); + break; + } + if (l.getWhoListed().equals(player.getUniqueId())) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "To cancel your auction, click the diamond."); + break; + } + if (!Util.hasInventorySpace(player)) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "You do not have enough inventory space!"); + break; + } + if (!economy.has(Bukkit.getOfflinePlayer((UUID) player.getUniqueId()), (double) l.getPrice())) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "You cannot afford this item."); + break; + } + player.closeInventory(); + Bukkit.getScheduler().runTaskLater((Plugin) Auction.getPlugin(), () -> MenuRenderer.purchaseConfirmation(player, l), 1L); + break; + } + if (slot == 45) { + player.closeInventory(); + MenuRenderer.selling(player); + break; + } + if (slot == 46) { + player.closeInventory(); + MenuRenderer.expired(player); + break; + } + if (slot == 47) { + if (item.getType() == Material.ENDER_CHEST) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> { + player.closeInventory(); + player.performCommand("ah collect"); + }, 1L); + break; + } + if (item.getType() != Material.BOOK_AND_QUILL) break; + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> { + player.closeInventory(); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> new BidMenu(player).openGUI(Auction.getPlugin()), 1L); + }, 1L); + break; + } + if (slot == 48 && MenuHelper.getViewingListings(player).size() != 0) { + MenuRenderer.renderAuctionPage(MenuHelper.getViewingPage(player) - 1, inventory, player); + break; + } + if (slot == 49) { + int page = MenuHelper.getViewingPage(player); + if (page == -1) break; + MenuRenderer.renderAuctionPage(page, inventory, player); + MenuUtil.displayMenuInfo(slot, inventory, item, "All auctions have been refreshed."); + break; + } + if (slot == 50) { + MenuRenderer.renderAuctionPage(MenuHelper.getViewingPage(player) + 1, inventory, player); + break; + } + if (slot != 51) break; + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> { + player.closeInventory(); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> new CategoryMainMenu(player).openGUI(Auction.getPlugin()), 1L); + }, 1L); + break; + } + case PURCHASE_CONFIRMATION: { + boolean viewingCategories = player.hasMetadata("category_view"); + if (slot < 4) { + Listing l = MenuHelper.getPurchasing(player); + if (!DataHolder.getListings().contains(l)) { + if (viewingCategories) { + player.closeInventory(); + player.sendMessage(CC.RedB + "(!) " + CC.Red + "Item is no longer available!"); + Bukkit.getScheduler().runTaskLater((Plugin) Auction.getPlugin(), () -> new CategoryMainMenu(player).openGUI(Auction.getPlugin()), 1L); + return; + } + MenuUtil.displayMenuInvalidity(slot, inventory, item, "This item is no longer available."); + break; + } + if (l.getWhoListed().equals(player.getUniqueId())) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "To cancel your auction, click the diamond."); + break; + } + if (!Util.hasInventorySpace(player)) { + if (viewingCategories) { + player.closeInventory(); + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You dont have enough inventory space to purchase that item!"); + Bukkit.getScheduler().runTaskLater((Plugin) Auction.getPlugin(), () -> new CategoryMainMenu(player).openGUI(Auction.getPlugin()), 1L); + return; + } + MenuUtil.displayMenuInvalidity(slot, inventory, item, "You do not have enough inventory space!"); + break; + } + if (!economy.has(Bukkit.getOfflinePlayer((UUID) player.getUniqueId()), (double) l.getPrice())) { + if (viewingCategories) { + player.closeInventory(); + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You cannot afford this item."); + Bukkit.getScheduler().runTaskLater((Plugin) Auction.getPlugin(), () -> new CategoryMainMenu(player).openGUI(Auction.getPlugin()), 1L); + return; + } + MenuUtil.displayMenuInvalidity(slot, inventory, item, "You cannot afford this item."); + break; + } + Controller.purchase(player, l); + player.closeInventory(); + MenuRenderer.openAuction(player); + break; + } + if (slot <= 4 || slot >= 9) break; + player.closeInventory(); + if (viewingCategories) { + Bukkit.getScheduler().runTaskLater((Plugin) Auction.getPlugin(), () -> new CategoryMainMenu(player).openGUI(Auction.getPlugin()), 1L); + return; + } + MenuRenderer.openAuction(player); + break; + } + case SELLING: { + if (slot < 45) { + List listings = MenuHelper.getViewingListings(player); + Listing listing = listings.get(slot); + if (!DataHolder.getListings().contains(listing)) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "This item is no longer available."); + break; + } + Controller.cancel(player, listing); + MenuRenderer.renderSelling(player, inventory); + break; + } + if (slot != 45) break; + player.closeInventory(); + MenuRenderer.openAuction(player); + break; + } + case EXPIRED: { + if (slot < 45) { + List listings = MenuHelper.getUnclaimedViewing(player); + UnclaimedListing listing = listings.get(slot); + if (!DataHolder.getUnclaimedListings().containsKey(player.getUniqueId()) || !DataHolder.getUnclaimedListings().get(player.getUniqueId()).contains(listing)) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "This Item No Longer Exists"); + break; + } + if (!Util.hasInventorySpace(player)) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "You do not have enough inventory space!"); + break; + } + Controller.claim(player, listing); + MenuRenderer.renderExpired(1, inventory, player); + break; + } + if (slot == 45) { + player.closeInventory(); + MenuRenderer.openAuction(player); + break; + } + if (slot == 48) { + MenuRenderer.renderExpired(MenuHelper.getViewingPage(player) - 1, inventory, player); + break; + } + if (slot == 49) { + if (!DataHolder.getUnclaimedListings().containsKey(player.getUniqueId())) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "Your Collection Bin is empty!"); + break; + } + if (!Util.hasInventorySpace(player)) { + MenuUtil.displayMenuInvalidity(slot, inventory, item, "You do not have enough inventory space!"); + break; + } + Controller.claimAll(player); + MenuRenderer.renderExpired(1, inventory, player); + break; + } + if (slot != 50) break; + MenuRenderer.renderExpired(MenuHelper.getViewingPage(player) + 1, inventory, player); + } + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onClose(InventoryCloseEvent event) { + final Player player = (Player) event.getPlayer(); + if (!MenuHelper.isViewing(player)) { + return; + } + switch (MenuHelper.getViewing(player)) { + case AUCTION: { + MenuHelper.removeViewingListings(player); + MenuHelper.removeViewingPage(player); + break; + } + case PURCHASE_CONFIRMATION: { + MenuHelper.removePurchasing(player); + break; + } + case SELLING: { + MenuHelper.removeViewingListings(player); + break; + } + case EXPIRED: { + MenuHelper.removeViewingPage(player); + MenuHelper.removeViewingUnclaimed(player); + } + } + MenuHelper.removeViewing(player); + closeSecurity.put(player.getUniqueId(), event.getInventory()); + new BukkitRunnable() { + + public void run() { + closeSecurity.remove(player.getUniqueId()); + } + }.runTaskLater((Plugin) Auction.plugin, 2L); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onDrag(InventoryDragEvent event) { + Player player = (Player) event.getWhoClicked(); + if (!MenuHelper.isViewing(player)) { + return; + } + Inventory inventory = event.getInventory(); + Iterator iterator = event.getRawSlots().iterator(); + while (iterator.hasNext()) { + int slot = (Integer) iterator.next(); + if (slot >= inventory.getSize()) continue; + event.setCancelled(true); + break; + } + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuHelper.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuHelper.java new file mode 100644 index 0000000..42f2f96 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuHelper.java @@ -0,0 +1,96 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.entity.Player + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.menu; + +import me.recolance.auction.Auction; +import me.recolance.auction.auction.Listing; +import me.recolance.auction.auction.UnclaimedListing; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +public class MenuHelper { + public static HashMap viewingPage = new HashMap(); + public static HashMap> viewingListings = new HashMap(); + public static HashMap purchasing = new HashMap(); + public static HashMap> viewingUnclaimed = new HashMap(); + private static final HashMap currentlyViewing = new HashMap(); + + public static boolean isViewing(Player player) { + return currentlyViewing.containsKey(player.getUniqueId()); + } + + public static MenuType getViewing(Player player) { + return currentlyViewing.get(player.getUniqueId()); + } + + public static void setViewing(Player player, MenuType menuType) { + currentlyViewing.put(player.getUniqueId(), menuType); + } + + public static void removeViewing(Player player) { + currentlyViewing.remove(player.getUniqueId()); + } + + public static int getViewingPage(Player player) { + if (!viewingPage.containsKey(player)) { + player.closeInventory(); + return -1; + } + return viewingPage.get(player); + } + + public static void setViewingPage(Player player, int page) { + viewingPage.put(player, page); + } + + public static void removeViewingPage(Player player) { + viewingPage.remove(player); + } + + public static List getViewingListings(Player player) { + return viewingListings.get(player); + } + + public static void setViewingListings(Player player, List list) { + viewingListings.put(player, list); + } + + public static void removeViewingListings(Player player) { + viewingListings.remove(player); + } + + public static Listing getPurchasing(Player player) { + return purchasing.get(player); + } + + public static void setPurchasing(Player player, Listing list) { + purchasing.put(player, list); + } + + public static void removePurchasing(Player player) { + purchasing.remove(player); + player.removeMetadata("category_view", Auction.getPlugin()); + } + + public static List getUnclaimedViewing(Player player) { + return viewingUnclaimed.get(player); + } + + public static void setViewingUnclaimed(Player player, List list) { + viewingUnclaimed.put(player, list); + } + + public static void removeViewingUnclaimed(Player player) { + viewingUnclaimed.remove(player); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuRenderer.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuRenderer.java new file mode 100644 index 0000000..f9318b6 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuRenderer.java @@ -0,0 +1,308 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.ItemBuilder + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.NumberUtils + * com.google.common.collect.Lists + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.Sound + * org.bukkit.entity.Player + * org.bukkit.inventory.Inventory + * org.bukkit.inventory.ItemStack + * org.bukkit.metadata.FixedMetadataValue + * org.bukkit.metadata.MetadataValue + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.menu; + + +import com.google.common.collect.Lists; +import me.recolance.auction.Auction; +import me.recolance.auction.auction.Listing; +import me.recolance.auction.auction.UnclaimedListing; +import me.recolance.auction.controller.Controller; +import me.recolance.auction.data.DataHolder; +import me.recolance.auction.util.AuctionUtil; +import me.recolance.auction.util.Item; +import me.recolance.auction.util.Util; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.util.*; + +public class MenuRenderer { + private static Plugin plugin = Auction.plugin; + private static MenuButton pP; + private static MenuButton rP; + private static MenuButton nP; + private static MenuButton hTS; + private static MenuButton wITP; + private static String auctionInventoryName; + private static String itemsSellingName; + private static String expiredItemName; + private static List itemsSellingLore; + private static List expirationLore; + + public static void loadMenuItems() { + auctionInventoryName = ChatColor.translateAlternateColorCodes((char) '&', (String) plugin.getConfig().getString("menuText.menuName")); + itemsSellingName = plugin.getConfig().getString("menuText.itemsYoureSelling.name"); + itemsSellingLore = plugin.getConfig().getStringList("menuText.itemsYoureSelling.lore"); + expiredItemName = plugin.getConfig().getString("menuText.collectExpired.name"); + expirationLore = plugin.getConfig().getStringList("menuText.collectExpired.lore"); + String pPN = plugin.getConfig().getString("menuText.previous.name"); + List pPL = plugin.getConfig().getStringList("menuText.previous.lore"); + pP = new MenuButton().type(Material.PAPER).name(pPN); + for (String lore : pPL) { + pP.lore(lore); + } + String rPN = plugin.getConfig().getString("menuText.refresh.name"); + List rPL = plugin.getConfig().getStringList("menuText.refresh.lore"); + rP = new MenuButton().type(Material.CHEST).name(rPN); + for (String lore : rPL) { + rP.lore(lore); + } + String nPN = plugin.getConfig().getString("menuText.next.name"); + List nPL = plugin.getConfig().getStringList("menuText.next.lore"); + nP = new MenuButton().type(Material.PAPER).name(nPN); + for (String lore : nPL) { + nP.lore(lore); + } + String hTSN = plugin.getConfig().getString("menuText.howToSell.name"); + List hTSL = plugin.getConfig().getStringList("menuText.howToSell.lore"); + hTS = new MenuButton().type(Material.GOLD_INGOT).name(hTSN); + for (String lore : hTSL) { + hTS.lore(lore); + } + hTS.lore("", CC.Gray + "To list an item in a Bid Auction use", CC.Yellow + "/ah startbid ", "", CC.Gray + "To toggle alerts when you are outbid", CC.Gray + "use " + CC.Yellow + "/ah aucnotify"); + String wITPN = plugin.getConfig().getString("menuText.bookButton.name"); + ArrayList wITPL = Lists.newArrayList("&7This is the auction house, here you can", "&7list items for sale and purchase items", "&7that others have listed for sale.", "", "&7The auction is also a great way to make", "&7money by selling farmable items other", "&7players may be interested in buying.", "", "&7All sell listings last for a max of &e15 minutes", "&7unsold items are sent to your collection bin.", "", "&7You can also list items up for auction", "&7where players can outbid each other to", "&7be the highest bidder using &e/bids&7.", "", "&7For more help, use &e/ah help!"); + wITP = new MenuButton().type(Material.BOOK).name(wITPN); + for (String lore : wITPL) { + wITP.lore(lore.replace("15 minute", "60 minute")); + } + } + + public static void openAuction(Player player) { + if (pP == null) { + MenuRenderer.loadMenuItems(); + } + Inventory inventory = Bukkit.createInventory(null, (int) 54, (String) auctionInventoryName); + MenuRenderer.renderAuctionPage(1, inventory, player); + MenuButton iYS = new MenuButton().type(Material.DIAMOND).name(itemsSellingName); + for (String string : itemsSellingLore) { + iYS.lore(string.replace("%selling%", String.valueOf(AuctionUtil.getCurrentlySellingAmount(player)))); + } + MenuButton cEI = new MenuButton().type(Material.ENDER_CHEST).name(expiredItemName); + for (String lore : expirationLore) { + cEI.lore(lore.replace("%expired%", String.valueOf(AuctionUtil.getItemsToCollectAmount(player)))); + } + inventory.setItem(45, iYS.get()); + inventory.setItem(46, cEI.get()); + BidManager bidManager = Auction.getPlugin().getBidManager(); + List claimMenu = bidManager.getBidCollectionBin().get(player.getUniqueId()); + if (claimMenu != null && !claimMenu.isEmpty()) { + inventory.setItem(47, new ItemBuilder(Material.ENDER_CHEST).setName(CC.YellowB + "Bid Collection Bin").addLore(CC.Gray + "Click to view all items won from bid auctions", CC.Gray + "or expired bids you attempted to sell.", "", CC.YellowB + claimMenu.size() + " Item(s)").build()); + } else { + inventory.setItem(47, new ItemBuilder(Material.BOOK_AND_QUILL).setName(CC.YellowB + "Auction Bids").addLore(CC.Gray + "Click here to view all current Auction Biddings!", "", CC.YellowB + bidManager.getActiveAuctionBids().size() + " Auction(s)").build()); + } + inventory.setItem(48, pP.get()); + inventory.setItem(49, rP.get()); + inventory.setItem(50, nP.get()); + inventory.setItem(51, new ItemBuilder(Material.STORAGE_MINECART, CC.YellowB + "Category View", CC.Gray + "Click to view all current", CC.Gray + "auction item categories!").build()); + inventory.setItem(52, hTS.get()); + inventory.setItem(53, wITP.get()); + player.openInventory(inventory); + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 1.0f, 2.4f); + MenuHelper.setViewing(player, MenuType.AUCTION); + } + + public static void renderAuctionPage(int page, Inventory inventory, Player player) { + int sI; + int eI; + int displaying; + int lS; + List listings = DataHolder.getListings(); + if (page < 1) { + lS = listings.size(); + page = lS / 45; + if (lS % 45 > 0) { + ++page; + } + } + if ((displaying = (eI = (sI = (page - 1) * 45) + 44 >= (lS = listings.size()) ? lS - 1 : page * 45 - 1) - sI + 1) < 1 && page != 1) { + MenuRenderer.renderAuctionPage(1, inventory, player); + return; + } + int slot = 0; + for (int i = 0; i < 45; ++i) { + inventory.setItem(i, null); + } + ArrayList vL = new ArrayList(); + for (int i = sI; i <= eI; ++i) { + Listing listing = listings.get(i); + inventory.setItem(slot, listing.getMenuDisplayItem()); + ++slot; + vL.add(listing); + } + MenuHelper.setViewingPage(player, page); + MenuHelper.setViewingListings(player, vL); + } + + public static void purchaseConfirmation(Player player, Listing listing) { + MenuRenderer.purchaseConfirmation(player, listing, false); + } + + public static void purchaseConfirmation(Player player, Listing listing, boolean categoryViewing) { + Inventory inventory = Bukkit.createInventory(null, (int) 9, (String) "Purchase Item: Are You Sure?"); + ItemStack yes = new MenuButton().type(Material.STAINED_GLASS_PANE).durability(5).name("&a&lConfirm Purchase").lore("&7Click to confirm purchase.").get(); + for (int i = 0; i < 4; ++i) { + inventory.setItem(i, yes); + } + ItemStack no = new MenuButton().type(Material.STAINED_GLASS_PANE).durability(14).name("&c&lCancel Purchase").lore("&7Click to cancel purchase.").get(); + for (int i = 5; i < 9; ++i) { + inventory.setItem(i, no); + } + ItemStack item = new Item(new ItemStack(listing.getItem())).addLore("", "&6Price: &e$" + listing.getPrettyPrice(), "&6Seller: &e" + Bukkit.getOfflinePlayer((UUID) listing.getWhoListed()).getName()).get(); + inventory.setItem(4, item); + player.openInventory(inventory); + MenuHelper.setPurchasing(player, listing); + MenuHelper.setViewing(player, MenuType.PURCHASE_CONFIRMATION); + if (categoryViewing) { + player.setMetadata("category_view", (MetadataValue) new FixedMetadataValue((Plugin) Auction.getPlugin(), (Object) "")); + } + } + + public static void selling(Player player) { + Inventory inventory = Bukkit.createInventory(null, (int) 54, (String) "Your Current Listings"); + MenuRenderer.renderSelling(player, inventory); + MenuButton back = new MenuButton().type(Material.CHEST).name("&e&lReturn to Auction House").lore("&7Click here to return to the", "&7auction house main menu."); + MenuButton wITP = new MenuButton().type(Material.BOOK).name("&e&lTutorial").lore("&7These are your current listings, all of", "&7the items you currently have listed on", "&7the auction house are displayed here.", "", "&7You can cancel and view your listing's", "&7expire time here."); + inventory.setItem(45, back.get()); + inventory.setItem(53, wITP.get()); + player.openInventory(inventory); + MenuHelper.setViewing(player, MenuType.SELLING); + } + + public static void renderSelling(Player player, Inventory inventory) { + for (int i = 0; i < 45; ++i) { + inventory.setItem(i, null); + } + List playerListings = DataHolder.getPlayerListings().get(player.getUniqueId()); + if (playerListings == null || playerListings.isEmpty()) { + return; + } + if (playerListings.size() > 1) { + Collections.sort(playerListings, new Comparator() { + + @Override + public int compare(Listing l1, Listing l2) { + return Long.valueOf(l1.getEndTime()).compareTo(l2.getEndTime()); + } + }); + } + ArrayList vL = new ArrayList(); + int slot = 0; + for (Listing listing : playerListings) { + String perData = listing.getExpInBottle() > 0 ? CC.Gray + " ($" + NumberUtils.formatMoney((double) listing.getExpPerDollar()) + " / xp)" : ""; + double perItem = listing.getPricePerItem(); + if (perItem != (double) listing.getPrice() && perItem > 0.0) { + perData = " ($" + NumberUtils.formatMoney((double) perItem) + " / item)"; + } + ItemStack item = new Item(new ItemStack(listing.getItem())).addLore("&7-------------------------", "&c&lClick item to cancel auction.", "", "&6Price: &e$" + listing.getPrettyPrice() + perData, "&6Expire: &e" + Util.getRemainingTimeString(System.currentTimeMillis(), listing.getEndTime() - System.currentTimeMillis()), "&7-------------------------").get(); + vL.add(listing); + inventory.setItem(slot, item); + ++slot; + } + MenuHelper.setViewingListings(player, vL); + } + + public static void expired(Player player) { + Inventory inventory = Bukkit.createInventory(null, (int) 54, (String) "Cancelled / Expired Listings"); + MenuRenderer.renderExpired(1, inventory, player); + MenuButton back = new MenuButton().type(Material.CHEST).name("&e&lReturn to Auction House").lore("&7Click here to return to the", "&7auction house main menu."); + MenuButton previous = new MenuButton().type(Material.PAPER).name("&e&l<- Previous Page"); + MenuButton all = new MenuButton().type(Material.ENDER_CHEST).name("&e&lClaim All").lore("&7Click here to claim all", "&7your Collection Bin items."); + MenuButton next = new MenuButton().type(Material.PAPER).name("&e&lNext Page ->"); + MenuButton wITP = new MenuButton().type(Material.BOOK).name("&e&lTutorial").lore("&7This page houses all of your cancelled and", "&7expired items, when a listings is cancelled", "&7or expires you will be able to return that", "&7item back to you from this menu.", "", "&7Just click on the item and if you have enough", "&7inventory space you will recieve the item."); + inventory.setItem(45, back.get()); + inventory.setItem(48, previous.get()); + inventory.setItem(49, all.get()); + inventory.setItem(50, next.get()); + inventory.setItem(53, wITP.get()); + player.openInventory(inventory); + MenuHelper.setViewing(player, MenuType.EXPIRED); + } + + public static void renderExpired(int page, Inventory inventory, Player player) { + int sI; + int eI; + int displaying; + int lS; + List listings = DataHolder.getUnclaimedListings().get(player.getUniqueId()); + if (listings == null) { + listings = new ArrayList(); + } + for (int i = 0; i < 45; ++i) { + inventory.setItem(i, null); + } + if (page < 1) { + lS = listings.size(); + page = lS / 45; + if (lS % 45 > 0) { + ++page; + } + } + MenuHelper.setViewingPage(player, page); + if (listings.isEmpty()) { + return; + } + if (listings.size() > 1) { + Collections.sort(listings, new Comparator() { + + @Override + public int compare(UnclaimedListing l1, UnclaimedListing l2) { + return Long.valueOf(l1.getExpireTime()).compareTo(l2.getExpireTime()); + } + }); + Collections.reverse(listings); + } + if ((displaying = (eI = (sI = (page - 1) * 45) + 44 >= (lS = listings.size()) ? lS - 1 : page * 45 - 1) - sI + 1) < 1 && page != 1) { + MenuRenderer.renderExpired(1, inventory, player); + return; + } + ArrayList vL = new ArrayList(); + ArrayList rL = new ArrayList(); + int slot = 0; + for (int i = sI; i <= eI; ++i) { + UnclaimedListing listing = listings.get(i); + if (listing.getExpireTime() < System.currentTimeMillis()) { + rL.add(listing); + continue; + } + ItemStack item = new Item(new ItemStack(listing.getItem())).addLore("&7-------------------------", "&e&lClick here to claim item.", "", "&6Item Deletion: &e" + Util.getRemainingTimeString(System.currentTimeMillis(), listing.getExpireTime() - System.currentTimeMillis()), "&7-------------------------").get(); + inventory.setItem(slot, item); + ++slot; + vL.add(listing); + } + for (UnclaimedListing l : rL) { + Controller.expireUnclaimed(l); + } + MenuHelper.setViewingUnclaimed(player, vL); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuType.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuType.java new file mode 100644 index 0000000..67f4648 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuType.java @@ -0,0 +1,13 @@ +/* + * Decompiled with CFR 0.150. + */ +package me.recolance.auction.menu; + +public enum MenuType { + AUCTION, + PURCHASE_CONFIRMATION, + SELLING, + EXPIRED; + +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuUtil.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuUtil.java new file mode 100644 index 0000000..3c30e84 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/MenuUtil.java @@ -0,0 +1,65 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.Material + * org.bukkit.event.me.astropvp.cratekeys.inventory.ClickType + * org.bukkit.me.astropvp.cratekeys.inventory.Inventory + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.plugin.Plugin + * org.bukkit.scheduler.BukkitRunnable + */ +package me.recolance.auction.menu; + +import me.recolance.auction.Auction; +import me.recolance.auction.util.Util; +import org.bukkit.Material; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; + +public class MenuUtil { + public static boolean isCancellableClick(Inventory inventory, int slot, ClickType click) { + if (slot < inventory.getSize()) { + return true; + } + return click != ClickType.LEFT && click != ClickType.RIGHT; + } + + public static void displayMenuInvalidity(final int slot, final Inventory inventory, final ItemStack originalItem, String message) { + message = Util.setStringColors(message); + if (originalItem.getType() == Material.STAINED_GLASS_PANE) { + return; + } + inventory.setItem(slot, new MenuButton().type(Material.STAINED_GLASS_PANE).durability(14).name("&c" + message).get()); + new BukkitRunnable() { + + public void run() { + ItemStack item = inventory.getItem(slot); + if (item != null && inventory.getItem(slot).getType() == Material.STAINED_GLASS_PANE) { + inventory.setItem(slot, originalItem); + } + } + }.runTaskLater((Plugin) Auction.plugin, 20L); + } + + public static void displayMenuInfo(final int slot, final Inventory inventory, final ItemStack originalItem, String message) { + message = Util.setStringColors(message); + if (originalItem.getType() == Material.STAINED_GLASS_PANE) { + return; + } + inventory.setItem(slot, new MenuButton().type(Material.STAINED_GLASS_PANE).durability(4).name("&e" + message).get()); + new BukkitRunnable() { + + public void run() { + ItemStack item = inventory.getItem(slot); + if (item != null && inventory.getItem(slot).getType() == Material.STAINED_GLASS_PANE) { + inventory.setItem(slot, originalItem); + } + } + }.runTaskLater((Plugin) Auction.plugin, 20L); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/AuctionGUI.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/AuctionGUI.java new file mode 100644 index 0000000..64b6d3d --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/AuctionGUI.java @@ -0,0 +1,36 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.CosmicGUI + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.CC + * org.bukkit.entity.Player + */ +package me.recolance.auction.menu.bidmenus; + + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import org.bukkit.entity.Player; + +public abstract class AuctionGUI + extends CosmicGUI { + private long lastClicked; + + public AuctionGUI(Player player, String title, int size) { + super(player, title, size); + } + + public boolean canClick() { + if (this.lastClicked <= System.currentTimeMillis()) { + return true; + } + this.player.sendMessage(CC.RedB + "(!) " + CC.Red + "Please wait before clicking again!"); + return false; + } + + public void click() { + this.lastClicked = System.currentTimeMillis() + 500L; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/AuctionPackageMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/AuctionPackageMenu.java new file mode 100644 index 0000000..d736c44 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/AuctionPackageMenu.java @@ -0,0 +1,232 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.compat.ASound + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.InventoryItem + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.ItemBuilder + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.PlayerUtil + * com.google.common.collect.Lists + * net.minecraft.util.org.apache.commons.lang3.tuple.ImmutablePair + * net.minecraft.util.org.apache.commons.lang3.tuple.Pair + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.DyeColor + * org.bukkit.Material + * org.bukkit.Sound + * org.bukkit.entity.Player + * org.bukkit.event.inventory.ClickType + * org.bukkit.event.inventory.InventoryClickEvent + * org.bukkit.inventory.ItemStack + */ +package me.recolance.auction.menu.bidmenus; + + +import com.google.common.collect.Lists; +import me.recolance.auction.command.CommandHandler; +import me.recolance.auction.util.ItemUtils; +import me.recolance.auction.util.Util; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +public class AuctionPackageMenu + extends AuctionGUI { + public long bidLength5 = TimeUnit.MINUTES.toSeconds(5L); + public long bidLength10 = TimeUnit.MINUTES.toSeconds(10L); + public long bidLength15 = TimeUnit.MINUTES.toSeconds(15L); + public long bidLength30 = TimeUnit.MINUTES.toSeconds(30L); + public int bidLength = (int) TimeUnit.MINUTES.toSeconds(15L); + private List toReturn = Lists.newArrayList(); + private long startingBid; + private long maxBid; + private long buyoutPrice; + private Consumer, Integer>> callback; + private boolean confirmed = false; + + public AuctionPackageMenu(Player player, long startingBid, long incrementAmount, long buyoutPrice, ItemStack selling, Consumer, Integer>> successCallback) { + super(player, "Enter Auction Package Items", 54); + this.startingBid = startingBid; + this.maxBid = incrementAmount; + this.buyoutPrice = buyoutPrice; + this.callback = successCallback; + if (selling != null && selling.getType() != Material.AIR && CommandHandler.canSellItem(selling)) { + player.getInventory().removeItem(new ItemStack[]{selling}); + this.toReturn.add(selling); + } + } + + public void onInventoryClose() { + super.onInventoryClose(); + if (!this.confirmed) { + this.player.sendMessage(CC.Red + "Auction bid " + CC.RedB + "CANCELLED"); + if (this.toReturn.isEmpty()) { + this.confirmed = true; + return; + } + this.player.sendMessage(CC.Gray + "Your items have been returned to you."); + this.confirmed = true; + for (ItemStack retr : this.toReturn) { + PlayerUtils.giveOrDropProtectedItem((Player) this.player, (ItemStack) retr, (int) 60); + } + this.toReturn.clear(); + } + } + + public void redraw() { + this.inventory.clear(); + this.getInventoryItems().clear(); + int slot = 0; + for (ItemStack itemStack : this.toReturn) { + ItemStack clone = itemStack.clone(); + this.setItem(slot++, new InventoryItem(new ItemBuilder(clone).build()).click(() -> { + if (!this.toReturn.remove((Object) itemStack)) { + this.redraw(); + Bukkit.getLogger().info("Didnt find item in toReturn: " + (Object) itemStack + " for " + this.player.getName()); + return; + } + PlayerUtils.giveOrDropProtectedItem((Player) this.player, (ItemStack) itemStack, (int) 60); + + this.player.playSound(this.player.getLocation(), Sound.LAVA_POP, 1.0f, 1.4f); + this.redraw(); + })); + } + ArrayList lore = Lists.newArrayList( new String[]{"", CC.Gray + "Confirm to auction " + CC.GrayB + this.toReturn.size() + "x" + CC.Gray + " Items:"}); + for (ItemStack item3 : this.toReturn) { + lore.add(CC.GoldB + "* " + CC.White + Util.getItemName(item3)); + } + lore.add(""); + lore.add(CC.Gold + "Starting Bid: " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.startingBid)); + lore.add(CC.Gold + "Bid Increments: " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.maxBid)); + if (this.buyoutPrice > 1L) { + lore.add(CC.Gold + "Buy Now Price: " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.buyoutPrice)); + } + lore.add(""); + lore.add(CC.RedB + "NOTE: " + CC.Red + "You cannot cancel this"); + lore.add(CC.Red + "auction once it has started!"); + InventoryItem inventoryItem = new InventoryItem(new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) DyeColor.LIME.getWoolData()).setName(CC.GreenB + "Confirm Auction").addLore((List) lore).build()).click(() -> { + if (this.toReturn.isEmpty()) { + this.player.sendMessage(CC.RedB + "(!) " + CC.Red + "You must provide at least 1 item to auction!"); + return; + } + if (this.confirmed) { + this.player.sendMessage(CC.RedB + "(!) " + CC.Red + "Package already confirmed!"); + return; + } + if (!this.canClick()) { + return; + } + this.click(); + this.confirmed = true; + this.callback.accept((Pair, Integer>) new ImmutablePair(this.toReturn, (Object) this.bidLength)); + }); + for (int index = this.size - 9; index < this.size; ++index) { + if (index < this.size - 5) { + this.setItem(index, inventoryItem); + continue; + } + this.setItem(index, new InventoryItem(new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) DyeColor.RED.getWoolData()).setName(CC.RedB + "Cancel Auction").addLore("", CC.Gray + "Click to cancel this auction.").build()).click(() -> { + if (this.confirmed) { + return; + } + Util.closePlayerInventoryOnClick(this.player); + })); + } + if (!this.toReturn.isEmpty()) { + ItemStack sellingItem = this.toReturn.get(0); + this.setItem(this.size - 5, new InventoryItem(sellingItem)); + } + for (int i = this.size - 18; i < this.size - 9; ++i) { + this.setItem(i, new InventoryItem(new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) DyeColor.GRAY.getWoolData()).setName(" ").build())); + } + boolean min = (long) this.bidLength == this.bidLength5; + boolean min2 = (long) this.bidLength == this.bidLength10; + boolean min5 = (long) this.bidLength == this.bidLength15; + boolean min30 = (long) this.bidLength == this.bidLength30; + boolean maxRank = this.player.hasPermission("enchantments.max.20"); + int slots = this.size - (maxRank ? 16 : 15); + this.setItem(slots, new InventoryItem(ItemUtils.setFakeEnchantment(new ItemBuilder(Material.WATCH).setName(CC.GreenB + "5 Minute Duration").addLore("", CC.Gray + "Click to set auction bid duration!").build(), min)).click(() -> { + if (!this.canClick()) { + return; + } + this.bidLength = (int) this.bidLength5; + this.click(); + this.redraw(); + })); + this.setItem(++slots, new InventoryItem(ItemUtils.setFakeEnchantment(new ItemBuilder(Material.WATCH).setName(CC.GreenB + "10 Minute Duration").addLore("", CC.Gray + "Click to set auction bid duration!").build(), min2)).click(() -> { + if (!this.canClick()) { + return; + } + this.bidLength = (int) this.bidLength10; + this.click(); + this.redraw(); + })); + if (maxRank) { + ++slots; + } + this.setItem(++slots, new InventoryItem(ItemUtils.setFakeEnchantment(new ItemBuilder(Material.WATCH).setName(CC.GreenB + "15 Minute Duration").addLore("", CC.Gray + "Click to set auction bid duration!").build(), min5)).click(() -> { + if (!this.canClick()) { + return; + } + this.bidLength = (int) this.bidLength15; + this.click(); + this.redraw(); + })); + if (maxRank) { + this.setItem(++slots, new InventoryItem(ItemUtils.setFakeEnchantment(new ItemBuilder(Material.WATCH).setName(CC.GreenB + "30 Minute Duration").addLore("", CC.Gray + "Click to set auction bid duration!").build(), min30)).click(() -> { + if (!this.canClick()) { + return; + } + this.bidLength = (int) this.bidLength30; + this.click(); + this.redraw(); + })); + } + } + + public void onUnknownItemClick(InventoryClickEvent event) { + event.setCancelled(true); + if (event.getClick() != ClickType.LEFT && event.getClick() != ClickType.RIGHT) { + return; + } + if (!this.canClick()) { + return; + } + this.click(); + if (event.getRawSlot() >= event.getInventory().getSize()) { + ItemStack item = event.getCurrentItem(); + if (item == null || event.getCurrentItem().getType() == Material.AIR) { + return; + } + if (!CommandHandler.canSellItem(item)) { + this.player.sendMessage(CC.Red + "You cannot sell this item."); + return; + } + if (this.toReturn.size() >= 5) { + this.player.sendMessage((Object) ChatColor.RED + "You can only sell up to 5 items in a single Auction Package!"); + return; + } + event.getClickedInventory().setItem(event.getSlot(), null); + this.toReturn.add(item); + this.player.sendMessage(CC.GreenB + "(!) " + CC.Green + "Item added into Auction Package!"); + this.player.playSound(this.player.getLocation(), Sound.ORB_PICKUP, 1.4f, 1.4f); + this.redraw(); + } + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BidCollectionBinMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BidCollectionBinMenu.java new file mode 100644 index 0000000..c94191a --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BidCollectionBinMenu.java @@ -0,0 +1,83 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.CosmicGUI + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.InventoryItem + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.InventoryUtils + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.ItemBuilder + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.PlayerUtil + * org.arkhamnetwork.Arkkit.patches.ItemID + * org.arkhamnetwork.Arkkit.plugins.ArkPlugins + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.entity.Player + * org.bukkit.inventory.ItemStack + */ +package me.recolance.auction.menu.bidmenus; + + +import me.recolance.auction.Auction; +import me.recolance.auction.menu.BidManager; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class BidCollectionBinMenu + extends CosmicGUI { + public BidCollectionBinMenu(Player player, List bin) { + super(player, "Auction Bid Collection", InventoryUtils.fitSize((int) (bin != null ? bin.size() + 1 : 9))); + } + + public void redraw() { + BidManager bidManager = Auction.getPlugin().getBidManager(); + List binItems = bidManager.getBidCollectionBin().get(this.player.getUniqueId()); + this.inventory.clear(); + this.getInventoryItems().clear(); + if (binItems != null && !binItems.isEmpty()) { + int slot = 0; + for (ItemStack toClaim : binItems) { + if (slot >= this.size) break; + this.setItem(slot++, new InventoryItem(toClaim).click(() -> { + if (!binItems.contains((Object) toClaim)) { + this.redraw(); + return; + } + if (this.player.getInventory().firstEmpty() == -1) { + this.player.sendMessage((Object) ChatColor.RED + "You do not have the inventory space for this item!"); + return; + } + binItems.remove((Object) toClaim); + if (binItems.isEmpty()) { + bidManager.getBidCollectionBin().remove(this.player.getUniqueId()); + } + + PlayerUtils.giveOrDropProtectedItem((Player) this.player, (ItemStack) toClaim, (int) -1); + if (binItems.isEmpty()) { + new BidMenu(this.player).openGUI(Auction.getPlugin()); + return; + } + this.redraw(); + })); + } + } + this.setItem(this.size - 1, new InventoryItem(new ItemBuilder(Material.ARROW).setName(CC.GreenB + "Return to Auction Page").addLore(new String[]{CC.Gray + "Click here to return to the", CC.Gray + "auction house main menu."}).build()).click(() -> { + this.player.closeInventory(); + this.player.performCommand("ah"); + })); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BidMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BidMenu.java new file mode 100644 index 0000000..9dd6dd4 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BidMenu.java @@ -0,0 +1,153 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.InventoryItem + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.ItemBuilder + * com.google.common.collect.Lists + * net.minecraft.util.io.netty.util.internal.ConcurrentSet + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.OfflinePlayer + * org.bukkit.Sound + * org.bukkit.entity.Player + * org.bukkit.event.inventory.ClickType + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.menu.bidmenus; + + +import com.google.common.collect.Lists; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.BidManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; + +import java.util.ArrayList; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +public class BidMenu + extends BiddableMenu { + int page = 1; + private long lastUpdate = 0L; + private boolean forceUpdate = false; + + public BidMenu(Player player) { + super(player, "Active Bids", 54); + } + + @Override + public String getTitle() { + return this.title; + } + + @Override + public Player getPlayer() { + return this.player; + } + + public void redraw() { + int startIndex; + if (System.currentTimeMillis() - this.lastUpdate <= 500L && !this.forceUpdate) { + return; + } + this.forceUpdate = false; + BidManager bidManager = Auction.getPlugin().getBidManager(); + ArrayList> bidEntries = Lists.newArrayList(bidManager.getActiveAuctionBids().entrySet()); // HELP + bidEntries.sort((o1, o2) -> { + int secondsLeft2; + int secondsLeft1 = o1.getValue().getSecondsLeftInAuction(); + if (secondsLeft1 > (secondsLeft2 = o2.getValue().getSecondsLeftInAuction())) { + return -1; + } + if (secondsLeft2 == secondsLeft1) { + return 0; + } + return 1; + }); + double perPage = 45.0; + int maxPages = Math.max(1, (int) Math.ceil((double) bidEntries.size() / perPage)); + if (this.page < 1) { + this.page = 1; + } + if (this.page > maxPages) { + this.page = maxPages; + } + this.inventory.clear(); + this.getInventoryItems().clear(); + this.lastUpdate = System.currentTimeMillis(); + AtomicInteger slot = new AtomicInteger(0); + for (int i = startIndex = (int) ((double) this.page * perPage - perPage); (double) i < (double) startIndex + perPage && i < bidEntries.size(); ++i) { + Map.Entry entry = bidEntries.get(i); + AuctionBid auctionBid = (AuctionBid) entry.getValue(); + if (slot.get() >= this.size) break; + if (auctionBid.isExpired()) continue; + this.setItem(slot.getAndIncrement(), new InventoryItem(new ItemBuilder(auctionBid.getAuctionDisplayItem(true)).build()).click(ClickType.LEFT, auctionBid.getLeftClickLogic(this, this.player)).click(ClickType.RIGHT, auctionBid.getRightClickLogic(this, this.player)).click(ClickType.MIDDLE, auctionBid.getMiddleClickLogic(this, this.player)).click(ClickType.SHIFT_LEFT, auctionBid.getShiftLeftClickLogic(this, this.player)).click(ClickType.SHIFT_RIGHT, () -> { + Set watching = Auction.getPlugin().getBidManager().getWatchlists().computeIfAbsent(this.player.getUniqueId(), list -> new ConcurrentSet()); + if (watching.contains(auctionBid.getBidID())) { + watching.remove(auctionBid.getBidID()); + this.player.sendMessage(CC.RedB + "(!) " + CC.Red + "Item removed from watchlist!"); + if (watching.isEmpty()) { + Auction.getPlugin().getBidManager().getWatchlists().remove(this.player.getUniqueId()); + } + return; + } + if (watching.size() >= 40) { + this.player.sendMessage(CC.RedB + "Your watch list is currently full!"); + this.player.sendMessage(CC.Gray + "Visit the watchlist tab to remove expired bids!"); + return; + } + this.player.sendMessage(CC.GreenB + "(!) " + CC.Green + "Item added to your bidding watchlist!"); + watching.add(auctionBid.getBidID()); + this.player.playSound(this.player.getLocation(), Sound.LEVEL_UP, 1.0f, 1.4f); + }).click(ClickType.NUMBER_KEY, () -> this.forceExpireAuction(auctionBid, this.player))); + } + this.setItem(this.size - 9, new InventoryItem(new ItemBuilder(Material.CHEST, CC.YellowB + "Return to Auction", CC.Gray + "Click here to return to the", CC.Gray + "auction house main menu.").build()).click(() -> { + this.player.closeInventory(); + this.player.performCommand("ah"); + })); + this.setItem(this.size - 8, new InventoryItem(new ItemBuilder(Material.DIAMOND, CC.AquaB + "View Watchlist").addLore(CC.Gray + "Click here to view all active", CC.Gray + "bids on your watchlist!").build()).click(() -> Bukkit.getScheduler().scheduleSyncDelayedTask(Auction.getPlugin(), () -> new WatchlistMenu(this.player).openGUI(Auction.getPlugin())))); + this.setItem(this.size - 6, new InventoryItem(new ItemBuilder(Material.PAPER, CC.YellowB + "<- Previous Page", CC.Gray + "View previous page of auction biddings.").build()).click(() -> { + --this.page; + this.forceUpdate = true; + this.redraw(); + })); + this.setItem(this.size - 4, new InventoryItem(new ItemBuilder(Material.PAPER, CC.YellowB + "Next Page ->", CC.Gray + "View next page of auction biddings.").build()).click(() -> { + ++this.page; + this.forceUpdate = true; + this.redraw(); + })); + } + + public void forceExpireAuction(AuctionBid auctionBid, Player player) { + if (!player.isOp()) { + return; + } + if (auctionBid.isExpired()) { + player.sendMessage(ChatColor.RED + "Bid already expired!"); + return; + } + auctionBid.expire(); + if (auctionBid.getCurrentHighestBidder() != null) { + OfflinePlayer offlineBuyer = Bukkit.getOfflinePlayer(auctionBid.getCurrentHighestBidder()); + if (offlineBuyer != null) { + Auction.economy.depositPlayer(offlineBuyer, (double) auctionBid.getCurrentBid()); + } + player.sendMessage(CC.Red + "Returned " + auctionBid.getCurrentBidderName() + " $" + auctionBid.getCurrentBid()); + } + player.sendMessage(CC.RedB + "Auction Bid force expired and items have been returned to seller!"); + this.redraw(); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BiddableMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BiddableMenu.java new file mode 100644 index 0000000..3f88f51 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/BiddableMenu.java @@ -0,0 +1,35 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.CosmicGUI + * org.bukkit.entity.Player + */ +package me.recolance.auction.menu.bidmenus; + +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import org.bukkit.entity.Player; + +import java.util.UUID; + +public abstract class BiddableMenu + extends CosmicGUI { + public boolean forceUpdate = false; + public long lastLeftClick; + public long lastRightClick; + public long lastBid; + private UUID lastSlotClicked; + + public BiddableMenu(Player player, String title, int size) { + super(player, title, size); + } + + public Player getPlayer() { + return this.player; + } + + public String getTitle() { + return this.title; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/ConfirmItemMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/ConfirmItemMenu.java new file mode 100644 index 0000000..7e4a59d --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/ConfirmItemMenu.java @@ -0,0 +1,98 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.CosmicGUI + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.InventoryItem + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.ItemBuilder + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.DyeColor + * org.bukkit.Material + * org.bukkit.OfflinePlayer + * org.bukkit.entity.Player + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.menu.bidmenus; + +import com.google.common.collect.Lists; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.BidManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.util.Util; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.function.Consumer; + +public class ConfirmItemMenu + extends CosmicGUI { + Consumer confirmCallback; + Consumer denyCallback; + private AuctionBid bid; + private long bidding; + + public ConfirmItemMenu(Player player, String title, long bidding, AuctionBid bid, Consumer confirm, Consumer deny) { + super(player, title, 9); + this.confirmCallback = confirm; + this.denyCallback = deny; + this.bid = bid; + this.bidding = bidding; + if (Auction.getPlugin().getToggles().isToggled(player)) { + Bukkit.getLogger().info("Automatically accepting confirm menu due to safetey toggles turned off: " + player.getName()); + confirm.accept(null); + } + } + + public static Consumer getConfirmCallback(AuctionBid bid, Player pl, long finalBidAmount, boolean buyout) { + return confirm -> { + if (bid.isExpired()) { + pl.sendMessage(CC.RedB + "Item no longer available!"); + return; + } + if (bid.getCurrentBid() >= finalBidAmount) { + pl.sendMessage((Object) ChatColor.RED + "Your bid must be higher than the current bid!"); + pl.sendMessage(CC.RedB + "Current Bid: $" + CC.Red + Util.formatMoney(bid.getCurrentBid())); + return; + } + if (!Auction.economy.has((OfflinePlayer) pl, (double) finalBidAmount)) { + pl.sendMessage(CC.Red + "You do not have the funds to do that!"); + return; + } + if (buyout) { + bid.buyNow(pl); + } else { + bid.placePlayerBid(pl, finalBidAmount); + } + pl.closeInventory(); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> new BidMenu(pl).openGUI(Auction.getPlugin()), 1L); + }; + } + + public void redraw() { + int i; + boolean buyout = this.bid.getBuyoutAmount() > 0.0 && this.bid.getBuyoutAmount() == (double) this.bidding; + InventoryItem item = new InventoryItem(new ItemBuilder(Material.STAINED_GLASS_PANE, CC.GreenB + "Confirm " + (buyout ? "Buy" : "Bid") + " Now", new String[]{(Object) ChatColor.GRAY + "Click to confirm " + (buyout ? "purchase of" : "bid on"), CC.Gray + "'" + CC.White + this.bid.getBidSellDisplayName() + CC.Gray + "' for " + CC.GreenB + "$" + CC.Green + Util.formatMoney(this.bidding)}).setDurability((short) DyeColor.LIME.getWoolData()).build()).click(() -> this.confirmCallback.accept(null)); + InventoryItem deny = new InventoryItem(new ItemBuilder(Material.STAINED_GLASS_PANE, CC.RedB + "Cancel", new String[]{(Object) ChatColor.GRAY + "Click to cancel this bid!"}).setDurability((short) DyeColor.RED.getWoolData()).build()).click(() -> this.denyCallback.accept(null)); + for (i = 0; i < 4; ++i) { + this.setItem(i, item); + } + for (i = 4; i < this.size; ++i) { + this.setItem(i, deny); + } + this.setItem(4, new InventoryItem(this.bid.getSellingItems().get(0).clone())); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/PackageViewMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/PackageViewMenu.java new file mode 100644 index 0000000..b0dc2b1 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/PackageViewMenu.java @@ -0,0 +1,63 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.CosmicGUI + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.InventoryItem + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.InventoryUtils + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.ItemBuilder + * org.bukkit.Bukkit + * org.bukkit.Material + * org.bukkit.entity.Player + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.menu.bidmenus; + +import com.google.common.collect.Lists; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.BidManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +public class PackageViewMenu + extends CosmicGUI { + private AuctionBid toView; + private BiddableMenu menu; + + public PackageViewMenu(Player player, AuctionBid toView, BiddableMenu parent) { + super(player, toView.getSellerName() + "'s Package Items", InventoryUtils.fitSize((int) (toView.getSellingItems().size() + 1))); + this.toView = toView; + this.menu = parent; + } + + public void redraw() { + if (this.toView.isExpired()) { + this.player.closeInventory(); + this.player.sendMessage(CC.Red + "That Auction item is no longer available!"); + return; + } + int slot = 0; + for (ItemStack item : this.toView.getSellingItems()) { + this.setItem(slot++, item, null); + } + this.setItem(this.size - 1, new InventoryItem(new ItemBuilder(Material.ARROW).setName(CC.GreenB + "Return to Auctions").addLore(new String[]{"", CC.Gray + "Click to return to auction bids!"}).build()).click(() -> Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> this.menu.openGUI(Auction.getPlugin()), 1L))); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/WatchlistMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/WatchlistMenu.java new file mode 100644 index 0000000..0ad453c --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/bidmenus/WatchlistMenu.java @@ -0,0 +1,133 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.InventoryItem + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.ItemBuilder + * net.minecraft.util.io.netty.util.internal.ConcurrentSet + * org.bukkit.Bukkit + * org.bukkit.Material + * org.bukkit.entity.Player + * org.bukkit.event.me.astropvp.cratekeys.inventory.ClickType + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.menu.bidmenus; + +import com.google.common.collect.Lists; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.BidManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.BidManager; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.plugin.Plugin; + +import java.util.LinkedList; +import java.util.Set; +import java.util.UUID; + +public class WatchlistMenu + extends BiddableMenu { + private LinkedList bidsWatching = new LinkedList(); + + public WatchlistMenu(Player player) { + super(player, "Bidding Watchlist", 54); + BidManager bidManager = Auction.getPlugin().getBidManager(); + ConcurrentSet bids = bidManager.getWatchlists().get(player.getUniqueId()); + if (bids != null) { + bids.forEach(bidId -> { + AuctionBid bid = bidManager.getActiveAuctionBids().get(bidId); + if (bid == null || bid.isExpired()) { + bids.remove(bidId); + return; + } + if (!this.bidsWatching.contains(bid)) { + this.bidsWatching.add(bid); + } + }); + if (bids.isEmpty()) { + bidManager.getWatchlists().remove(player.getUniqueId()); + } + } + if (this.bidsWatching != null) { + this.bidsWatching.sort((o1, o2) -> { + int secondsLeft2; + int secondsLeft1 = o1.getSecondsLeftInAuction(); + if (secondsLeft1 > (secondsLeft2 = o2.getSecondsLeftInAuction())) { + return -1; + } + if (secondsLeft2 == secondsLeft1) { + return 0; + } + return 1; + }); + } + } + + public void redraw() { + int slot = 0; + for (AuctionBid bid : this.bidsWatching) { + ItemBuilder builder = new ItemBuilder(bid.getAuctionDisplayItem(false)); + if (bid.isExpired()) { + builder.addLore("", CC.RedB + "EXPIRED", bid.getCurrentHighestBidder() != null ? CC.GreenB + "BUYER: " + CC.Green + bid.getCurrentBidderName() : ""); + } + this.setItem(slot++, new InventoryItem(builder.build()).click(ClickType.LEFT, () -> { + if (bid.isExpired()) { + this.player.sendMessage(CC.RedB + "That auction has expired!"); + this.player.sendMessage(CC.Gray + "Shift-RClick to remove this from your watchlist!"); + return; + } + bid.getLeftClickLogic(this, this.player).run(); + }).click(ClickType.RIGHT, () -> { + if (bid.isExpired()) { + this.player.sendMessage(CC.RedB + "That auction has expired!"); + this.player.sendMessage(CC.Gray + "Shift-RClick to remove this from your watchlist!"); + return; + } + bid.getRightClickLogic(this, this.player).run(); + }).click(ClickType.MIDDLE, () -> { + if (bid.isExpired()) { + this.player.sendMessage(CC.RedB + "That auction has expired!"); + this.player.sendMessage(CC.Gray + "Shift-RClick to remove this from your watchlist!"); + return; + } + bid.getMiddleClickLogic(this, this.player).run(); + }).click(ClickType.SHIFT_LEFT, () -> { + if (bid.isExpired()) { + this.player.sendMessage(CC.RedB + "That auction has expired!"); + this.player.sendMessage(CC.Gray + "Shift-RClick to remove this from your watchlist!"); + return; + } + bid.getShiftLeftClickLogic(this, this.player).run(); + }).click(ClickType.SHIFT_RIGHT, () -> { + Set watching = (Set) Auction.getPlugin().getBidManager().getWatchlists().computeIfAbsent(this.player.getUniqueId(), list -> new ConcurrentSet()); + this.player.sendMessage(CC.RedB + "(!) " + CC.Red + "Item removed from watchlist!"); + watching.remove(bid.getBidID()); + this.bidsWatching.remove(bid); + if (watching.isEmpty()) { + Auction.getPlugin().getBidManager().getWatchlists().remove(this.player.getUniqueId()); + } + this.redraw(); + })); + } + this.setItem(this.size - 9, new InventoryItem(new ItemBuilder(Material.CHEST, CC.YellowB + "Return to Bids", CC.Gray + "Click here to return to the", CC.Gray + "bid auction main page.").build()).click(() -> Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) Auction.getPlugin(), () -> new BidMenu(this.player).openGUI(Auction.getPlugin())))); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/AuctionCategory.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/AuctionCategory.java new file mode 100644 index 0000000..d0b5d0e --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/AuctionCategory.java @@ -0,0 +1,100 @@ +// Decompiled with: FernFlower +// Class Version: 8 +package me.recolance.auction.menu.categories; + +import com.google.common.collect.Lists; +import me.recolance.auction.auction.Listing; +import me.recolance.auction.data.AuctionItem; + +import net.crankedpvp.crankedcore.utils.ExpBottleAPI; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Comparator; +import java.util.List; + +public class AuctionCategory implements Comparable, AuctionItem { + private String displayName; + private String strippedName; + private ItemStack displayItem; + private List categoryItems = Lists.newLinkedList(); + private Listing lowestPricedItem; + private List subCategories; + private Integer rarityTier = 0; + + public double getLowestPricedItem() { + if (this.lowestPricedItem == null || this.lowestPricedItem.isExpired() || !this.lowestPricedItem.isValid()) { + this.lowestPricedItem = null; + this.lowestPricedItem = (Listing)this.categoryItems.stream().min(Comparator.comparing(Listing::getPrice)).orElse(null); + } + + return this.lowestPricedItem != null ? this.lowestPricedItem.getPrice() : 0.0D; + } + + public List getCategoryItems() { + this.categoryItems.removeIf((item) -> { + return !item.isValid() || item.isExpired(); + }); + return this.categoryItems; + } + + public void addSubCategoryItem(AuctionCategory subCategory) { + this.subCategories.add(subCategory); + } + + public void sortSubCategories() { + this.subCategories.sort(Comparator.comparingInt(AuctionCategory::getRarityTier)); + } + + public void sortCategoryItems() { + if (this.displayItem != null && this.displayItem.getType() == Material.EXP_BOTTLE && ExpBottleAPI.isXpBottle(this.displayItem)) { + int exp = ExpBottleAPI.getXpAmount(this.displayItem); + if (exp > 0) { + this.getCategoryItems().sort(Comparator.comparingDouble(Listing::getExpPerDollar)); + } + + } else { + this.getCategoryItems().sort((item1, item2) -> { + return item1.getPricePerItem() == item2.getPricePerItem() ? item1.compareTo(item2) : Double.compare(item1.getPricePerItem(), item2.getPricePerItem()); + }); + } + } + + public int compareTo(AuctionCategory o) { + return this.getDisplayItem().getType().compareTo(o.getDisplayItem().getType()); + } + + public ItemStack getDisplay() { + return this.getDisplayItem(); + } + + public AuctionCategory(String displayName, String strippedName, ItemStack displayItem, List categoryItems, Listing lowestPricedItem, List subCategories, Integer rarityTier) { + this.displayName = displayName; + this.strippedName = strippedName; + this.displayItem = displayItem; + this.categoryItems = categoryItems; + this.lowestPricedItem = lowestPricedItem; + this.subCategories = subCategories; + this.rarityTier = rarityTier; + } + + public String getDisplayName() { + return this.displayName; + } + + public String getStrippedName() { + return this.strippedName; + } + + public ItemStack getDisplayItem() { + return this.displayItem; + } + + public List getSubCategories() { + return this.subCategories; + } + + public Integer getRarityTier() { + return this.rarityTier; + } +} diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/AuctionMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/AuctionMenu.java new file mode 100644 index 0000000..1398a2a --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/AuctionMenu.java @@ -0,0 +1,107 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.CosmicGUI + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.gui.InventoryItem + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.ItemBuilder + * org.bukkit.Material + * org.bukkit.entity.Player + * org.bukkit.event.inventory.ClickType + */ +package me.recolance.auction.menu.categories; + +import com.google.common.collect.Lists; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.BidManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.auction.Listing; +import me.recolance.auction.auction.UnclaimedListing; +import me.recolance.auction.controller.Controller; +import me.recolance.auction.data.DataHolder; +import me.recolance.auction.menu.MenuRenderer; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; + +import java.util.List; + +public abstract class AuctionMenu + extends CosmicGUI { + public long nextClickExpiration = System.currentTimeMillis() + 1000L; + + public AuctionMenu(Player player, String title, int size) { + super(player, title, size); + } + + public void clearItems() { + this.inventory.clear(); + this.getInventoryItems().clear(); + } + + public InventoryItem getAuctionItem(Listing item) { + Runnable leftClick = () -> { + if (!this.canClick()) { + return; + } + if (!item.isValid() || item.isExpired()) { + this.player.sendMessage(CC.Red + "Item no longer available!"); + this.redraw(); + return; + } + if (item.getWhoListed().equals(this.player.getUniqueId())) { + this.player.sendMessage(CC.RedB + "(!) " + CC.Red + "You cannot purchase your own item!"); + this.player.sendMessage(CC.Gray + "Shift Right-Click to stop selling this item!"); + return; + } + this.nextClickExpiration = System.currentTimeMillis() + 100L; + this.closeWithDelay(pl -> MenuRenderer.purchaseConfirmation(this.player, item, true)); + }; + return new InventoryItem(new ItemBuilder(item.getMenuDisplayItem()).build()).click(ClickType.LEFT, leftClick).click(ClickType.SHIFT_RIGHT, () -> { + if (!this.canClick()) { + return; + } + if (!item.isValid() || item.isExpired()) { + this.player.sendMessage(CC.Red + "Item no longer valid!"); + this.redraw(); + return; + } + if (item.getWhoListed().equals(this.player.getUniqueId())) { + this.nextClickExpiration = System.currentTimeMillis() + 100L; + if (item.isValid() && !item.isExpired()) { + Controller.cancel(this.player, item); + this.redraw(); + } + } else { + leftClick.run(); + } + }); + } + + public InventoryItem getCollectionBinItem() { + List itemsSelling = DataHolder.getUnclaimedListings().get(this.player.getUniqueId()); + int emptyItems = itemsSelling != null ? (int) itemsSelling.stream().filter(item -> !item.isExpired()).count() : 0; + return new InventoryItem(new ItemBuilder(Material.ENDER_CHEST, CC.YellowB + "Collection Bin", new String[]{CC.Gray + "Click to view and collect", CC.Gray + "all of your active, cancelled", CC.Gray + "or expired Auction items.", "", CC.YellowB + emptyItems + " Item" + (emptyItems != 1 ? "s" : "")}).build()).click(() -> this.closeWithDelay(pl -> MenuRenderer.expired(this.player))); + } + + public boolean canClick() { + if (this.nextClickExpiration > System.currentTimeMillis() && !this.player.hasPermission("cosmicsky.auction.vip")) { + this.player.sendMessage(CC.RedB + "(!) " + CC.Red + "Please slow down in between clicks!"); + return false; + } + return true; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/CategoryItemViewMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/CategoryItemViewMenu.java new file mode 100644 index 0000000..d65d2b4 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/CategoryItemViewMenu.java @@ -0,0 +1,92 @@ +// Decompiled with: CFR 0.151 +// Class Version: 8 +package me.recolance.auction.menu.categories; + +import com.google.common.collect.Lists; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.BidManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.Auction; +import me.recolance.auction.auction.Listing; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +import java.util.List; + +public class CategoryItemViewMenu + extends AuctionMenu { + private AuctionCategory category; + private int page = 1; + + public CategoryItemViewMenu(Player player, AuctionCategory category) { + super(player, "Category Items", 54); + this.category = category; + } + + @Override + public void redraw() { + this.clearItems(); + int PREVIOUS_PAGE_SLOT = this.inventory.getSize() - 6; + int NEXT_PAGE_SLOT = this.inventory.getSize() - 4; + int MAIN_CATEGORY_SLOT = this.inventory.getSize() - 1; + int COLLECTION_BIN_SLOT = this.inventory.getSize() - 9; + List items = this.category.getCategoryItems(); + this.setItem(MAIN_CATEGORY_SLOT, new InventoryItem(new ItemBuilder(Material.PAPER, CC.RedB + "Main Category Menu", new String[]{CC.Gray + "Click to view all current", CC.Gray + "auction item categories."}).build()).click(() -> { + if (this.getParentGUI() != null) { + this.getParentGUI().openGUI(Auction.getPlugin()); + this.getParentGUI().redraw(); + } + })); + this.setItem(COLLECTION_BIN_SLOT, this.getCollectionBinItem()); + if (items.size() > 0) { + int perPage = 45; + int maxPages = (int)Math.ceil((double)items.size() / 45.0); + if (this.page > maxPages) { + this.page = maxPages; + } + if (this.page < 1) { + this.page = 1; + } + if (this.page > 1) { + int previousPage = Math.max(1, this.page - 1); + this.setItem(PREVIOUS_PAGE_SLOT, new InventoryItem(new ItemBuilder(Material.ARROW, CC.RedB + "Previous Page (" + CC.Gray + previousPage + CC.Red + "/" + CC.Gray + maxPages + CC.RedB + ")", new String[]{CC.Gray + "Click to view previous page."}).build()).click(() -> { + if (!this.canClick()) { + return; + } + --this.page; + this.nextClickExpiration = System.currentTimeMillis() + 100L; + this.redraw(); + })); + } + if (maxPages > 1 && this.page < maxPages) { + int nextPage = Math.min(maxPages, this.page + 1); + this.setItem(NEXT_PAGE_SLOT, new InventoryItem(new ItemBuilder(Material.ARROW, CC.GreenB + "Next Page (" + CC.Gray + nextPage + CC.Green + "/" + CC.Gray + maxPages + CC.GreenB + ")", new String[]{CC.Gray + "Click to view next page."}).build()).click(() -> { + if (!this.canClick()) { + return; + } + ++this.page; + this.nextClickExpiration = System.currentTimeMillis() + 100L; + this.redraw(); + })); + } + int startIndex = this.page * 45 - 45; + int endIndex = startIndex + 45; + int index = 0; + for (int i = startIndex; i < endIndex && i < items.size(); ++i) { + Listing item = items.get(i); + this.setItem(index++, this.getAuctionItem(item)); + } + } + } +} diff --git a/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/CategoryMainMenu.java b/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/CategoryMainMenu.java new file mode 100644 index 0000000..7812abb --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/menu/categories/CategoryMainMenu.java @@ -0,0 +1,166 @@ +// Decompiled with: CFR 0.151 +// Class Version: 8 +package me.recolance.auction.menu.categories; + +import com.google.common.collect.Lists; +import io.netty.util.internal.ConcurrentSet; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import me.recolance.auction.menu.BidManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.cosmicgui.CosmicGUI; +import net.crankedpvp.crankedutils.utils.cosmicgui.InventoryItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import me.recolance.auction.Auction; +import me.recolance.auction.data.AuctionBid; +import com.google.common.collect.Lists; +import me.recolance.auction.Auction; +import me.recolance.auction.auction.Listing; +import me.recolance.auction.data.AuctionItem; +import me.recolance.auction.data.DataHandler; +import me.recolance.auction.menu.MenuRenderer; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.List; + +public class CategoryMainMenu + extends AuctionMenu { + private List categories; + private int page = 1; + private boolean mainPage = true; + + public CategoryMainMenu(Player player) { + super(player, "Auction Categories", 54); + } + + public void setCategories(List categories, boolean main) { + this.categories = categories; + this.mainPage = main; + } + + private List getCategories() { + if (this.categories == null || this.categories.isEmpty()) { + this.categories = Lists.newLinkedList(DataHandler.getAuctionCategories()); + this.mainPage = true; + } + return this.categories; + } + + @Override + public void redraw() { + this.clearItems(); + int PREVIOUS_PAGE_SLOT = this.inventory.getSize() - 6; + int NEXT_PAGE_SLOT = this.inventory.getSize() - 4; + int MAIN_AUCTION_SLOT = this.inventory.getSize() - 1; + int BIN_SLOT = this.inventory.getSize() - 9; + int REFRESH_SLOT = this.inventory.getSize() - 5; + int MAIN_CATEGORIES = this.inventory.getSize() - 7; + List categories = this.getCategories(); + int perPage = 45; + int maxPages = (int)Math.ceil((double)categories.size() / 45.0); + if (this.page > maxPages) { + this.page = maxPages; + } + if (this.page < 1) { + this.page = 1; + } + if (this.page > 1) { + int previousPage = Math.max(1, this.page - 1); + this.setItem(PREVIOUS_PAGE_SLOT, new ItemBuilder(Material.ARROW, CC.RedB + "Previous Page (" + CC.Gray + previousPage + CC.Red + "/" + CC.Gray + maxPages + CC.RedB + ")", new String[]{CC.Gray + "Click to view previous category page."}).build(), () -> { + if (!this.canClick()) { + return; + } + --this.page; + this.nextClickExpiration = System.currentTimeMillis() + 100L; + this.redraw(); + }); + } + if (maxPages > 1 && this.page < maxPages) { + int nextPage = Math.min(maxPages, this.page + 1); + this.setItem(NEXT_PAGE_SLOT, new ItemBuilder(Material.ARROW, CC.GreenB + "Next Page (" + CC.Gray + nextPage + CC.Green + "/" + CC.Gray + maxPages + CC.GreenB + ")", new String[]{CC.Gray + "Click to view next category page."}).build(), () -> { + if (!this.canClick()) { + return; + } + ++this.page; + this.nextClickExpiration = System.currentTimeMillis() + 100L; + this.redraw(); + }); + } + this.setItem(MAIN_AUCTION_SLOT, new ItemBuilder(Material.PAPER, CC.YellowB + "Main Auction Menu", new String[]{CC.Gray + "Click to view the main auction menu."}).build(), () -> this.closeWithDelay(pl -> MenuRenderer.openAuction(this.player))); + this.setItem(BIN_SLOT, this.getCollectionBinItem()); + this.setItem(REFRESH_SLOT, new ItemBuilder(Material.WATCH, CC.GreenB + "Refresh", new String[]{CC.Gray + "Click to refresh the auction page!"}).build(), () -> { + if (!this.canClick()) { + return; + } + this.nextClickExpiration = System.currentTimeMillis() + 100L; + this.redraw(); + }); + if (!this.mainPage) { + this.setItem(MAIN_CATEGORIES, new ItemBuilder(Material.CHEST, CC.RedB + "Main Categories", new String[]{CC.Gray + "Click to view main category page."}).build(), () -> { + if (!this.canClick()) { + return; + } + this.page = 1; + this.nextClickExpiration = System.currentTimeMillis() + 100L; + this.categories = Lists.newLinkedList(DataHandler.getAuctionCategories()); + this.mainPage = true; + this.redraw(); + }); + } + int startIndex = this.page * 45 - 45; + int endIndex = startIndex + 45; + int index = 0; + for (int i = startIndex; i < endIndex && i < categories.size(); ++i) { + AuctionItem item = categories.get(i); + ItemStack display = item.getDisplay(); + ItemMeta im = display.getItemMeta(); + if (item instanceof AuctionCategory) { + AuctionCategory category = (AuctionCategory)item; + if (category.getCategoryItems().size() == 1 && category.getSubCategories().isEmpty()) { + this.setItem(index++, this.getAuctionItem(category.getCategoryItems().get(0))); + continue; + } + ArrayList lore = Lists.newArrayList(); + lore.add(""); + if (category.getSubCategories() != null && !category.getSubCategories().isEmpty()) { + lore.add(CC.Gold + "Sub Categories: " + CC.Yellow + category.getSubCategories().size()); + } + lore.add(CC.GoldB + "Listings: " + CC.Yellow + category.getCategoryItems().size()); + lore.add(CC.Gold + " Lowest Price: " + CC.YellowB + "$" + CC.Yellow + NumberUtils.formatMoney(category.getLowestPricedItem())); + if (category.getSubCategories() != null && !category.getSubCategories().isEmpty()) { + lore.add(CC.Gray + "Click to view sub categories!"); + } + im.setLore(lore); + display.setItemMeta(im); + this.setItem(index++, new InventoryItem(display).click(() -> { + if (category.getSubCategories() != null && category.getSubCategories().size() > 0) { + this.categories = Lists.newLinkedList(category.getSubCategories()); + if (category.getCategoryItems() != null && !category.getCategoryItems().isEmpty()) { + this.categories.addAll(category.getCategoryItems()); + } + this.mainPage = false; + this.redraw(); + return; + } + new CategoryItemViewMenu(this.player, category).setParentGUI(this).openGUI(Auction.getPlugin()); + })); + continue; + } + if (!(item instanceof Listing)) continue; + this.setItem(index++, this.getAuctionItem((Listing)item)); + } + } + + public void setCategories(List categories) { + this.categories = categories; + } +} diff --git a/Auctionhouse/src/main/java/me/recolance/auction/tasks/ItemExpireWarnTask.java b/Auctionhouse/src/main/java/me/recolance/auction/tasks/ItemExpireWarnTask.java new file mode 100644 index 0000000..f7f837f --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/tasks/ItemExpireWarnTask.java @@ -0,0 +1,41 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Sound + * org.bukkit.entity.Player + * org.bukkit.scheduler.BukkitRunnable + */ +package me.recolance.auction.tasks; + +import me.recolance.auction.auction.UnclaimedListing; +import me.recolance.auction.data.DataHolder; +import me.recolance.auction.util.Util; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.List; + +public class ItemExpireWarnTask + extends BukkitRunnable { + public void run() { + block0: + for (Player p : Bukkit.getOnlinePlayers()) { + List listings = DataHolder.getUnclaimedListings().get(p.getUniqueId()); + if (listings == null || listings.size() <= 0) continue; + for (UnclaimedListing ul : listings) { + long l = ul.getExpireTime() - System.currentTimeMillis(); + if (l <= 0L || l > 900000L) continue; + p.sendMessage((Object) ChatColor.RED + "" + (Object) ChatColor.BOLD + "(!) " + (Object) ChatColor.RED + "You have item(s) in your " + (Object) ChatColor.UNDERLINE + "/ah expired" + (Object) ChatColor.RED + " that are going to be deleted in " + (Object) ChatColor.BOLD + Util.timeToDHMSString(l)); + p.playSound(p.getLocation(), Sound.CHICKEN_EGG_POP, 1.2f, 1.25f); + continue block0; + } + } + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/util/AuctionUtil.java b/Auctionhouse/src/main/java/me/recolance/auction/util/AuctionUtil.java new file mode 100644 index 0000000..23a965e --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/util/AuctionUtil.java @@ -0,0 +1,67 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.entity.Player + */ +package me.recolance.auction.util; + +import me.recolance.auction.Auction; +import me.recolance.auction.data.DataHolder; +import org.bukkit.entity.Player; + +public class AuctionUtil { + public static int getCurrentlySellingAmount(Player player) { + if (!DataHolder.getPlayerListings().containsKey(player.getUniqueId())) { + return 0; + } + return DataHolder.getPlayerListings().get(player.getUniqueId()).size(); + } + + public static int getItemsToCollectAmount(Player player) { + if (!DataHolder.getUnclaimedListings().containsKey(player.getUniqueId())) { + return 0; + } + return DataHolder.getUnclaimedListings().get(player.getUniqueId()).size(); + } + + public static long getEndTime() { + return System.currentTimeMillis() + 864000000; //10 days + } + + public static long getUnclaimedEndTime() { + return System.currentTimeMillis() + (long) (Auction.plugin.getConfig().getInt("auction.unclaimedHours") * 3600000); + } + + public static boolean canSellItemPermission(Player player) { + int currentlySelling = AuctionUtil.getCurrentlySellingAmount(player); + if (player.isOp()) { + return true; + } + int limit = AuctionUtil.getSellItemLimit(player); + return currentlySelling + 1 <= limit; + } + + private static int getSellItemLimit(Player p) { + if (p.hasPermission("auction.limit.8")) { + return 8; + } + if (p.hasPermission("auction.limit.6")) { + return 6; + } + if (p.hasPermission("auction.limit.5")) { + return 5; + } + if (p.hasPermission("auction.limit.4")) { + return 4; + } + if (p.hasPermission("auction.limit.3")) { + return 3; + } + if (p.hasPermission("auction.limit.2")) { + return 2; + } + return 1; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/util/Item.java b/Auctionhouse/src/main/java/me/recolance/auction/util/Item.java new file mode 100644 index 0000000..cdcb2f7 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/util/Item.java @@ -0,0 +1,214 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * net.minecraft.server.v1_8_R3.ItemStack + * net.minecraft.server.v1_8_R3.NBTTagCompound + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.craftbukkit.v1_8_R3.me.astropvp.cratekeys.inventory.CraftItemStack + * org.bukkit.enchantments.Enchantment + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.me.astropvp.cratekeys.inventory.meta.ItemMeta + * org.bukkit.me.astropvp.cratekeys.inventory.meta.SkullMeta + */ +package me.recolance.auction.util; + +import me.recolance.globalutils.attribute.Attributes; +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.ArrayList; +import java.util.UUID; + +public class Item { + private ItemStack item; + + public Item() { + this.item = new ItemStack(Material.AIR, 1); + } + + public Item(ItemStack item) { + this.item = item; + } + + public Item(Item item) { + item = this; + } + + public Item setAmount(int amount) { + this.item.setAmount(amount); + return this; + } + + public Item setType(Material mat) { + this.item.setType(mat); + return this; + } + + public Item setType(int id) { + this.item.setTypeId(id); + return this; + } + + public Item setDurability(short d) { + this.item.setDurability(d); + return this; + } + + public Item setDurability(int d) { + this.item.setDurability((short) d); + return this; + } + + public Item setName(String name) { + name = ChatColor.translateAlternateColorCodes((char) '&', (String) name); + ItemMeta meta = this.item.getItemMeta(); + meta.setDisplayName(name); + this.item.setItemMeta(meta); + return this; + } + + public Item addLore(String... lore) { + ItemMeta meta = this.item.getItemMeta(); + ArrayList loreList = new ArrayList(); + if (meta.hasLore()) { + loreList.addAll(meta.getLore()); + } + for (String line : lore) { + loreList.add(ChatColor.translateAlternateColorCodes((char) '&', (String) line)); + } + meta.setLore(loreList); + this.item.setItemMeta(meta); + return this; + } + + public boolean isEnchanted() { + return this.item.hasItemMeta() && this.item.getItemMeta().hasEnchants(); + } + + public Item addEnchant(int eId, int level) { + return this.addEnchant(Enchantment.getById((int) eId), level); + } + + public Item addEnchant(Enchantment enchant, int level) { + this.item.addUnsafeEnchantment(enchant, level); + return this; + } + + public Item incrementEnchant(int eId, int amount) { + return this.incrementEnchant(Enchantment.getById((int) eId), amount); + } + + public Item incrementEnchant(Enchantment enchant, int amount) { + if (!this.item.containsEnchantment(enchant)) { + this.item.addUnsafeEnchantment(enchant, amount); + } else { + int cEL = this.item.getEnchantmentLevel(enchant); + this.item.removeEnchantment(enchant); + this.item.addUnsafeEnchantment(enchant, cEL + amount); + } + return this; + } + + public Item incrementSafeEnchant(int eId, int amount) { + return this.incrementSafeEnchant(Enchantment.getById((int) eId), amount); + } + + public Item incrementSafeEnchant(Enchantment enchant, int amount) { + int mEL = enchant.getMaxLevel(); + if (!this.item.containsEnchantment(enchant)) { + int inc = amount > mEL ? mEL : amount; + this.item.addEnchantment(enchant, inc); + } else { + int cEL = this.item.getEnchantmentLevel(enchant); + int inc = cEL + amount > mEL ? mEL : cEL + amount; + this.item.removeEnchantment(enchant); + this.item.addEnchantment(enchant, inc); + } + return this; + } + + public Item skull(UUID uuid) { + return this.skull(Bukkit.getOfflinePlayer((UUID) uuid).getName()); + } + + public Item skull(String name) { + SkullMeta meta = (SkullMeta) this.item.getItemMeta(); + meta.setOwner(name); + this.item.setItemMeta((ItemMeta) meta); + return this; + } + + public Item hideFlag(FlagType flagType) { + int type = (Integer) flagType.getFlag(); + net.minecraft.server.v1_8_R3.ItemStack stack = CraftItemStack.asNMSCopy((ItemStack) this.item); + NBTTagCompound compound = stack.getTag(); + if (compound == null) { + compound = new NBTTagCompound(); + stack.setTag(compound); + compound = stack.getTag(); + } + compound.setInt("HideFlags", type); + stack.setTag(compound); + this.item = CraftItemStack.asCraftMirror((net.minecraft.server.v1_8_R3.ItemStack) stack); + return this; + } + + public Item setUnbreakable(boolean isUnbreakable) { + int type = isUnbreakable ? (Integer) FlagType.UNBREAKABLE_TRUE.getFlag() : (Integer) FlagType.UNBREAKABLE_FALSE.getFlag(); + net.minecraft.server.v1_8_R3.ItemStack stack = CraftItemStack.asNMSCopy((ItemStack) this.item); + NBTTagCompound compound = stack.getTag(); + if (compound == null) { + compound = new NBTTagCompound(); + stack.setTag(compound); + compound = stack.getTag(); + } + compound.setInt("Unbreakable", type); + stack.setTag(compound); + this.item = CraftItemStack.asCraftMirror((net.minecraft.server.v1_8_R3.ItemStack) stack); + return this; + } + + public Item addAttribute(String name, Attributes.AttributeType type, double amount) { + Attributes a = new Attributes(this.item); + a.add(Attributes.Attribute.newBuilder().name(name).type(type).amount(amount).build()); + this.item = a.getStack(); + return this; + } + + public ItemStack get() { + return this.item; + } + + public static enum FlagType { + ENCHANTMENTS(1), + ATTRIBUTES(2), + UNBREAKABLE(4), + CAN_DESTROY(8), + CAN_PLACE_ON(16), + OTHERS(32), + ALL(64), + UNBREAKABLE_TRUE(1), + UNBREAKABLE_FALSE(0); + + private Object flag; + + private FlagType(Object flag) { + this.flag = flag; + } + + public Object getFlag() { + return this.flag; + } + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/util/ItemSerialization.java b/Auctionhouse/src/main/java/me/recolance/auction/util/ItemSerialization.java new file mode 100644 index 0000000..f1c5785 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/util/ItemSerialization.java @@ -0,0 +1,291 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.net.astropvp.armorsets.utils.ItemBuilder + * net.minecraft.server.v1_8_R3.ItemStack + * net.minecraft.server.v1_8_R3.NBTBase + * net.minecraft.server.v1_8_R3.NBTCompressedStreamTools + * net.minecraft.server.v1_8_R3.NBTReadLimiter + * net.minecraft.server.v1_8_R3.NBTTagCompound + * net.minecraft.server.v1_8_R3.NBTTagList + * org.bukkit.Material + * org.bukkit.craftbukkit.v1_8_R3.inventory.CraftInventoryCustom + * org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack + * org.bukkit.inventory.Inventory + * org.bukkit.inventory.ItemStack + * org.bukkit.inventory.PlayerInventory + * org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder + */ +package me.recolance.auction.util; + +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.minecraft.server.v1_8_R3.*; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftInventoryCustom; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.*; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class ItemSerialization { + private static final int VERSION = 1; + private static final String INVENTORY_CUSTOM = "custom"; + private static final String INVENTORY_PLAYER = "player"; + private static final int NBT_TYPE_COMPOUND = 10; + private static final String NBT_TYPE = "type"; + private static final String NBT_ITEM = "item"; + private static final String NBT_ITEMS = "items"; + private static final String NBT_VERSION = "version"; + private static final String NBT_PLAYER_HELD_INDEX = "player_held_index"; + private static final String NBT_PLAYER_NAME = "player_name"; + private static Method WRITE_NBT; + private static Method READ_NBT; + + public static String inventoryToString(Inventory inv) { + return ItemSerialization.toBase64(inv); + } + + public static Inventory getInventoryFromString(String s, String name, int size) { + return ItemSerialization.fromBase64(s, name, size); + } + + public static String itemListToBase64(List items) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + DataOutputStream dataOutput = new DataOutputStream(outputStream); + NBTTagCompound root = new NBTTagCompound(); + NBTTagList itemList = new NBTTagList(); + for (ItemStack is : items) { + NBTTagCompound outputObject = new NBTTagCompound(); + CraftItemStack craft = ItemSerialization.getCraftVersion(is); + net.minecraft.server.v1_8_R3.ItemStack nmsCopy = CraftItemStack.asNMSCopy((ItemStack) craft); + if (nmsCopy != null) { + nmsCopy.save(outputObject); + } + itemList.add((NBTBase) outputObject); + } + root.setInt(NBT_VERSION, 1); + root.set(NBT_ITEMS, (NBTBase) itemList); + ItemSerialization.writeNbt((NBTBase) root, dataOutput); + return Base64Coder.encodeLines((byte[]) outputStream.toByteArray()); + } + + /* + * WARNING - Removed try catching itself - possible behaviour change. + * Enabled aggressive exception aggregation + */ + public static String itemToStringBase64(ItemStack item) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try { + String string; + block11: + { + DataOutputStream dataOutput = new DataOutputStream(outputStream); + try { + NBTTagCompound root = new NBTTagCompound(); + CraftItemStack craft = ItemSerialization.getCraftVersion(item); + net.minecraft.server.v1_8_R3.ItemStack nmsCopy = CraftItemStack.asNMSCopy((ItemStack) craft); + NBTTagCompound outputObject = new NBTTagCompound(); + if (nmsCopy != null) { + nmsCopy.save(outputObject); + } + root.setInt(NBT_VERSION, 1); + root.set(NBT_ITEM, (NBTBase) outputObject); + ItemSerialization.writeNbt((NBTBase) root, dataOutput); + String retr = Base64Coder.encodeLines((byte[]) outputStream.toByteArray()); + dataOutput.close(); + outputStream.close(); + string = retr; + if (Collections.singletonList(dataOutput).get(0) == null) break block11; + } catch (Throwable throwable) { + if (Collections.singletonList(dataOutput).get(0) != null) { + dataOutput.close(); + } + throw throwable; + } + dataOutput.close(); + } + return string; + } finally { + if (Collections.singletonList(outputStream).get(0) != null) { + outputStream.close(); + } + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static ItemStack itemFromBase64(String data) { + if (data == null) { + return new ItemBuilder(Material.DIRT, "Invalid NBT Data!").build(); + } + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines((String) data)); + NBTTagCompound root = (NBTTagCompound) ItemSerialization.readNbt(new DataInputStream(inputStream), 0); + if (root.getInt(NBT_VERSION) != 1) { + throw new IllegalArgumentException("Incompatible version: " + root.getInt(NBT_VERSION)); + } + NBTTagCompound compound = root.getCompound(NBT_ITEM); + if (!compound.isEmpty()) { + return CraftItemStack.asCraftMirror((net.minecraft.server.v1_8_R3.ItemStack) net.minecraft.server.v1_8_R3.ItemStack.createStack((NBTTagCompound) compound)); + } + return null; + } + + public static List itemListFromBase64(String data) { + ArrayList items = new ArrayList(); + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines((String) data)); + NBTTagCompound root = (NBTTagCompound) ItemSerialization.readNbt(new DataInputStream(inputStream), 0); + if (root.getInt(NBT_VERSION) != 1) { + throw new IllegalArgumentException("Incompatible version: " + root.getInt(NBT_VERSION)); + } + NBTTagList itemList = root.getList(NBT_ITEMS, 10); + for (int i = 0; i < itemList.size(); ++i) { + NBTTagCompound inputObject = itemList.get(i); + if (inputObject.isEmpty()) continue; + items.add((ItemStack) CraftItemStack.asCraftMirror((net.minecraft.server.v1_8_R3.ItemStack) net.minecraft.server.v1_8_R3.ItemStack.createStack((NBTTagCompound) inputObject))); + } + return items; + } + + /* + * WARNING - Removed try catching itself - possible behaviour change. + * Enabled aggressive exception aggregation + */ + public static String toBase64(Inventory inventory) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try { + String string; + block13: + { + DataOutputStream dataOutput = new DataOutputStream(outputStream); + try { + NBTTagCompound root = new NBTTagCompound(); + NBTTagList itemList = new NBTTagList(); + String type = INVENTORY_CUSTOM; + int size = inventory.getSize(); + if (inventory instanceof PlayerInventory) { + PlayerInventory playerInventory = (PlayerInventory) inventory; + root.setInt(NBT_PLAYER_HELD_INDEX, playerInventory.getHeldItemSlot()); + root.setString(NBT_PLAYER_NAME, playerInventory.getHolder().getName()); + type = INVENTORY_PLAYER; + size += 4; + } + for (int i = 0; i < size; ++i) { + NBTTagCompound outputObject = new NBTTagCompound(); + CraftItemStack craft = ItemSerialization.getCraftVersion(inventory.getItem(i)); + net.minecraft.server.v1_8_R3.ItemStack nmsCopy = CraftItemStack.asNMSCopy((ItemStack) craft); + if (nmsCopy != null) { + nmsCopy.save(outputObject); + } + itemList.add((NBTBase) outputObject); + } + root.setString(NBT_TYPE, type); + root.setInt(NBT_VERSION, 1); + root.set(NBT_ITEMS, (NBTBase) itemList); + ItemSerialization.writeNbt((NBTBase) root, dataOutput); + string = Base64Coder.encodeLines((byte[]) outputStream.toByteArray()); + if (Collections.singletonList(dataOutput).get(0) == null) break block13; + } catch (Throwable throwable) { + if (Collections.singletonList(dataOutput).get(0) != null) { + dataOutput.close(); + } + throw throwable; + } + dataOutput.close(); + } + return string; + } finally { + if (Collections.singletonList(outputStream).get(0) != null) { + outputStream.close(); + } + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static Inventory fromBase64(String data, String name, int size) { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines((String) data)); + NBTTagCompound root = (NBTTagCompound) ItemSerialization.readNbt(new DataInputStream(inputStream), 0); + if (root.getInt(NBT_VERSION) != 1) { + throw new IllegalArgumentException("Incompatible version: " + root.getInt(NBT_VERSION)); + } + NBTTagList itemList = root.getList(NBT_ITEMS, 10); + String type = root.getString(NBT_TYPE); + return ItemSerialization.parseInventory(root, size, itemList, type, name); + } + + private static Inventory parseInventory(NBTTagCompound root, int size, NBTTagList itemList, String type, String name) { + CraftInventoryCustom inventory = new CraftInventoryCustom(null, size, name); + for (int i = 0; i < itemList.size(); ++i) { + NBTTagCompound inputObject = itemList.get(i); + if (inputObject.isEmpty()) continue; + inventory.setItem(i, (ItemStack) CraftItemStack.asCraftMirror((net.minecraft.server.v1_8_R3.ItemStack) net.minecraft.server.v1_8_R3.ItemStack.createStack((NBTTagCompound) inputObject))); + } + return inventory; + } + + private static void writeNbt(NBTBase base, DataOutput output) { + if (WRITE_NBT == null) { + try { + WRITE_NBT = NBTCompressedStreamTools.class.getDeclaredMethod("a", NBTBase.class, DataOutput.class); + WRITE_NBT.setAccessible(true); + } catch (Exception e) { + throw new IllegalStateException("Unable to find private write method.", e); + } + } + try { + WRITE_NBT.invoke(null, new Object[]{base, output}); + } catch (Exception e) { + throw new IllegalArgumentException("Unable to write " + (Object) base + " to " + output, e); + } + } + + private static NBTBase readNbt(DataInput input, int level) { + if (READ_NBT == null) { + try { + READ_NBT = NBTCompressedStreamTools.class.getDeclaredMethod("a", DataInput.class, Integer.TYPE, NBTReadLimiter.class); + READ_NBT.setAccessible(true); + } catch (Exception e) { + throw new IllegalStateException("Unable to find private read method.", e); + } + } + try { + return (NBTBase) READ_NBT.invoke(null, new Object[]{input, level, NBTReadLimiter.a}); + } catch (Exception e) { + throw new IllegalArgumentException("Unable to read from " + input, e); + } + } + + public static Inventory getInventoryFromArray(ItemStack[] items) { + CraftInventoryCustom custom = new CraftInventoryCustom(null, items.length); + for (int i = 0; i < items.length; ++i) { + if (items[i] == null) continue; + custom.setItem(i, items[i]); + } + return custom; + } + + private static CraftItemStack getCraftVersion(ItemStack stack) { + if (stack instanceof CraftItemStack) { + return (CraftItemStack) stack; + } + if (stack != null) { + return CraftItemStack.asCraftCopy((ItemStack) stack); + } + return null; + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/util/ItemUtils.java b/Auctionhouse/src/main/java/me/recolance/auction/util/ItemUtils.java new file mode 100644 index 0000000..ba627da --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/util/ItemUtils.java @@ -0,0 +1,75 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * net.minecraft.server.v1_8_R3.ItemStack + * net.minecraft.server.v1_8_R3.NBTBase + * net.minecraft.server.v1_8_R3.NBTTagCompound + * org.bukkit.Material + * org.bukkit.craftbukkit.v1_8_R3.me.astropvp.cratekeys.inventory.CraftItemStack + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.me.astropvp.cratekeys.inventory.meta.ItemMeta + */ +package me.recolance.auction.util; + +import net.minecraft.server.v1_8_R3.ItemStack; +import net.minecraft.server.v1_8_R3.NBTBase; +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Arrays; + +public class ItemUtils { + public static org.bukkit.inventory.ItemStack buildItem(Material m, short metaData, String name, String... description) { + org.bukkit.inventory.ItemStack is = new org.bukkit.inventory.ItemStack(m, 1, metaData); + ItemMeta im = is.getItemMeta(); + if (name != null) { + im.setDisplayName(name); + } + if (description != null) { + im.setLore(Arrays.asList(description)); + } + is.setItemMeta(im); + return is; + } + + public static org.bukkit.inventory.ItemStack setNBTString(org.bukkit.inventory.ItemStack item, String key, String data) { + ItemStack nmsItem = CraftItemStack.asNMSCopy((org.bukkit.inventory.ItemStack) item); + NBTTagCompound compound = nmsItem.getTag(); + if (compound == null) { + compound = new NBTTagCompound(); + } + compound.setString(key, data); + nmsItem.setTag(compound); + return CraftItemStack.asCraftMirror((ItemStack) nmsItem); + } + + public static org.bukkit.inventory.ItemStack setFakeEnchantment(org.bukkit.inventory.ItemStack item, boolean enchant) { + if (!enchant) { + return item; + } + ItemStack nmsItem = CraftItemStack.asNMSCopy((org.bukkit.inventory.ItemStack) item); + NBTTagCompound compound = nmsItem.getTag(); + if (compound == null) { + compound = new NBTTagCompound(); + } + compound.set("ench", (NBTBase) new NBTTagCompound()); + nmsItem.setTag(compound); + return CraftItemStack.asCraftMirror((ItemStack) nmsItem); + } + + public static String getNBTString(org.bukkit.inventory.ItemStack item, String key) { + ItemStack nmsItem = CraftItemStack.asNMSCopy((org.bukkit.inventory.ItemStack) item); + NBTTagCompound compound = nmsItem.getTag(); + if (compound == null) { + return null; + } + if (!compound.hasKey(key)) { + return null; + } + return compound.getString(key); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/auction/util/Util.java b/Auctionhouse/src/main/java/me/recolance/auction/util/Util.java new file mode 100644 index 0000000..5cc28e9 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/auction/util/Util.java @@ -0,0 +1,158 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.entity.Player + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.plugin.Plugin + */ +package me.recolance.auction.util; + +import me.recolance.auction.Auction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +import java.text.DecimalFormat; +import java.util.regex.Pattern; + +public class Util { + private static DecimalFormat format = new DecimalFormat("#,###"); + + public static String setStringColors(String message) { + return ChatColor.translateAlternateColorCodes((char) '&', (String) message); + } + + public static void message(Player player, String message) { + player.sendMessage(ChatColor.translateAlternateColorCodes((char) '&', (String) message)); + } + + public static String formatMoney(long value) { + return format.format(value); + } + + public static String formatMoney(double value) { + return format.format(value); + } + + public static void closePlayerInventoryOnClick(Player p) { + Bukkit.getScheduler().runTaskLater((Plugin) Auction.getPlugin(), ((Player) p)::closeInventory, 1L); + } + + public static Long parseLongOrNull(String strg) { + try { + return Long.parseLong(strg); + } catch (Exception exception) { + return null; + } + } + + public static long getMoneyValue(String formatted_value) { + String numb_val = ChatColor.stripColor((String) formatted_value.replaceAll(",", "").replace("$", "")).toLowerCase(); + numb_val = numb_val.replace("k", "000"); + numb_val = numb_val.replace("million", "000000"); + numb_val = numb_val.replace("billion", "000000000"); + numb_val = numb_val.replace("trillion", "000000000000"); + numb_val = numb_val.replace("mil", "000000"); + numb_val = numb_val.replace("bil", "000000000"); + numb_val = numb_val.replace("tril", "000000000000"); + numb_val = numb_val.replace("m", "000000"); + numb_val = numb_val.replace("b", "000000000"); + numb_val = numb_val.replace("t", "000000000000"); + return Long.parseLong(numb_val); + } + + public static boolean hasInventorySpace(Player player) { + for (ItemStack item : player.getInventory().getContents()) { + if (item != null && item.getType() != Material.AIR) continue; + return true; + } + return false; + } + + public static int getFreeInventorySpace(Player player) { + int i = 0; + for (ItemStack item : player.getInventory().getContents()) { + if (item != null && item.getType() != Material.AIR) continue; + ++i; + } + return i; + } + + public static boolean itemLoreContains(ItemStack i, String s) { + if (i == null || !i.hasItemMeta() || !i.getItemMeta().hasLore()) { + return false; + } + for (String lore : i.getItemMeta().getLore()) { + if (!lore.equals(s)) continue; + return true; + } + return false; + } + + public static String getItemName(ItemStack item) { + if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) { + return item.getItemMeta().getDisplayName(); + } + String name = item.getType().name(); + name = name.replace('_', ' '); + StringBuilder sb = new StringBuilder(name = name.toLowerCase()); + if (sb.length() > 0) { + sb.setCharAt(0, Character.toUpperCase(name.charAt(0))); + } + int i = 0; + for (char character : name.toCharArray()) { + if (character == ' ') { + sb.setCharAt(i + 1, Character.toUpperCase(sb.charAt(i + 1))); + } + ++i; + } + return sb.toString(); + } + + public static boolean stringIsNumerical(String string) { + Pattern pattern = Pattern.compile("[^0-9]"); + return !pattern.matcher(string).find(); + } + + public static String getRemainingTimeString(long startTime, long lengthOfTime) { + return Util.timeToDHMSString(startTime - System.currentTimeMillis() + lengthOfTime); + } + + public static String timeToDHMSString(long time) { + int second = 1000; + int minute = second * 60; + int hour = minute * 60; + int day = hour * 24; + long playTimeManipulator = time; + StringBuilder timeString = new StringBuilder(); + if (playTimeManipulator >= (long) day) { + long finalDay = playTimeManipulator / (long) day; + playTimeManipulator -= finalDay * (long) day; + timeString.append(finalDay + (finalDay > 1L ? "d " : "d ")); + } + if (playTimeManipulator >= (long) hour) { + long finalHour = playTimeManipulator / (long) hour; + playTimeManipulator -= finalHour * (long) hour; + timeString.append(finalHour + (finalHour > 1L ? "h " : "h ")); + } + if (playTimeManipulator >= (long) minute) { + long finalMinute = playTimeManipulator / (long) minute; + playTimeManipulator -= finalMinute * (long) minute; + timeString.append(finalMinute + (finalMinute > 1L ? "m " : "m ")); + } + if (playTimeManipulator >= (long) second) { + long finalSecond = playTimeManipulator / (long) second; + playTimeManipulator -= finalSecond * (long) second; + timeString.append(finalSecond + (finalSecond > 1L ? "s" : "s")); + } + return timeString.toString(); + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/globalutils/attribute/Attributes.java b/Auctionhouse/src/main/java/me/recolance/globalutils/attribute/Attributes.java new file mode 100644 index 0000000..533f621 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/globalutils/attribute/Attributes.java @@ -0,0 +1,311 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.google.common.base.Function + * com.google.common.base.Objects + * com.google.common.base.Preconditions + * com.google.common.collect.Iterators + * com.google.common.collect.Maps + * javax.annotation.Nonnull + * javax.annotation.Nullable + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + */ +package me.recolance.globalutils.attribute; + +import com.google.common.base.Function; +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterators; +import com.google.common.collect.Maps; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Iterator; +import java.util.UUID; +import java.util.concurrent.ConcurrentMap; + +public class Attributes { + public ItemStack stack; + private NbtFactory.NbtList attributes; + + public Attributes(ItemStack stack) { + this.stack = NbtFactory.getCraftItemStack(stack); + NbtFactory.NbtCompound nbt = NbtFactory.fromItemTag(this.stack); + this.attributes = nbt.getList("AttributeModifiers", true); + } + + public ItemStack getStack() { + return this.stack; + } + + public int size() { + return this.attributes.size(); + } + + public void add(Attribute attribute) { + Preconditions.checkNotNull((Object) attribute.getName(), (Object) "must specify an attribute name."); + this.attributes.add(attribute.data); + } + + public boolean remove(Attribute attribute) { + UUID uuid = attribute.getUUID(); + Iterator it = this.values().iterator(); + while (it.hasNext()) { + if (!Objects.equal((Object) it.next().getUUID(), (Object) uuid)) continue; + it.remove(); + return true; + } + return false; + } + + public void clear() { + this.attributes.clear(); + } + + public Attribute get(int index) { + return new Attribute((NbtFactory.NbtCompound) this.attributes.get(index)); + } + + public Iterable values() { + return new Iterable() { + + @Override + public Iterator iterator() { + return Iterators.transform(Attributes.this.attributes.iterator(), (Function) new Function() { + + public Attribute apply(@Nullable Object element) { + return new Attribute((NbtFactory.NbtCompound) element); + } + }); + } + }; + } + + public static enum Operation { + ADD_NUMBER(0), + MULTIPLY_PERCENTAGE(1), + ADD_PERCENTAGE(2); + + private int id; + + private Operation(int id) { + this.id = id; + } + + public static Operation fromId(int id) { + for (Operation op : Operation.values()) { + if (op.getId() != id) continue; + return op; + } + throw new IllegalArgumentException("Corrupt operation ID " + id + " detected."); + } + + public int getId() { + return this.id; + } + } + + public static class Attribute { + private NbtFactory.NbtCompound data; + + private Attribute(Builder builder) { + this.data = NbtFactory.createCompound(); + this.setAmount(builder.amount); + this.setOperation(builder.operation); + this.setAttributeType(builder.type); + this.setName(builder.name); + this.setUUID(builder.uuid); + } + + private Attribute(NbtFactory.NbtCompound data) { + this.data = data; + } + + public static Builder newBuilder() { + return new Builder().uuid(UUID.randomUUID()).operation(Operation.ADD_NUMBER); + } + + private static /* synthetic */ void $$$reportNull$$$0(int n) { + Object[] arrobject; + Object[] arrobject2; + Object[] arrobject3 = new Object[3]; + switch (n) { + default: { + arrobject2 = arrobject3; + arrobject3[0] = "operation"; + break; + } + case 1: { + arrobject2 = arrobject3; + arrobject3[0] = "type"; + break; + } + case 2: { + arrobject2 = arrobject3; + arrobject3[0] = "name"; + break; + } + case 3: { + arrobject2 = arrobject3; + arrobject3[0] = "id"; + break; + } + } + arrobject2[1] = "me/recolance/globalutils/attribute/Attributes$Attribute"; + switch (n) { + default: { + arrobject = arrobject2; + arrobject2[2] = "setOperation"; + break; + } + case 1: { + arrobject = arrobject2; + arrobject2[2] = "setAttributeType"; + break; + } + case 2: { + arrobject = arrobject2; + arrobject2[2] = "setName"; + break; + } + case 3: { + arrobject = arrobject2; + arrobject2[2] = "setUUID"; + break; + } + } + throw new IllegalArgumentException(String.format("Argument for @Nonnull parameter '%s' of %s.%s must not be null", arrobject)); + } + + public double getAmount() { + return this.data.getDouble("Amount", 0.0); + } + + public void setAmount(double amount) { + this.data.put("Amount", (Object) amount); + } + + public Operation getOperation() { + return Operation.fromId(this.data.getInteger("Operation", 0)); + } + + public void setOperation(@Nonnull Operation operation) { + if (operation == null) { + Attribute.$$$reportNull$$$0(0); + } + Preconditions.checkNotNull((Object) ((Object) operation), (Object) "operation cannot be NULL."); + this.data.put("Operation", (Object) operation.getId()); + } + + public AttributeType getAttributeType() { + return AttributeType.fromId(this.data.getString("AttributeName", null)); + } + + public void setAttributeType(@Nonnull AttributeType type) { + if (type == null) { + Attribute.$$$reportNull$$$0(1); + } + Preconditions.checkNotNull((Object) type, (Object) "type cannot be NULL."); + this.data.put("AttributeName", (Object) type.getMinecraftId()); + } + + public String getName() { + return this.data.getString("Name", null); + } + + public void setName(@Nonnull String name) { + if (name == null) { + Attribute.$$$reportNull$$$0(2); + } + Preconditions.checkNotNull((Object) name, (Object) "name cannot be NULL."); + this.data.put("Name", (Object) name); + } + + public UUID getUUID() { + return new UUID(this.data.getLong("UUIDMost", null), this.data.getLong("UUIDLeast", null)); + } + + public void setUUID(@Nonnull UUID id) { + if (id == null) { + Attribute.$$$reportNull$$$0(3); + } + Preconditions.checkNotNull((Object) "id", (Object) "id cannot be NULL."); + this.data.put("UUIDLeast", (Object) id.getLeastSignificantBits()); + this.data.put("UUIDMost", (Object) id.getMostSignificantBits()); + } + + public static class Builder { + private double amount; + private Operation operation = Operation.ADD_NUMBER; + private AttributeType type; + private String name; + private UUID uuid; + + private Builder() { + } + + public Builder amount(double amount) { + this.amount = amount; + return this; + } + + public Builder operation(Operation operation) { + this.operation = operation; + return this; + } + + public Builder type(AttributeType type) { + this.type = type; + return this; + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + public Attribute build() { + return new Attribute(this); + } + } + } + + public static class AttributeType { + private static ConcurrentMap LOOKUP = Maps.newConcurrentMap(); + public static final AttributeType GENERIC_MAX_HEALTH = new AttributeType("generic.maxHealth").register(); + public static final AttributeType GENERIC_FOLLOW_RANGE = new AttributeType("generic.followRange").register(); + public static final AttributeType GENERIC_ATTACK_DAMAGE = new AttributeType("generic.attackDamage").register(); + public static final AttributeType GENERIC_MOVEMENT_SPEED = new AttributeType("generic.movementSpeed").register(); + public static final AttributeType GENERIC_KNOCKBACK_RESISTANCE = new AttributeType("generic.knockbackResistance").register(); + private final String minecraftId; + + public AttributeType(String minecraftId) { + this.minecraftId = minecraftId; + } + + public static AttributeType fromId(String minecraftId) { + return (AttributeType) LOOKUP.get(minecraftId); + } + + public static Iterable values() { + return LOOKUP.values(); + } + + public String getMinecraftId() { + return this.minecraftId; + } + + public AttributeType register() { + AttributeType old = LOOKUP.putIfAbsent(this.minecraftId, this); + return old != null ? old : this; + } + } +} + diff --git a/Auctionhouse/src/main/java/me/recolance/globalutils/attribute/NbtFactory.java b/Auctionhouse/src/main/java/me/recolance/globalutils/attribute/NbtFactory.java new file mode 100644 index 0000000..2985970 --- /dev/null +++ b/Auctionhouse/src/main/java/me/recolance/globalutils/attribute/NbtFactory.java @@ -0,0 +1,750 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.google.common.base.Splitter + * com.google.common.collect.BiMap + * com.google.common.collect.HashBiMap + * com.google.common.collect.Lists + * com.google.common.collect.MapMaker + * com.google.common.io.Closeables + * com.google.common.io.InputSupplier + * com.google.common.io.OutputSupplier + * com.google.common.primitives.Primitives + * org.bukkit.Bukkit + * org.bukkit.Material + * org.bukkit.Server + * org.bukkit.inventory.ItemStack + */ +package me.recolance.globalutils.attribute; + +import com.google.common.base.Splitter; +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.Lists; +import com.google.common.collect.MapMaker; +import com.google.common.io.Closeables; +import com.google.common.io.InputSupplier; +import com.google.common.io.OutputSupplier; +import com.google.common.primitives.Primitives; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.inventory.ItemStack; + +import java.io.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; +import java.util.concurrent.ConcurrentMap; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class NbtFactory { + private static final BiMap> NBT_CLASS = HashBiMap.create(); + private static final BiMap NBT_ENUM = HashBiMap.create(); + private static NbtFactory INSTANCE; + private final Field[] DATA_FIELD = new Field[12]; + private Class BASE_CLASS; + private Class COMPOUND_CLASS; + private Class STREAM_TOOLS; + private Class READ_LIMITER_CLASS; + private Method NBT_CREATE_TAG; + private Method NBT_GET_TYPE; + private Field NBT_LIST_TYPE; + private Class CRAFT_STACK; + private Field CRAFT_HANDLE; + private Field STACK_TAG; + private LoadCompoundMethod LOAD_COMPOUND; + private Method SAVE_COMPOUND; + + private NbtFactory() { + if (this.BASE_CLASS == null) { + try { + ClassLoader loader = NbtFactory.class.getClassLoader(); + String packageName = this.getPackageName(); + Class offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); + this.COMPOUND_CLASS = NbtFactory.getMethod(0, 8, offlinePlayer, "getData", new Class[0]).getReturnType(); + this.BASE_CLASS = this.COMPOUND_CLASS.getSuperclass(); + this.NBT_GET_TYPE = NbtFactory.getMethod(0, 8, this.BASE_CLASS, "getTypeId", new Class[0]); + this.NBT_CREATE_TAG = NbtFactory.getMethod(8, 0, this.BASE_CLASS, "createTag", Byte.TYPE); + this.CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); + this.CRAFT_HANDLE = NbtFactory.getField(null, this.CRAFT_STACK, "handle"); + this.STACK_TAG = NbtFactory.getField(null, this.CRAFT_HANDLE.getType(), "tag"); + String nmsPackage = this.BASE_CLASS.getPackage().getName(); + this.initializeNMS(loader, nmsPackage); + this.LOAD_COMPOUND = this.READ_LIMITER_CLASS != null ? new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS) : new LoadMethodWorldUpdate(this.STREAM_TOOLS); + this.SAVE_COMPOUND = NbtFactory.getMethod(8, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, DataOutput.class); + } catch (ClassNotFoundException e) { + throw new IllegalStateException("Unable to find offline player.", e); + } + } + } + + private static NbtFactory get() { + if (INSTANCE == null) { + INSTANCE = new NbtFactory(); + } + return INSTANCE; + } + + public static NbtList createList(Object... content) { + return NbtFactory.createList(Arrays.asList(content)); + } + + public static NbtList createList(Iterable iterable) { + NbtFactory nbtFactory = NbtFactory.get(); + nbtFactory.getClass(); + NbtList list = nbtFactory.new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null)); + for (Object object : iterable) { + list.add(object); + } + return list; + } + + public static NbtCompound createCompound() { + NbtFactory nbtFactory = NbtFactory.get(); + nbtFactory.getClass(); + return nbtFactory.new NbtCompound(INSTANCE.createNbtTag(NbtType.TAG_COMPOUND, null)); + } + + public static NbtList fromList(Object nmsList) { + NbtFactory nbtFactory = NbtFactory.get(); + nbtFactory.getClass(); + return nbtFactory.new NbtList(nmsList); + } + + /* + * WARNING - Removed try catching itself - possible behaviour change. + */ + public static NbtCompound fromStream(InputSupplier stream, StreamOptions option) throws IOException { + NbtCompound nbtCompound; + block7: + { + boolean suppress; + InputStream input; + block6: + { + input = null; + DataInputStream data = null; + suppress = true; + try { + input = (InputStream) stream.getInput(); + data = new DataInputStream(new BufferedInputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPInputStream(input) : input)); + NbtCompound result = NbtFactory.fromCompound(NbtFactory.get().LOAD_COMPOUND.loadNbt(data)); + suppress = false; + nbtCompound = result; + if (data == null) break block6; + } catch (Throwable throwable) { + if (data != null) { + Closeables.close(data, (boolean) suppress); + } else if (input != null) { + Closeables.close((Closeable) input, (boolean) suppress); + } + throw throwable; + } + Closeables.close((Closeable) data, (boolean) suppress); + break block7; + } + if (input != null) { + Closeables.close((Closeable) input, (boolean) suppress); + } + } + return nbtCompound; + } + + /* + * WARNING - Removed try catching itself - possible behaviour change. + */ + public static void saveStream(NbtCompound source, OutputSupplier stream, StreamOptions option) throws IOException { + block7: + { + boolean suppress; + OutputStream output; + block6: + { + output = null; + DataOutputStream data = null; + suppress = true; + try { + output = (OutputStream) stream.getOutput(); + data = new DataOutputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output); + NbtFactory.invokeMethod(NbtFactory.get().SAVE_COMPOUND, null, source.getHandle(), data); + suppress = false; + if (data == null) break block6; + } catch (Throwable throwable) { + if (data != null) { + Closeables.close(data, (boolean) suppress); + } else if (output != null) { + Closeables.close((Closeable) output, (boolean) suppress); + } + throw throwable; + } + Closeables.close((Closeable) data, (boolean) suppress); + break block7; + } + if (output != null) { + Closeables.close((Closeable) output, (boolean) suppress); + } + } + } + + public static NbtCompound fromCompound(Object nmsCompound) { + NbtFactory nbtFactory = NbtFactory.get(); + nbtFactory.getClass(); + return nbtFactory.new NbtCompound(nmsCompound); + } + + public static void setItemTag(ItemStack stack, NbtCompound compound) { + NbtFactory.checkItemStack(stack); + Object nms = NbtFactory.getFieldValue(NbtFactory.get().CRAFT_HANDLE, (Object) stack); + NbtFactory.setFieldValue(NbtFactory.get().STACK_TAG, nms, compound.getHandle()); + } + + public static NbtCompound fromItemTag(ItemStack stack) { + NbtFactory.checkItemStack(stack); + Object nms = NbtFactory.getFieldValue(NbtFactory.get().CRAFT_HANDLE, (Object) stack); + Object tag = NbtFactory.getFieldValue(NbtFactory.get().STACK_TAG, nms); + if (tag == null) { + NbtCompound compound = NbtFactory.createCompound(); + NbtFactory.setItemTag(stack, compound); + return compound; + } + return NbtFactory.fromCompound(tag); + } + + public static ItemStack getCraftItemStack(ItemStack stack) { + if (stack == null || NbtFactory.get().CRAFT_STACK.isAssignableFrom(stack.getClass())) { + return stack; + } + try { + Constructor caller = NbtFactory.INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class); + caller.setAccessible(true); + return (ItemStack) caller.newInstance(new Object[]{stack}); + } catch (Exception e) { + throw new IllegalStateException("Unable to convert " + (Object) stack + " + to a CraftItemStack."); + } + } + + private static void checkItemStack(ItemStack stack) { + if (stack == null) { + throw new IllegalArgumentException("Stack cannot be NULL."); + } + if (!NbtFactory.get().CRAFT_STACK.isAssignableFrom(stack.getClass())) { + throw new IllegalArgumentException("Stack must be a CraftItemStack."); + } + if (stack.getType() == Material.AIR) { + throw new IllegalArgumentException("ItemStacks representing air cannot store NMS information."); + } + } + + private static Object invokeMethod(Method method, Object target, Object... params) { + try { + return method.invoke(target, params); + } catch (Exception e) { + throw new RuntimeException("Unable to invoke method " + method + " for " + target, e); + } + } + + private static void setFieldValue(Field field, Object target, Object value) { + try { + field.set(target, value); + } catch (Exception e) { + throw new RuntimeException("Unable to set " + field + " for " + target, e); + } + } + + private static Object getFieldValue(Field field, Object target) { + try { + return field.get(target); + } catch (Exception e) { + throw new RuntimeException("Unable to retrieve " + field + " for " + target, e); + } + } + + private static Method getMethod(int requireMod, int bannedMod, Class clazz, String methodName, Class... params) { + for (Method method : clazz.getDeclaredMethods()) { + if ((method.getModifiers() & requireMod) != requireMod || (method.getModifiers() & bannedMod) != 0 || methodName != null && !method.getName().equals(methodName) || !Arrays.equals(method.getParameterTypes(), params)) + continue; + method.setAccessible(true); + return method; + } + if (clazz.getSuperclass() != null) { + return NbtFactory.getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params); + } + throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params))); + } + + private static Field getField(Object instance, Class clazz, String fieldName) { + if (clazz == null) { + clazz = instance.getClass(); + } + for (Field field : clazz.getDeclaredFields()) { + if (!field.getName().equals(fieldName)) continue; + field.setAccessible(true); + return field; + } + if (clazz.getSuperclass() != null) { + return NbtFactory.getField(instance, clazz.getSuperclass(), fieldName); + } + throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance); + } + + private void initializeNMS(ClassLoader loader, String nmsPackage) { + try { + this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); + this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); + } catch (ClassNotFoundException classNotFoundException) { + // empty catch block + } + } + + private String getPackageName() { + String name; + Server server = Bukkit.getServer(); + String string = name = server != null ? server.getClass().getPackage().getName() : null; + if (name != null && name.contains("craftbukkit")) { + return name; + } + return "org.bukkit.craftbukkit.v1_7_R3"; + } + + private Map getDataMap(Object handle) { + return (Map) NbtFactory.getFieldValue(this.getDataField(NbtType.TAG_COMPOUND, handle), handle); + } + + private List getDataList(Object handle) { + return (List) NbtFactory.getFieldValue(this.getDataField(NbtType.TAG_LIST, handle), handle); + } + + private Object unwrapValue(Object value) { + if (value == null) { + return null; + } + if (value instanceof Wrapper) { + return ((Wrapper) value).getHandle(); + } + if (value instanceof List) { + throw new IllegalArgumentException("Can only insert a WrappedList."); + } + if (value instanceof Map) { + throw new IllegalArgumentException("Can only insert a WrappedCompound."); + } + return this.createNbtTag(this.getPrimitiveType(value), value); + } + + private Object wrapNative(Object nms) { + if (nms == null) { + return null; + } + if (this.BASE_CLASS.isAssignableFrom(nms.getClass())) { + NbtType type = this.getNbtType(nms); + switch (type) { + case TAG_COMPOUND: { + return new NbtCompound(nms); + } + case TAG_LIST: { + return new NbtList(nms); + } + } + return NbtFactory.getFieldValue(this.getDataField(type, nms), nms); + } + throw new IllegalArgumentException("Unexpected type: " + nms); + } + + private Object createNbtTag(NbtType type, Object value) { + Object tag = NbtFactory.invokeMethod(this.NBT_CREATE_TAG, null, (byte) type.id); + if (value != null) { + NbtFactory.setFieldValue(this.getDataField(type, tag), tag, value); + } + return tag; + } + + private Field getDataField(NbtType type, Object nms) { + if (this.DATA_FIELD[type.id] == null) { + this.DATA_FIELD[type.id] = NbtFactory.getField(nms, null, type.getFieldName()); + } + return this.DATA_FIELD[type.id]; + } + + private NbtType getNbtType(Object nms) { + byte type = (Byte) NbtFactory.invokeMethod(this.NBT_GET_TYPE, nms, new Object[0]); + return (NbtType) ((Object) NBT_ENUM.get((Object) type)); + } + + private NbtType getPrimitiveType(Object primitive) { + NbtType type = (NbtType) ((Object) NBT_ENUM.get(NBT_CLASS.inverse().get((Object) Primitives.unwrap(primitive.getClass())))); + if (type == null) { + throw new IllegalArgumentException(String.format("Illegal type: %s (%s)", primitive.getClass(), primitive)); + } + return type; + } + + private static enum NbtType { + TAG_END(0, Void.class), + TAG_BYTE(1, Byte.TYPE), + TAG_SHORT(2, Short.TYPE), + TAG_INT(3, Integer.TYPE), + TAG_LONG(4, Long.TYPE), + TAG_FLOAT(5, Float.TYPE), + TAG_DOUBLE(6, Double.TYPE), + TAG_BYTE_ARRAY(7, byte[].class), + TAG_INT_ARRAY(11, int[].class), + TAG_STRING(8, String.class), + TAG_LIST(9, List.class), + TAG_COMPOUND(10, Map.class); + + public final int id; + + private NbtType(int id, Class type) { + this.id = id; + NBT_CLASS.put(id, type); + NBT_ENUM.put(id, this); + } + + private String getFieldName() { + if (this == TAG_COMPOUND) { + return "map"; + } + if (this == TAG_LIST) { + return "list"; + } + return "data"; + } + } + + public static enum StreamOptions { + NO_COMPRESSION, + GZIP_COMPRESSION; + + } + + public static interface Wrapper { + public Object getHandle(); + } + + private static class LoadMethodSkinUpdate + extends LoadCompoundMethod { + private Object readLimiter; + + public LoadMethodSkinUpdate(Class streamClass, Class readLimiterClass) { + this.setMethod(NbtFactory.getMethod(8, 0, streamClass, null, new Class[]{DataInput.class, readLimiterClass})); + for (Field field : readLimiterClass.getDeclaredFields()) { + if (!readLimiterClass.isAssignableFrom(field.getType())) continue; + try { + this.readLimiter = field.get(null); + } catch (Exception e) { + throw new RuntimeException("Cannot retrieve read limiter.", e); + } + } + } + + @Override + public Object loadNbt(DataInput input) { + return NbtFactory.invokeMethod(this.staticMethod, null, new Object[]{input, this.readLimiter}); + } + } + + private static class LoadMethodWorldUpdate + extends LoadCompoundMethod { + public LoadMethodWorldUpdate(Class streamClass) { + this.setMethod(NbtFactory.getMethod(8, 0, streamClass, null, new Class[]{DataInput.class})); + } + + @Override + public Object loadNbt(DataInput input) { + return NbtFactory.invokeMethod(this.staticMethod, null, new Object[]{input}); + } + } + + private static abstract class LoadCompoundMethod { + protected Method staticMethod; + + private LoadCompoundMethod() { + } + + protected void setMethod(Method method) { + this.staticMethod = method; + this.staticMethod.setAccessible(true); + } + + public abstract Object loadNbt(DataInput var1); + } + + private class ConvertedList + extends AbstractList + implements Wrapper { + private final Object handle; + private final List original; + private final CachedNativeWrapper cache; + + public ConvertedList(Object handle, List original) { + this.cache = new CachedNativeWrapper(); + if (NbtFactory.this.NBT_LIST_TYPE == null) { + NbtFactory.this.NBT_LIST_TYPE = NbtFactory.getField(handle, null, "type"); + } + this.handle = handle; + this.original = original; + } + + protected Object wrapOutgoing(Object value) { + return this.cache.wrap(value); + } + + protected Object unwrapIncoming(Object wrapped) { + return NbtFactory.this.unwrapValue(wrapped); + } + + @Override + public Object get(int index) { + return this.wrapOutgoing(this.original.get(index)); + } + + @Override + public int size() { + return this.original.size(); + } + + @Override + public Object set(int index, Object element) { + return this.wrapOutgoing(this.original.set(index, this.unwrapIncoming(element))); + } + + @Override + public void add(int index, Object element) { + Object nbt = this.unwrapIncoming(element); + if (this.size() == 0) { + NbtFactory.setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, (byte) ((NbtFactory) NbtFactory.this).getNbtType((Object) nbt).id); + } + this.original.add(index, nbt); + } + + @Override + public Object remove(int index) { + return this.wrapOutgoing(this.original.remove(index)); + } + + @Override + public boolean remove(Object o) { + return this.original.remove(this.unwrapIncoming(o)); + } + + @Override + public Object getHandle() { + return this.handle; + } + } + + private class ConvertedMap + extends AbstractMap + implements Wrapper { + private final Object handle; + private final Map original; + private final CachedNativeWrapper cache; + + public ConvertedMap(Object handle, Map original) { + this.cache = new CachedNativeWrapper(); + this.handle = handle; + this.original = original; + } + + protected Object wrapOutgoing(Object value) { + return this.cache.wrap(value); + } + + protected Object unwrapIncoming(Object wrapped) { + return NbtFactory.this.unwrapValue(wrapped); + } + + @Override + public Object put(String key, Object value) { + return this.wrapOutgoing(this.original.put(key, this.unwrapIncoming(value))); + } + + @Override + public Object get(Object key) { + return this.wrapOutgoing(this.original.get(key)); + } + + @Override + public Object remove(Object key) { + return this.wrapOutgoing(this.original.remove(key)); + } + + @Override + public boolean containsKey(Object key) { + return this.original.containsKey(key); + } + + @Override + public Set> entrySet() { + return new AbstractSet>() { + + @Override + public boolean add(Entry e) { + String key = e.getKey(); + Object value = e.getValue(); + ConvertedMap.this.original.put(key, ConvertedMap.this.unwrapIncoming(value)); + return true; + } + + @Override + public int size() { + return ConvertedMap.this.original.size(); + } + + @Override + public Iterator> iterator() { + return ConvertedMap.this.iterator(); + } + }; + } + + private Iterator> iterator() { + final Iterator> proxy = this.original.entrySet().iterator(); + return new Iterator>() { + + @Override + public boolean hasNext() { + return proxy.hasNext(); + } + + @Override + public Entry next() { + Entry entry = (Entry) proxy.next(); + return new SimpleEntry((String) entry.getKey(), ConvertedMap.this.wrapOutgoing(entry.getValue())); + } + + @Override + public void remove() { + proxy.remove(); + } + }; + } + + @Override + public Object getHandle() { + return this.handle; + } + } + + private final class CachedNativeWrapper { + private final ConcurrentMap cache = new MapMaker().weakKeys().makeMap(); + + private CachedNativeWrapper() { + } + + public Object wrap(Object value) { + Object current = this.cache.get(value); + if (current == null && ((current = NbtFactory.this.wrapNative(value)) instanceof ConvertedMap || current instanceof ConvertedList)) { + this.cache.put(value, current); + } + return current; + } + } + + public final class NbtList + extends ConvertedList { + private NbtList(Object handle) { + super(handle, NbtFactory.this.getDataList(handle)); + } + } + + public final class NbtCompound + extends ConvertedMap { + private NbtCompound(Object handle) { + super(handle, NbtFactory.this.getDataMap(handle)); + } + + public Byte getByte(String key, Byte defaultValue) { + return this.containsKey(key) ? (Byte) this.get(key) : defaultValue; + } + + public Short getShort(String key, Short defaultValue) { + return this.containsKey(key) ? (Short) this.get(key) : defaultValue; + } + + public Integer getInteger(String key, Integer defaultValue) { + return this.containsKey(key) ? (Integer) this.get(key) : defaultValue; + } + + public Long getLong(String key, Long defaultValue) { + return this.containsKey(key) ? (Long) this.get(key) : defaultValue; + } + + public Float getFloat(String key, Float defaultValue) { + return this.containsKey(key) ? (Float) this.get(key) : defaultValue; + } + + public Double getDouble(String key, Double defaultValue) { + return this.containsKey(key) ? (Double) this.get(key) : defaultValue; + } + + public String getString(String key, String defaultValue) { + return this.containsKey(key) ? (String) this.get(key) : defaultValue; + } + + public byte[] getByteArray(String key, byte[] defaultValue) { + return this.containsKey(key) ? (byte[]) this.get(key) : defaultValue; + } + + public int[] getIntegerArray(String key, int[] defaultValue) { + return this.containsKey(key) ? (int[]) this.get(key) : defaultValue; + } + + public NbtList getList(String key, boolean createNew) { + NbtList list = (NbtList) this.get(key); + if (list == null && createNew) { + list = NbtFactory.createList(new Object[0]); + this.put(key, (Object) list); + } + return list; + } + + public NbtCompound getMap(String key, boolean createNew) { + return this.getMap(Arrays.asList(key), createNew); + } + + public NbtCompound putPath(String path, Object value) { + List entries = this.getPathElements(path); + NbtCompound map = this.getMap(entries.subList(0, entries.size() - 1), true); + map.put(entries.get(entries.size() - 1), value); + return this; + } + + public T getPath(String path) { + List entries = this.getPathElements(path); + NbtCompound map = this.getMap(entries.subList(0, entries.size() - 1), false); + if (map != null) { + return (T) map.get(entries.get(entries.size() - 1)); + } + return null; + } + + public void saveTo(OutputSupplier stream, StreamOptions option) throws IOException { + NbtFactory.saveStream(this, stream, option); + } + + private NbtCompound getMap(Iterable path, boolean createNew) { + NbtCompound current = this; + for (String entry : path) { + NbtCompound child = (NbtCompound) current.get(entry); + if (child == null) { + if (!createNew) { + return null; + } + child = NbtFactory.createCompound(); + current.put(entry, (Object) child); + } + current = child; + } + return current; + } + + private List getPathElements(String path) { + return Lists.newArrayList((Iterable) Splitter.on((String) ".").omitEmptyStrings().split((CharSequence) path)); + } + } +} + diff --git a/Auctionhouse/src/main/resources/config.yml b/Auctionhouse/src/main/resources/config.yml new file mode 100644 index 0000000..85afbe3 --- /dev/null +++ b/Auctionhouse/src/main/resources/config.yml @@ -0,0 +1,69 @@ +############################################ +# Your database information should go here.# +############################################ +sql: + host: '127.0.0.1' + port: '3306' + database: 'database' + user: 'user' + pass: 'password' + +auction: + #Listing price is the price it costs to list one item on the auction house. + listingPrice: 1000 + #Listing hours is the amount of hours a listing is active before being automatically cancelled and expired. + listingMinutes: 15 + #Unclaimed hours is the amount of hours a cancelled or expired listing can remain unretrieved for before being removed from the database. + unclaimedHours: 24 + #Disallow users in creative mode from listing me.astropvp.cratekeys.items. + preventCreativeSale: true + +menuText: + menuName: 'Auction House' + itemsYoureSelling: + name: '&e&lYour Auctions' + lore: + - '&7Click here to view all of the items you' + - '&7are currently selling on the auction.' + - '' + - '&e&l%selling% Item(s)' + collectExpired: + name: '&e&lCollection Bin' + lore: + - '&7Click here to view and collect all of the' + - '&7items you have cancelled or have expired.' + - '' + - '&e&l%expired% Item(s)' + previous: + name: '&e&l<- Previous Page' + lore: + - '&7View the previous page of auctions.' + refresh: + name: '&6&lRefresh Auctions' + lore: + - '&7Click to refresh the currently' + - '&7available auction listings.' + next: + name: '&e&lNext Page ->' + lore: + - '&7View the next page of auctions.' + howToSell: + name: '&e&lHow to Sell' + lore: + - '&7To list an item on the auction house, just hold' + - '&7the item in your hand and type &e/ah sell &7.' + bookButton: + name: '&e&lGuide' + lore: + - '&7This is the auction house, here you can' + - '&7list items for sale, and purchase items' + - '&7that others have listed for sale.' + - '' + - '&7The auction is also a great way to make' + - '&7money by selling farmable items other' + - '&7players may be interested in buying.' + - '' + - '&7All listings last for a max of &e15 minutes' + - '&7unsold items are sent to your collection bin.' + - '' + - '&7For more help, use &e/ah help!' \ No newline at end of file diff --git a/Auctionhouse/src/main/resources/plugin.yml b/Auctionhouse/src/main/resources/plugin.yml new file mode 100644 index 0000000..fd2888f --- /dev/null +++ b/Auctionhouse/src/main/resources/plugin.yml @@ -0,0 +1,10 @@ +name: CrankedAuction +main: me.recolance.auction.Auction +version: 1.1 +depend: [Vault, CrankedUtils] +commands: + ah: + aliases: [auction, auctionhouse, auc, bid, bids] +permissions: + auction.admin.expire: + default: op \ No newline at end of file diff --git a/Bosses/pom.xml b/Bosses/pom.xml new file mode 100644 index 0000000..88a747a --- /dev/null +++ b/Bosses/pom.xml @@ -0,0 +1,54 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Bosses + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + Keys + + + net.crankedpvp + LootTable + + + net.crankedpvp + Leaderboards + + + net.crankedpvp + Core + + + com.massivecraft + Factions + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + + \ No newline at end of file diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/BossAPI.java b/Bosses/src/main/java/net/crankedpvp/bosses/BossAPI.java new file mode 100644 index 0000000..899249d --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/BossAPI.java @@ -0,0 +1,57 @@ +package net.crankedpvp.bosses; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossPlaceCooldown; +import net.crankedpvp.bosses.struct.BossRegister; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import net.crankedpvp.crankedutils.utils.cache.CachedPlayer; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Optional; + +import static net.crankedpvp.bosses.struct.BossPlaceCooldown.BOSS_PLACE_COOLDOWN_NAME; + +public class BossAPI { + + public static boolean isBossEgg(ItemStack itemStack) { + if (ItemUtils.isAirOrNull(itemStack)) return false; + + NBTItem nbtItem = new NBTItem(itemStack); + + if (!nbtItem.hasKey("cosmicData")) return false; + return nbtItem.getString("cosmicData").equals("boss-egg"); + } + + public static boolean isBossEgg(NBTItem nbtItem) { + if (!nbtItem.hasKey("cosmicData")) return false; + return nbtItem.getString("cosmicData").equals("boss-egg"); + } + + public static Optional getBossFromEgg(ItemStack itemStack) { + if (ItemUtils.isAirOrNull(itemStack)) return Optional.empty(); + + NBTItem nbtItem = new NBTItem(itemStack); + + if (!isBossEgg(itemStack)) return Optional.empty(); + + return Optional.of(BossRegister.getInstance().getBossFromID(nbtItem.getString("boss-type"))); + } + + public static boolean isOnBossPlaceCooldown(Player player) { + CachedPlayer cachedPlayer = CacheManager.getInstance().getCachedPlayer(player); + + if (!cachedPlayer.hasCache(BOSS_PLACE_COOLDOWN_NAME)) { + return false; + } + + return ((BossPlaceCooldown) cachedPlayer.getCache(BOSS_PLACE_COOLDOWN_NAME)).isActive(); + } + + public static void registerBossPlaceCooldown(Player player) { + CachedPlayer cachedPlayer = CacheManager.getInstance().getCachedPlayer(player); + cachedPlayer.registerCache(new BossPlaceCooldown()); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/BossPlugin.java b/Bosses/src/main/java/net/crankedpvp/bosses/BossPlugin.java new file mode 100644 index 0000000..0a0cb59 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/BossPlugin.java @@ -0,0 +1,83 @@ +package net.crankedpvp.bosses; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.bosses.abilities.BroodMotherMinion; +import net.crankedpvp.bosses.abilities.NoPot; +import net.crankedpvp.bosses.commands.AdminCommand; +import net.crankedpvp.bosses.commands.BossesCommand; +import net.crankedpvp.bosses.language.LanguageHandler; +import net.crankedpvp.bosses.listeners.BossListeners; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossManager; +import net.crankedpvp.bosses.struct.BossRegister; +import net.crankedpvp.bosses.struct.config.BossConfigManager; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Locale; +import java.util.stream.Collectors; + +@Getter +public class BossPlugin extends JavaPlugin { + + @Getter + private static BossPlugin instance; + + private CommandManager commandManager; + private BossRegister bossRegister; + private BossManager bossManager; + private LanguageHandler languageHandler; + private BossConfigManager bossConfigManager; + + @Override + public void onEnable() { + instance = this; + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + + this.bossRegister = new BossRegister(this); + this.bossRegister.initialize(); + + this.bossManager = new BossManager(); + this.commandManager = new CommandManager(this); + + PluginUtils.registerListeners(this, + new BossListeners(this), + new NoPot(), + new BroodMotherMinion()); + + Bukkit.getScheduler().runTask(this, () -> { + this.bossConfigManager = new BossConfigManager(this); + this.bossConfigManager.setupFiles(); + + this.registerCommandParameters(); + this.registerCommandCompletion(); + + this.commandManager.register(new AdminCommand(this), new BossesCommand()); + }); + + + } + + @Override + public void onDisable() { + this.getBossManager().killAllAliveBosses(); + this.bossRegister.unregisterAll(); + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(Boss.class, argument -> { + Boss boss = BossRegister.getInstance().getBossFromID(String.valueOf(argument).toLowerCase(Locale.ROOT)); + return new TypeResult(boss, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#bosses", input -> { + return BossRegister.getInstance().getRegisteredBosses().values().stream().map(Boss::getID).collect(Collectors.toList()); + }); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherBlind.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherBlind.java new file mode 100644 index 0000000..211bb9a --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherBlind.java @@ -0,0 +1,35 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class BroodMotherBlind extends BossAbility { + @Override + public String getName() { + return "Brood Mother Blind"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + bossEntity.getNearbyEntities(6D, 6D, 6D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> { + loopPlayer.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 3 * 20, 9, true)); + }); + } + + @Override + public int getCooldownLength() { + return 7; + } + + @Override + public double procChance() { + return 15; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherMinion.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherMinion.java new file mode 100644 index 0000000..e9a5ec2 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherMinion.java @@ -0,0 +1,58 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Location; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.List; + +public class BroodMotherMinion extends BossAbility implements Listener { + + private List minions = new ArrayList<>(); + + @Override + public String getName() { + return "Brood Mother Minion"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + for(int i = 0; i < 3; i++) { + Location location = bossEntity.getLocation(); + LivingEntity minion = (LivingEntity) bossEntity.getWorld().spawnEntity(location, EntityType.CAVE_SPIDER); + minion.setRemoveWhenFarAway(true); + minion.setMaxHealth(100); + minion.setHealth(100); + minion.setCanPickupItems(false); + minion.setCustomNameVisible(true); + minion.setCustomName(CC.translate("&d&lBrood Minion")); + minion.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 4)); + minions.add(minion); + } + } + + @Override + public int getCooldownLength() { + return 15; + } + + @Override + public double procChance() { + return 10; + } + + @EventHandler + public void onMinionDeath(EntityDeathEvent event) { + if(minions.contains(event.getEntity())) event.getDrops().clear(); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherWeb.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherWeb.java new file mode 100644 index 0000000..98d28e4 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/BroodMotherWeb.java @@ -0,0 +1,59 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class BroodMotherWeb extends BossAbility { + + @Override + public String getName() { + return "Brood Mother Web"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + + bossEntity.getNearbyEntities(6D, 6D, 6D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> { + List locations = new ArrayList<>(); + for(Location location : Arrays.asList(player.getLocation(), player.getEyeLocation())) if(trySetupWebBlock(location)) locations.add(location); + BossPlugin.getInstance().getServer().getScheduler().runTaskLater(BossPlugin.getInstance(), () -> { + for(Location location : locations) tryRemoveWebBlock(location); + }, 3 * 20L); + }); + } + + private void tryRemoveWebBlock(Location location) { + if(location.getBlock().getType() == Material.WEB) + location.getBlock().setType(Material.AIR); + } + + private boolean trySetupWebBlock(Location location) { + if(location.getBlock().getType() == Material.AIR) { + location.getBlock().setType(Material.WEB); + return true; + } + return false; + } + + @Override + public int getCooldownLength() { + return 10; + } + + @Override + public double procChance() { + return 5; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/DamageTick.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/DamageTick.java new file mode 100644 index 0000000..1572069 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/DamageTick.java @@ -0,0 +1,38 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class DamageTick extends BossAbility { + @Override + public String getName() { + return "Damage Tick"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + bossEntity.getNearbyEntities(6D, 6D, 6D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> { + if(Math.random() < 0.15) { + loopPlayer.damage(6D); + loopPlayer.sendMessage(CC.translate(boss.getBossDisplayName().split("\\|")[0] + "&8- &c&l[TICKED: -6HP]")); + } + loopPlayer.damage(2D); + }); + } + + @Override + public int getCooldownLength() { + return 0; + } + + @Override + public double procChance() { + return 30; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Heal.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Heal.java new file mode 100644 index 0000000..3b247c6 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Heal.java @@ -0,0 +1,34 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class Heal extends BossAbility { + @Override + public String getName() { + return "Heal"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + bossEntity.setHealth(bossEntity.getHealth() + 20); + bossEntity.setMaxHealth(bossEntity.getMaxHealth() + 20); + bossEntity.getNearbyEntities(10D, 10D, 10D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> loopPlayer.sendMessage(CC.translate(boss.getBossDisplayName().split("\\|")[0] + "&8- &a&l[HEAL: +20HP]"))); + } + + @Override + public int getCooldownLength() { + return 10; + } + + @Override + public double procChance() { + return 25; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Knockback.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Knockback.java new file mode 100644 index 0000000..607db40 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Knockback.java @@ -0,0 +1,42 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.bosses.KingSlime; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class Knockback extends BossAbility { + + private Boss boss; + + @Override + public String getName() { + return "Knockback"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + this.boss = boss; + bossEntity.getNearbyEntities(8D, 8D, 8D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> { + loopPlayer.setVelocity(loopPlayer.getLocation().getDirection().multiply(-1.1)); + loopPlayer.playSound(loopPlayer.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 8.0F); + }); + } + + + + @Override + public int getCooldownLength() { + return (boss instanceof KingSlime) ? 7 : 12; + } + + @Override + public double procChance() { + return (boss instanceof KingSlime) ? 40 : 20; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Launch.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Launch.java new file mode 100644 index 0000000..4e94418 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Launch.java @@ -0,0 +1,37 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class Launch extends BossAbility { + @Override + public String getName() { + return "Launch"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + bossEntity.getNearbyEntities(6D, 6D, 6D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> { + Location loc = loopPlayer.getLocation().add(0.0, 6.0, 0.0); + loopPlayer.setVelocity(loopPlayer.getVelocity().add(loopPlayer.getLocation().toVector().subtract(loc.toVector()).normalize().multiply(3))); + loopPlayer.playSound(loopPlayer.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 4.0F); + }); + } + + @Override + public int getCooldownLength() { + return 15; + } + + @Override + public double procChance() { + return 20; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/LightningStrike.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/LightningStrike.java new file mode 100644 index 0000000..a44736b --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/LightningStrike.java @@ -0,0 +1,34 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class LightningStrike extends BossAbility { + @Override + public String getName() { + return "Lightning Strike"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + bossEntity.getNearbyEntities(6D, 6D, 6D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> { + loopPlayer.getLocation().getWorld().strikeLightningEffect(loopPlayer.getLocation()); + }); + } + + @Override + public int getCooldownLength() { + return 3; + } + + @Override + public double procChance() { + return 12; + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/NoPot.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/NoPot.java new file mode 100644 index 0000000..a0ed6a8 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/NoPot.java @@ -0,0 +1,56 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PotionSplashEvent; + +import java.util.ArrayList; +import java.util.List; + +public class NoPot extends BossAbility implements Listener { + + private final List blockedFromUsingPotions = new ArrayList<>(); + + @Override + public String getName() { + return "No Pot"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity BossEntity, Player player) { + blockedFromUsingPotions.add(player); + TitleUtils.sendTitle(player, CC.translate("&c&lPOTIONS BLOCKED"), CC.translate("&7You cannot use potions for 5s"), 0, 2, 0); + BossPlugin.getInstance().getServer().getScheduler().runTaskLater(BossPlugin.getInstance(), () -> { + blockedFromUsingPotions.remove(player); + }, 5 * 20L); + } + + @Override + public int getCooldownLength() { + return 20; + } + + @Override + public double procChance() { + return 5; + } + + @EventHandler + public void onPotionSplashEvent(PotionSplashEvent event) { + if(!(event.getEntity().getShooter() instanceof Player)) return; + Player player = (Player) event.getEntity().getShooter(); + if(event.getPotion().getType() == EntityType.SPLASH_POTION) { + if(!blockedFromUsingPotions.contains(player)) return; + event.getEntity().remove(); + player.sendMessage(CC.translate("&c&l(!) &cYou cannot throw potions while blocked")); + } + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Pull.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Pull.java new file mode 100644 index 0000000..b238219 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Pull.java @@ -0,0 +1,35 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class Pull extends BossAbility { + @Override + public String getName() { + return "Pull"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + bossEntity.getNearbyEntities(6D, 6D, 6D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> { + loopPlayer.setVelocity(loopPlayer.getLocation().getDirection().multiply(1.2)); + loopPlayer.playSound(loopPlayer.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 2.0F); + }); + } + + @Override + public int getCooldownLength() { + return 7; + } + + @Override + public double procChance() { + return 50; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/ShootArrow.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/ShootArrow.java new file mode 100644 index 0000000..88ec1c2 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/ShootArrow.java @@ -0,0 +1,31 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class ShootArrow extends BossAbility { + @Override + public String getName() { + return "Arrow"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + Arrow arrow = bossEntity.launchProjectile(Arrow.class); + arrow.setKnockbackStrength(arrow.getKnockbackStrength() * 2); + arrow.spigot().setDamage(arrow.spigot().getDamage() * 3); + } + + @Override + public int getCooldownLength() { + return 5; + } + + @Override + public double procChance() { + return 30; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Trap.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Trap.java new file mode 100644 index 0000000..becb21e --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/Trap.java @@ -0,0 +1,72 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.interfaces.TrapAttributes; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class Trap extends BossAbility { + + private Boss boss; + @Override + public String getName() { + return "Trap Ability"; + } + + @Override + protected void abilityEffect(Boss boss, LivingEntity bossEntity, Player player) { + this.boss = boss; + + String subTitle = getSubTitle(); + double tickDamage = getTickDamage(); + + bossEntity.getNearbyEntities(6D, 6D, 6D).stream() + .filter(entity -> entity instanceof Player) + .map(entity -> (Player)entity) + .forEach(loopPlayer -> { + loopPlayer.setWalkSpeed(0F); + loopPlayer.damage(tickDamage); + + //loopPlayer.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, 200)); + //PotionEffectUtils.addPotionEffect(loopPlayer, PotionEffectType.JUMP, Integer.MAX_VALUE, "TrapBossEffect", 5); + + loopPlayer.playSound(loopPlayer.getLocation(), Sound.PISTON_RETRACT, 2.0F, 3.0F); + + TitleUtils.sendTitle(loopPlayer, CC.translate("&c&lTRAPPED"), CC.translate("&7" + subTitle), 0, 4, 0); + + BossPlugin.getInstance().getServer().getScheduler().runTaskLater(BossPlugin.getInstance(), () -> { + loopPlayer.setWalkSpeed(0.2F); + loopPlayer.damage(tickDamage); + }, 5 * 20L); + }); + + } + + private String getSubTitle() { + if(!(boss instanceof TrapAttributes)) return "You have been trapped"; + TrapAttributes trapAttributes = ((TrapAttributes)boss); + if(trapAttributes.getSubTitle() == null) return "You have been trapped"; + return trapAttributes.getSubTitle(); + } + + private double getTickDamage() { + if(!(boss instanceof TrapAttributes)) return 1; + return ((TrapAttributes)boss).getTickDamage(); + } + + @Override + public int getCooldownLength() { + if(!(boss instanceof TrapAttributes)) return 1; + return ((TrapAttributes)boss).getCooldownLength(); + } + + @Override + public double procChance() { + return 10; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/abilities/TreasureGoblinLootDrop.java b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/TreasureGoblinLootDrop.java new file mode 100644 index 0000000..8f477b5 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/abilities/TreasureGoblinLootDrop.java @@ -0,0 +1,36 @@ +package net.crankedpvp.bosses.abilities; + +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossAbility; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + + +public class TreasureGoblinLootDrop extends BossAbility { + @Override + public final String getName() { + return "Treasure Goblin Drop"; + } + + @Override + protected void abilityEffect(final Boss boss, final LivingEntity bossEntity, final Player player) { + final World world = bossEntity.getWorld(); + final Location bossLocation = bossEntity.getLocation(); + //TODO: fix this + //final ItemStack itemStack = CrankedCrateKeysAPI.getRandomItem(CrankedCrateKeysPlugin.getInstance().getCrateLootManager().getCachedCrateLoot().get(CrateType.RARE_KEY)); + //world.dropItem(bossLocation, itemStack); + } + + @Override + public final int getCooldownLength() { + return 0; + } + + @Override + public final double procChance() { + return 100; + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/BroodMother.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/BroodMother.java new file mode 100644 index 0000000..9661275 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/BroodMother.java @@ -0,0 +1,152 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class BroodMother extends Boss implements Incrementable { + @Override + public String getName() { + return "Brood Mother"; + } + + @Override + public String getBossDisplayName() { + return "&5&lBrood Mother &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&5&lBrood Mother"; + } + + @Override + public BossGear getBossGear() { + return null; + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&5&lLORE", + "&7&oA profound spider lost from", + "&7&oits counterparts in the cavern", + "&7&olayer of the Cosmoverse.", + "&7&oAlthough, it's still a fighter..", + "", + "&5&lINFO", + " &f• Difficulty: &e&lMEDIUM", + " &f• Warzone Only: &c&lFALSE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 52; + } + + @Override + public Sound getSpawnSound() { + return Sound.SPIDER_WALK; + } + + @Override + public Sound getDeathSound() { + return Sound.SPIDER_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2, true, false)); + } + + @Override + public EntityType getEntityType() { + return EntityType.SPIDER; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.MYTHIC_KEY; + } + + @Override + public int getRewardAmount() { + return 5; + } + + @Override + public double getMaxHealth() { + return 500.0D; + } + + @Override + public boolean showDeathMessage() { + return false; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_3_PLAYERS; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(250) + .incomingDamageDecrease(5) + .abilities(Arrays.asList(BossAbilities.BROOD_MOTHER_BLIND, BossAbilities.BROOD_MOTHER_MINION, BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(500) + .incomingDamageDecrease(10) + .abilities(Arrays.asList(BossAbilities.BROOD_MOTHER_BLIND, BossAbilities.PULL, BossAbilities.DAMAGE_TICK, BossAbilities.BROOD_MOTHER_MINION)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1000) + .incomingDamageDecrease(15) + .abilities(Arrays.asList(BossAbilities.BROOD_MOTHER_BLIND, BossAbilities.BROOD_MOTHER_WEB, BossAbilities.BROOD_MOTHER_MINION, BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Cerberus.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Cerberus.java new file mode 100644 index 0000000..beaa081 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Cerberus.java @@ -0,0 +1,206 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.interfaces.TrapAttributes; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Skeleton; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class Cerberus extends Boss implements TrapAttributes, Incrementable { + + @Override + public String getName() { + return "Cerberus"; + } + + @Override + public String getBossDisplayName() { + return "&6&lCerberus &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&6&lCerberus &8(&4Admin Only&8)"; + } + + @Override + public BossGear getBossGear() { + return BossGear.builder() + .helmet(new ItemBuilder(SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDdjYTc4ODNiMWI5YjJiYjU4OGUxYTcxZDMzYjI5MjNiN2M3OTI2ZGZiYTZkYjEzNDE0MzM5OTYxMTM2ZmRkOCJ9fX0="))) + .weapon(new ItemBuilder(Material.DIAMOND_SWORD).addEnchantment(Enchantment.DAMAGE_ALL, 5)) + .chestplate(new ItemBuilder(Material.LEATHER_CHESTPLATE).setLeatherArmorColor(Color.RED).setGlowing()) + .leggings(new ItemBuilder(Material.LEATHER_LEGGINGS).setLeatherArmorColor(Color.RED).setGlowing()) + .boots(new ItemBuilder(Material.LEATHER_BOOTS).setLeatherArmorColor(Color.RED).setGlowing()) + .build(); + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&6&lLORE", + "&7&oAn allegedly impossible boss", + "&7&ofrom early 2018... are you able", + "&7&oto defeat it now? Or will it", + "&7&ostill rule the world...?", + "", + "&6&lINFO", + " &f• Difficulty: &4&lEXTREME", + " &f• Warzone Only: &a&lTRUE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 67; + } + + @Override + public Sound getSpawnSound() { + return Sound.WITHER_SPAWN; + } + + @Override + public Sound getDeathSound() { + return Sound.WITHER_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 4, true, false), + new PotionEffect(PotionEffectType.FAST_DIGGING, Integer.MAX_VALUE, 4, true, false) + ); + } + + @Override + public EntityType getEntityType() { + return EntityType.SKELETON; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.SEASON_KEY; + } + + @Override + public int getRewardAmount() { + return 5; + } + + @Override + public double getMaxHealth() { + return 1000.0D; + } + + @Override + public boolean showDeathMessage() { + return true; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_3_PLAYERS; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(650) + .abilities(Arrays.asList( + BossAbilities.LIGHTNING_STRIKE, + BossAbilities.PULL, + BossAbilities.KNOCKBACK, + BossAbilities.DAMAGE_TICK, + BossAbilities.SHOOT_ARROW, + BossAbilities.LAUNCH + )) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1000) + .abilities(Arrays.asList( + BossAbilities.LIGHTNING_STRIKE, + BossAbilities.TRAP, + BossAbilities.PULL, + BossAbilities.KNOCKBACK, + BossAbilities.DAMAGE_TICK, + BossAbilities.SHOOT_ARROW, + BossAbilities.LAUNCH + )) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1500) + .incomingDamageDecrease(5) + .abilities(Arrays.asList( + BossAbilities.LIGHTNING_STRIKE, + BossAbilities.TRAP, + BossAbilities.PULL, + BossAbilities.KNOCKBACK, + BossAbilities.DAMAGE_TICK, + BossAbilities.SHOOT_ARROW, + BossAbilities.LAUNCH + )) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + ((Skeleton) livingEntity).setSkeletonType(Skeleton.SkeletonType.WITHER); + } + + + + @Override + public String getSubTitle() { + return "&fCome to the &6Cerberus &flittle one..."; + } + + @Override + public double getTickDamage() { + return 4; + } + + @Override + public int getCooldownLength() { + return 18; + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/CrankedGuardian.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/CrankedGuardian.java new file mode 100644 index 0000000..e30b5bf --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/CrankedGuardian.java @@ -0,0 +1,174 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.interfaces.TrapAttributes; +import net.crankedpvp.bosses.interfaces.WarzoneOnly; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class CrankedGuardian extends Boss implements TrapAttributes, Incrementable, WarzoneOnly { + @Override + public String getName() { + return "Cranked Guardian"; + } + + @Override + public String getBossDisplayName() { + return "&e&lCranked Guardian &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&e&lCranked Guardian"; + } + + @Override + public BossGear getBossGear() { + return null; + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&e&lLORE", + "&7&oA lost golem from the village", + "&7&oof estupia, wandered into the", + "&7&olands of cranked and guards it", + "&7&owith his life to this very day..", + "", + "&e&lINFO", + " &f• Difficulty: &c&lHARD", + " &f• Warzone Only: &a&lTRUE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 56; + } + + @Override + public Sound getSpawnSound() { + return Sound.IRONGOLEM_WALK; + } + + @Override + public Sound getDeathSound() { + return Sound.IRONGOLEM_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 4, true, false), + new PotionEffect(PotionEffectType.FAST_DIGGING, Integer.MAX_VALUE, 4, true, false) + ); + } + + @Override + public EntityType getEntityType() { + return EntityType.IRON_GOLEM; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.SEASON_KEY; + } + + @Override + public int getRewardAmount() { + return 2; + } + + @Override + public double getMaxHealth() { + return 350.0D; + } + + @Override + public boolean showDeathMessage() { + return true; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_3_PLAYERS; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(250) + .incomingDamageDecrease(5) + .abilities(Arrays.asList(BossAbilities.DAMAGE_TICK, BossAbilities.LIGHTNING_STRIKE, BossAbilities.LAUNCH)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(500) + .incomingDamageDecrease(5) + .abilities(Arrays.asList(BossAbilities.KNOCKBACK, BossAbilities.DAMAGE_TICK, BossAbilities.LIGHTNING_STRIKE, BossAbilities.SHOOT_ARROW)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1000) + .incomingDamageDecrease(5) + .abilities(Arrays.asList(BossAbilities.TRAP, BossAbilities.PULL, BossAbilities.KNOCKBACK, BossAbilities.DAMAGE_TICK, BossAbilities.LIGHTNING_STRIKE, BossAbilities.SHOOT_ARROW, BossAbilities.LAUNCH)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + + } + + + + @Override + public String getSubTitle() { + return "The cranked guardian has trapped you"; + } + + @Override + public double getTickDamage() { + return 3; + } + + @Override + public int getCooldownLength() { + return 15; + } + + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Cranker.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Cranker.java new file mode 100644 index 0000000..19d8073 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Cranker.java @@ -0,0 +1,205 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.interfaces.TrapAttributes; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Skeleton; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class Cranker extends Boss implements TrapAttributes, Incrementable { + @Override + public String getName() { + return "Cranker"; + } + + @Override + public String getBossDisplayName() { + return "&4&lCranker &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&c&ki&4✧&c&ki&r &4&lCranker &c&ki&4✧&c&ki&r"; + } + + @Override + public BossGear getBossGear() { + return BossGear.builder() + .helmet(new ItemBuilder(SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDdjYTc4ODNiMWI5YjJiYjU4OGUxYTcxZDMzYjI5MjNiN2M3OTI2ZGZiYTZkYjEzNDE0MzM5OTYxMTM2ZmRkOCJ9fX0="))) + .weapon(new ItemBuilder(Material.DIAMOND_SWORD).addEnchantment(Enchantment.DAMAGE_ALL, 5)) + .chestplate(new ItemBuilder(Material.LEATHER_CHESTPLATE).setLeatherArmorColor(Color.RED).setGlowing()) + .leggings(new ItemBuilder(Material.LEATHER_LEGGINGS).setLeatherArmorColor(Color.RED).setGlowing()) + .boots(new ItemBuilder(Material.LEATHER_BOOTS).setLeatherArmorColor(Color.RED).setGlowing()) + .build(); + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&4&lLORE", + "&7&oAn allegedly impossible boss", + "&7&ofrom early 2018... are you able", + "&7&oto defeat it now? Or will it", + "&7&ostill rule the world...?", + "", + "&4&lINFO", + " &f• Difficulty: &4&lEXTREME", + " &f• Warzone Only: &a&lTRUE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 67; + } + + @Override + public Sound getSpawnSound() { + return Sound.WITHER_SPAWN; + } + + @Override + public Sound getDeathSound() { + return Sound.WITHER_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 4, true, false), + new PotionEffect(PotionEffectType.FAST_DIGGING, Integer.MAX_VALUE, 4, true, false) + ); + } + + @Override + public EntityType getEntityType() { + return EntityType.SKELETON; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.SEASON_KEY; + } + + @Override + public int getRewardAmount() { + return 5; + } + + @Override + public double getMaxHealth() { + return 1000.0D; + } + + @Override + public boolean showDeathMessage() { + return true; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_3_PLAYERS; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(650) + .abilities(Arrays.asList( + BossAbilities.LIGHTNING_STRIKE, + BossAbilities.PULL, + BossAbilities.KNOCKBACK, + BossAbilities.DAMAGE_TICK, + BossAbilities.SHOOT_ARROW, + BossAbilities.LAUNCH + )) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1000) + .abilities(Arrays.asList( + BossAbilities.LIGHTNING_STRIKE, + BossAbilities.TRAP, + BossAbilities.PULL, + BossAbilities.KNOCKBACK, + BossAbilities.DAMAGE_TICK, + BossAbilities.SHOOT_ARROW, + BossAbilities.LAUNCH + )) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1500) + .incomingDamageDecrease(5) + .abilities(Arrays.asList( + BossAbilities.LIGHTNING_STRIKE, + BossAbilities.TRAP, + BossAbilities.PULL, + BossAbilities.KNOCKBACK, + BossAbilities.DAMAGE_TICK, + BossAbilities.SHOOT_ARROW, + BossAbilities.LAUNCH + )) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + ((Skeleton) livingEntity).setSkeletonType(Skeleton.SkeletonType.WITHER); + } + + + + @Override + public String getSubTitle() { + return "Your &csoul &7is mine... love, &4Cranker"; + } + + @Override + public double getTickDamage() { + return 4; + } + + @Override + public int getCooldownLength() { + return 18; + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/CrazedWerewolf.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/CrazedWerewolf.java new file mode 100644 index 0000000..7830b85 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/CrazedWerewolf.java @@ -0,0 +1,155 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Wolf; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class CrazedWerewolf extends Boss implements Incrementable { + @Override + public String getName() { + return "Crazed Werewolf"; + } + + @Override + public String getBossDisplayName() { + return "&b&lCrazed Werewolf &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&b&lCrazed Werewolf Spawn Egg"; + } + + @Override + public BossGear getBossGear() { + return null; + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&b&lLORE", + "&7&oA werewolf would usually stay with", + "&7&oit's pack, with it's family..", + "&7&oUnless it was crazy, and had unusual", + "&7&oideas and intentions...", + "", + "&b&lINFO", + " &f• Difficulty: &a&lEASY", + " &f• Warzone Only: &c&lFALSE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 95; + } + + @Override + public Sound getSpawnSound() { + return Sound.WOLF_BARK; + } + + @Override + public Sound getDeathSound() { + return Sound.WOLF_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2, true, false)); + } + + @Override + public EntityType getEntityType() { + return EntityType.WOLF; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.MYTHIC_KEY; + } + + @Override + public int getRewardAmount() { + return 3; + } + + @Override + public double getMaxHealth() { + return 300.0D; + } + + @Override + public boolean showDeathMessage() { + return false; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_PLAYER; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(30) + .incomingDamageDecrease(5) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(60) + .incomingDamageDecrease(10) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(90) + .incomingDamageDecrease(15) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + ((Wolf) livingEntity).setAngry(true); + } + + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/FireLord.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/FireLord.java new file mode 100644 index 0000000..b1c950d --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/FireLord.java @@ -0,0 +1,153 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class FireLord extends Boss implements Incrementable { + @Override + public String getName() { + return "Fire Lord"; + } + + @Override + public String getBossDisplayName() { + return "&6&lFire Lord &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&6&lFire Lord Spawn Egg"; + } + + @Override + public BossGear getBossGear() { + return null; + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&6&lLORE", + "&7&oHow did the fire lord escape", + "&7&othe nether? Who knows, but it", + "&7&odoesn't matter.. it's here now.", + "", + "&6&lINFO", + " &f• Difficulty: &a&lEASY", + " &f• Warzone Only: &c&lFALSE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 61; + } + + @Override + public Sound getSpawnSound() { + return Sound.BLAZE_BREATH; + } + + @Override + public Sound getDeathSound() { + return Sound.BLAZE_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 1, true, false)); + } + + @Override + public EntityType getEntityType() { + return EntityType.BLAZE; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.MYTHIC_KEY; + } + + @Override + public int getRewardAmount() { + return 3; + } + + @Override + public double getMaxHealth() { + return 350.0D; + } + + @Override + public boolean showDeathMessage() { + return false; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_PLAYER; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(30) + .incomingDamageDecrease(5) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(60) + .incomingDamageDecrease(10) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(90) + .incomingDamageDecrease(15) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + + } + + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Gauntlet.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Gauntlet.java new file mode 100644 index 0000000..b531359 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Gauntlet.java @@ -0,0 +1,180 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.interfaces.TrapAttributes; +import net.crankedpvp.bosses.interfaces.WarzoneOnly; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class Gauntlet extends Boss implements TrapAttributes, Incrementable, WarzoneOnly { + @Override + public String getName() { + return "Gauntlet"; + } + + @Override + public String getBossDisplayName() { + return "&6&lThe Gauntlet &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&6&lThe Gauntlet"; + } + + @Override + public BossGear getBossGear() { + return BossGear.builder() + .weapon(new ItemBuilder(Material.GOLD_AXE).setGlowing()) + .helmet(new ItemBuilder(Material.STAINED_GLASS, 1, DyeColor.RED.getData()).setGlowing()) + .chestplate(new ItemBuilder(Material.LEATHER_CHESTPLATE).setLeatherArmorColor(Color.GRAY).setGlowing()) + .leggings(new ItemBuilder(Material.LEATHER_LEGGINGS).setLeatherArmorColor(Color.GRAY).setGlowing()) + .boots(new ItemBuilder(Material.LEATHER_BOOTS).setLeatherArmorColor(Color.GRAY).setGlowing()) + .build(); + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&6&lLORE", + "&7&oIt's no longer just a glove.", + "&7&oThis is THE gauntlet. Good luck", + "&7&ofighting him, you'll need it.", + "&7&oThe gauntlet awakens...", + "", + "&6&lINFO", + " &f• Difficulty: &c&lHARD", + " &f• Warzone Only: &a&lTRUE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 54; + } + + @Override + public Sound getSpawnSound() { + return Sound.ZOMBIE_WOODBREAK; + } + + @Override + public Sound getDeathSound() { + return Sound.ZOMBIE_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 3, true, false)); + } + + @Override + public EntityType getEntityType() { + return EntityType.ZOMBIE; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.SEASON_KEY; + } + + @Override + public int getRewardAmount() { + return 2; + } + + @Override + public double getMaxHealth() { + return 1000.0D; + } + + @Override + public boolean showDeathMessage() { + return true; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_3_PLAYERS; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(650) + .incomingDamageDecrease(20) + .abilities(Arrays.asList(BossAbilities.LIGHTNING_STRIKE)) + + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(950) + .incomingDamageDecrease(25) + .abilities(Arrays.asList(BossAbilities.LIGHTNING_STRIKE, BossAbilities.TRAP, BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1400) + .incomingDamageDecrease(50) + .abilities(Arrays.asList(BossAbilities.LIGHTNING_STRIKE, BossAbilities.TRAP, BossAbilities.HEAL, BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + + } + + + @Override + public String getSubTitle() { + return "The gauntlet boss has trapped you"; + } + + @Override + public double getTickDamage() { + return 3; + } + + @Override + public int getCooldownLength() { + return 15; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/KingSlime.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/KingSlime.java new file mode 100644 index 0000000..c44f09f --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/KingSlime.java @@ -0,0 +1,161 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Slime; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class KingSlime extends Boss implements Incrementable { + @Override + public String getName() { + return "King Slime"; + } + + @Override + public String getBossDisplayName() { + return "&e&lKing Slime &8| &7{health}"; + } + + @Override + public String getSpawnEggName() { + return "&e&lKing Slime"; + } + + @Override + public BossGear getBossGear() { + return BossGear.builder() + .boots(new ItemBuilder(Material.DIAMOND_BOOTS)) + .leggings(new ItemBuilder(Material.DIAMOND_LEGGINGS)) + .chestplate(new ItemBuilder(Material.DIAMOND_CHESTPLATE)) + .helmet(new ItemBuilder(Material.DIAMOND_HELMET)) + .build(); + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&e&lLORE", + "&7&oAn enormous slime, rumored to be", + "&7&othe king of all slimes in the", + "&7&oCosmoverse. Apparently he has", + "&7&oanger issues. Be warned...", + "", + "&e&lINFO", + " &f• Difficulty: &e&lMEDIUM", + " &f• Warzone Only: &c&lFALSE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 55; + } + + @Override + public Sound getSpawnSound() { + return Sound.SLIME_WALK; + } + + @Override + public Sound getDeathSound() { + return Sound.SLIME_ATTACK; + } + + @Override + public List getEffects() { + return Collections.singletonList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false)); + } + + @Override + public EntityType getEntityType() { + return EntityType.SLIME; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.MYTHIC_KEY; + } + + @Override + public int getRewardAmount() { + return 5; + } + + @Override + public double getMaxHealth() { + return 2000.0D; + } + + @Override + public boolean showDeathMessage() { + return true; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_3_PLAYERS; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(250) + .incomingDamageDecrease(15) + .abilities(Collections.singletonList(BossAbilities.KNOCKBACK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(500) + .incomingDamageDecrease(30) + .abilities(Arrays.asList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1000) + .incomingDamageDecrease(50) + .abilities(Arrays.asList(BossAbilities.HEAL, BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + ((Slime)livingEntity).setSize(8); + } + + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/PlagueBloater.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/PlagueBloater.java new file mode 100644 index 0000000..5ee1a1a --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/PlagueBloater.java @@ -0,0 +1,177 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.interfaces.TrapAttributes; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class PlagueBloater extends Boss implements TrapAttributes, Incrementable { + @Override + public String getName() { + return "Plague Bloater"; + } + + @Override + public String getBossDisplayName() { + return "&2&lPlague Bloater &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&2&lPlague Bloater"; + } + + @Override + public BossGear getBossGear() { + return BossGear.builder() + .weapon(new ItemBuilder(Material.DIAMOND_AXE).addEnchantment(Enchantment.DAMAGE_ALL, 5).setGlowing()) + .helmet(new ItemBuilder(Material.DIAMOND_HELMET).setGlowing()) + .chestplate(new ItemBuilder(Material.DIAMOND_CHESTPLATE).setGlowing()) + .leggings(new ItemBuilder(Material.DIAMOND_LEGGINGS).setGlowing()) + .boots(new ItemBuilder(Material.DIAMOND_BOOTS).setGlowing()) + .build(); + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&2&lLORE", + "&7&oThe host vessel of the most deadly", + "&7&oplague virus strain ever", + "&7&odiscovered. Wherever this", + "&7&oabomination goes, death soon", + "&7&ofollows. stay weary..", + "", + "&2&lDIFFICULTY", + "&2Ultimate" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 54; + } + + @Override + public Sound getSpawnSound() { + return Sound.ZOMBIE_WOODBREAK; + } + + @Override + public Sound getDeathSound() { + return Sound.ZOMBIE_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList( + new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2, true, false) + ); + } + + @Override + public EntityType getEntityType() { + return EntityType.GIANT; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.ABYSS_KEY; + } + + @Override + public int getRewardAmount() { + return 2; + } + + @Override + public double getMaxHealth() { + return 2500.0D; + } + + @Override + public boolean showDeathMessage() { + return true; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_3_PLAYERS; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(250) + .incomingDamageDecrease(10) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(500) + .incomingDamageDecrease(20) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(1000) + .incomingDamageDecrease(30) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + + } + + + + @Override + public String getSubTitle() { + return "The cranked guardian has trapped you"; + } + + @Override + public double getTickDamage() { + return 5; + } + + @Override + public int getCooldownLength() { + return 12; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Slimicle.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Slimicle.java new file mode 100644 index 0000000..5dec3b6 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Slimicle.java @@ -0,0 +1,158 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Slime; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class Slimicle extends Boss implements Incrementable { + @Override + public String getName() { + return "Slimicle"; + } + + @Override + public String getBossDisplayName() { + return "&a&lSlimicle &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&a&lSlimicle Spawn Egg"; + } + + @Override + public BossGear getBossGear() { + return BossGear.builder() + .build(); + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&a&lLORE", + "&7&oA child of the King Slime", + "&7&oWill it hold the same power", + "&7&oas it's ancestors? Let's hope", + "&7&oit doesn't...", + "", + "&a&lINFO", + " &f• Difficulty: &a&lEASY", + " &f• Warzone Only: &c&lFALSE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 55; + } + + @Override + public Sound getSpawnSound() { + return Sound.SLIME_WALK; + } + + @Override + public Sound getDeathSound() { + return Sound.SLIME_ATTACK; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 1, true, false)); + } + + @Override + public EntityType getEntityType() { + return EntityType.SLIME; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.MYTHIC_KEY; + } + + @Override + public int getRewardAmount() { + return 2; + } + + @Override + public double getMaxHealth() { + return 400.0D; + } + + @Override + public boolean showDeathMessage() { + return false; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_PLAYER; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(30) + .incomingDamageDecrease(5) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(60) + .incomingDamageDecrease(15) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(90) + .incomingDamageDecrease(30) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + ((Slime)livingEntity).setSize(4); + + } + + + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/TreasureGoblin.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/TreasureGoblin.java new file mode 100644 index 0000000..3348ff3 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/TreasureGoblin.java @@ -0,0 +1,150 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class TreasureGoblin extends Boss implements Incrementable { + @Override + public String getName() { + return "Treasure Goblin"; + } + + @Override + public String getBossDisplayName() { + return "&6&lTreasure Goblin"; + } + + @Override + public String getSpawnEggName() { + return "&6&lTreasure Goblin"; + } + + @Override + public BossGear getBossGear() { + return BossGear.builder() + .boots(new ItemBuilder(Material.GOLD_BOOTS)).build(); + + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&6&lLORE", + "&7&oTreasure Goblin.. back from", + "&7&othe dead, he's here scavenging", + "&7&ofor treasures his family left", + "&7&obehind in 2018.. take more from him", + "", + "&6&lINFO", + " &f• Difficulty: &6&lEVENT", + " &f• Warzone Only: &c&lFALSE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 62; + } + + @Override + public Sound getSpawnSound() { + return Sound.ZOMBIE_PIG_IDLE; + } + + @Override + public Sound getDeathSound() { + return Sound.ZOMBIE_PIG_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2, true, false)); + } + + @Override + public EntityType getEntityType() { + return EntityType.PIG_ZOMBIE; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.ABYSS_KEY; + } + + @Override + public int getRewardAmount() { + return 1; + } + + @Override + public double getMaxHealth() { + return 15.0D; + } + + @Override + public boolean showDeathMessage() { + return true; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_PLAYER; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .abilities(Arrays.asList(BossAbilities.TREASURE_GOBLIN_LOOT)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .abilities(Arrays.asList(BossAbilities.TREASURE_GOBLIN_LOOT)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .abilities(Arrays.asList(BossAbilities.TREASURE_GOBLIN_LOOT)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + } + + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Warlord.java b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Warlord.java new file mode 100644 index 0000000..a028756 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/bosses/Warlord.java @@ -0,0 +1,158 @@ +package net.crankedpvp.bosses.bosses; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class Warlord extends Boss implements Incrementable { + @Override + public String getName() { + return "Warlord"; + } + + @Override + public String getBossDisplayName() { + return "&c&lWarlord &8| {health}"; + } + + @Override + public String getSpawnEggName() { + return "&c&lWarlord Spawn Egg"; + } + + @Override + public BossGear getBossGear() { + return BossGear.builder() + .weapon(new ItemBuilder(Material.GOLD_AXE)) + .helmet(new ItemBuilder(Material.GOLD_HELMET).setGlowing()) + .build(); + } + + @Override + public List getSpawnEggLore() { + return Arrays.asList( + "&7This monster egg contains a", + "&cdangerous &7warzone boss.", + "", + "&c&lLORE", + "&7&oAlthough it seems easy at first,", + "&7&othe Warlord can be challenging", + "&7&oat times, don't underestimate it", + "", + "&c&lINFO", + " &f• Difficulty: &a&lEASY", + " &f• Warzone Only: &c&lFALSE" + ); + } + + @Override + public BossAttributes getAttributes() { + return BossAttributes.builder().build(); + } + + @Override + public Short getSpawnEggId() { + return 54; + } + + @Override + public Sound getSpawnSound() { + return Sound.ZOMBIE_WOODBREAK; + } + + @Override + public Sound getDeathSound() { + return Sound.ZOMBIE_DEATH; + } + + @Override + public List getEffects() { + return Arrays.asList(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, true, false), + new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 1, true, false)); + } + + @Override + public EntityType getEntityType() { + return EntityType.ZOMBIE; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public LootTableType getLootTableType() { + return LootTableType.MYTHIC_KEY; + } + + @Override + public int getRewardAmount() { + return 3; + } + + @Override + public double getMaxHealth() { + return 250.0D; + } + + @Override + public boolean showDeathMessage() { + return false; + } + + @Override + public BossRewardSystem getBossRewardSystem() { + return BossRewardSystem.GIVE_TO_TOP_PLAYER; + } + + @Override + public boolean showsInGui() { + return true; + } + + @Override + protected BossPhaseInfo getPhaseOne() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(30) + .incomingDamageDecrease(5) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseTwo() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(60) + .incomingDamageDecrease(10) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected BossPhaseInfo getPhaseThree() { + return BossPhaseInfo.builder() + .outgoingDamageIncrease(90) + .incomingDamageDecrease(15) + .abilities(Collections.singletonList(BossAbilities.DAMAGE_TICK)) + .build(); + } + + @Override + protected void afterSpawn(LivingEntity livingEntity) { + + } + + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/commands/AdminCommand.java b/Bosses/src/main/java/net/crankedpvp/bosses/commands/AdminCommand.java new file mode 100644 index 0000000..5c09184 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/commands/AdminCommand.java @@ -0,0 +1,75 @@ +package net.crankedpvp.bosses.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.language.Language; +import net.crankedpvp.bosses.language.LanguageHandler; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.struct.BossManager; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Command("cbo") +@Alias({"cboss", "cbosses"}) +public class AdminCommand extends CommandBase { + + private final LanguageHandler languageHandler; + private BossPlugin plugin; + + + private final BossManager bossManager; + + public AdminCommand(BossPlugin plugin) { + this.bossManager = plugin.getBossManager(); + this.languageHandler = plugin.getLanguageHandler(); + this.plugin = plugin; + } + + @Default + @Permission("cranked.admin") + public void mainCommand(CommandSender sender) { + Language.CBO_COMMAND_HELP.send(sender); + } + + @SubCommand("reload") + @WrongUsage("&cUsage: /cbo reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + this.languageHandler.load(); + this.plugin.getBossConfigManager().reloadFiles(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } + + @SubCommand("egg") + @Permission("cranked.admin") + public void eggCommand(CommandSender sender, @Completion("#bosses") Boss boss, @Completion("#players") @Optional Player player) { + if (boss == null) { + return; + } + + ItemStack spawnEgg = boss.getSpawnEgg(); + + if (player != null) { + player.getInventory().addItem(spawnEgg); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), spawnEgg); + } + } + + @SubCommand("clear") + @Permission("cranked.admin") + public void clearCommand(CommandSender sender) { + this.bossManager.killAllAliveBosses(); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/commands/BossesCommand.java b/Bosses/src/main/java/net/crankedpvp/bosses/commands/BossesCommand.java new file mode 100644 index 0000000..2c5a6d0 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/commands/BossesCommand.java @@ -0,0 +1,23 @@ +package net.crankedpvp.bosses.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.bosses.inventory.BossesInventory; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("bosses") +public class BossesCommand extends CommandBase { + + @Default + public void mainCommand(CommandSender sender) { + if(!(sender instanceof Player)) return; + Player player = (Player)sender; + BossesInventory bossesInventory = new BossesInventory(); + bossesInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + +} \ No newline at end of file diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/events/BossDeathEvent.java b/Bosses/src/main/java/net/crankedpvp/bosses/events/BossDeathEvent.java new file mode 100644 index 0000000..570f79a --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/events/BossDeathEvent.java @@ -0,0 +1,34 @@ +package net.crankedpvp.bosses.events; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import net.crankedpvp.bosses.struct.Boss; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@Getter +@RequiredArgsConstructor +public class BossDeathEvent extends Event implements Cancellable { + + private final Boss boss; + private final LivingEntity entity; + private final Player Killer; + + @Setter + private boolean cancelled; + + private static final HandlerList handlers = new HandlerList(); + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/events/BossIncomingPlayerDamageEvent.java b/Bosses/src/main/java/net/crankedpvp/bosses/events/BossIncomingPlayerDamageEvent.java new file mode 100644 index 0000000..759b352 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/events/BossIncomingPlayerDamageEvent.java @@ -0,0 +1,37 @@ +package net.crankedpvp.bosses.events; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import net.crankedpvp.bosses.struct.Boss; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +@Getter +@RequiredArgsConstructor +public class BossIncomingPlayerDamageEvent extends Event implements Cancellable { + + private final Boss boss; + private final LivingEntity victim; + private final Player attacker; + private final EntityDamageByEntityEvent damageEvent; + + @Setter + private boolean cancelled; + + private static final HandlerList handlers = new HandlerList(); + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/events/BossOutgoingPlayerDamageEvent.java b/Bosses/src/main/java/net/crankedpvp/bosses/events/BossOutgoingPlayerDamageEvent.java new file mode 100644 index 0000000..b20b2f2 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/events/BossOutgoingPlayerDamageEvent.java @@ -0,0 +1,37 @@ +package net.crankedpvp.bosses.events; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import net.crankedpvp.bosses.struct.Boss; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +@Getter +@RequiredArgsConstructor +public class BossOutgoingPlayerDamageEvent extends Event implements Cancellable { + + private final Boss boss; + private final LivingEntity attacker; + private final Player victim; + private final EntityDamageByEntityEvent damageEvent; + + @Setter + private boolean cancelled; + + private static final HandlerList handlers = new HandlerList(); + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/events/BossSpawnEvent.java b/Bosses/src/main/java/net/crankedpvp/bosses/events/BossSpawnEvent.java new file mode 100644 index 0000000..ead7d90 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/events/BossSpawnEvent.java @@ -0,0 +1,32 @@ +package net.crankedpvp.bosses.events; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import net.crankedpvp.bosses.struct.Boss; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@Getter +@RequiredArgsConstructor +public class BossSpawnEvent extends Event implements Cancellable { + + private final Boss boss; + private final LivingEntity entity; + + @Setter + private boolean cancelled; + + private static final HandlerList handlers = new HandlerList(); + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/Incrementable.java b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/Incrementable.java new file mode 100644 index 0000000..d4b2110 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/Incrementable.java @@ -0,0 +1,4 @@ +package net.crankedpvp.bosses.interfaces; + +public interface Incrementable { +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/LootTableLoot.java b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/LootTableLoot.java new file mode 100644 index 0000000..2d73eac --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/LootTableLoot.java @@ -0,0 +1,8 @@ +package net.crankedpvp.bosses.interfaces; + +public interface LootTableLoot { + + // If a boss implements this interface it will give the loot inside the loot table as a reward + // instead of a crate key + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/Reloadable.java b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/Reloadable.java new file mode 100644 index 0000000..3c65b39 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/Reloadable.java @@ -0,0 +1,6 @@ +package net.crankedpvp.bosses.interfaces; + +public interface Reloadable { + + void reloadValues(); +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/TrapAttributes.java b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/TrapAttributes.java new file mode 100644 index 0000000..af391b5 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/TrapAttributes.java @@ -0,0 +1,9 @@ +package net.crankedpvp.bosses.interfaces; + +public interface TrapAttributes { + + String getSubTitle(); + double getTickDamage(); + int getCooldownLength(); + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/WarzoneOnly.java b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/WarzoneOnly.java new file mode 100644 index 0000000..0666503 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/interfaces/WarzoneOnly.java @@ -0,0 +1,4 @@ +package net.crankedpvp.bosses.interfaces; + +public interface WarzoneOnly { +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/inventory/BossesInventory.java b/Bosses/src/main/java/net/crankedpvp/bosses/inventory/BossesInventory.java new file mode 100644 index 0000000..4f8bf40 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/inventory/BossesInventory.java @@ -0,0 +1,69 @@ +package net.crankedpvp.bosses.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Collection; +import java.util.stream.Collectors; + +public class BossesInventory { + private final Gui bossesInventory; + + public Gui getUI() { + return this.bossesInventory; + } + + Collection bosses = BossPlugin.getInstance().getBossRegister().getRegisteredBosses().values(); + + public BossesInventory() { + this.bossesInventory = new Gui(6, "Cranked Bosses"); + this.bossesInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.bossesInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.bossesInventory.updateItem(6, 5, new GuiItem(createExitItem(), event -> event.getWhoClicked().closeInventory())); + this.bossesInventory.updateItem(1, 5, new GuiItem(createInformationItem())); + + + for(Boss boss : bosses.stream().filter(Boss::showsInGui).collect(Collectors.toList())) { + this.bossesInventory.addItem(new GuiItem(boss.getSpawnEgg(), event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) event.getWhoClicked().getInventory().addItem(boss.getSpawnEgg()); + })); + } + } + + private ItemStack createExitItem() { + ItemStack item = new ItemStack(Material.BED); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cExit Bosses menu")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createInformationItem() { + return new ItemBuilder(Material.BOOK, "&a&lCranked Bosses", + "&7Bosses are tough AI mobs that", + "&7can be fought by players to", + "&7obtain high-tier loot.", + "", + "&7Bosses can spawn in naturally", + "&7however you can also spawn them", + "&7in using boss spawn eggs as shown", + "&7in this inventory.") + .colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/language/Language.java b/Bosses/src/main/java/net/crankedpvp/bosses/language/Language.java new file mode 100644 index 0000000..094b2ab --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/language/Language.java @@ -0,0 +1,107 @@ +package net.crankedpvp.bosses.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + MAX_BOSSES, + + CBO_COMMAND_HELP, + + BOSS_DAMAGE_TITLE, + BOSS_DAMAGE_LINE, + SPAWN_BOSS_IN_WARZONE, + + ADMIN_RELOADING, + ADMIN_RELOADED, + + TOO_MANY_BOSSES, + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(Collection senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(Collection senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/language/LanguageHandler.java b/Bosses/src/main/java/net/crankedpvp/bosses/language/LanguageHandler.java new file mode 100644 index 0000000..d196291 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.bosses.language; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final JavaPlugin plugin; + + public LanguageHandler(JavaPlugin plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/listeners/BossListeners.java b/Bosses/src/main/java/net/crankedpvp/bosses/listeners/BossListeners.java new file mode 100644 index 0000000..2c58509 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/listeners/BossListeners.java @@ -0,0 +1,174 @@ +package net.crankedpvp.bosses.listeners; + +import net.crankedpvp.bosses.BossAPI; +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.events.BossDeathEvent; +import net.crankedpvp.bosses.events.BossIncomingPlayerDamageEvent; +import net.crankedpvp.bosses.events.BossOutgoingPlayerDamageEvent; +import net.crankedpvp.bosses.events.BossSpawnEvent; +import net.crankedpvp.bosses.interfaces.WarzoneOnly; +import net.crankedpvp.bosses.language.Language; +import net.crankedpvp.bosses.struct.*; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +public class BossListeners implements Listener { + + private final BossManager bossManager; + + public BossListeners(BossPlugin plugin) { + this.bossManager = plugin.getBossManager(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onBossIncomingDamage(BossIncomingPlayerDamageEvent event) { + LivingEntity bossEntity = event.getVictim(); + + event.getBoss().onIncomingDamage(event.getDamageEvent(), bossEntity, event.getAttacker()); + + double baseDamage = event.getDamageEvent().getFinalDamage(); + double damage = bossEntity.getHealth() - baseDamage >= 0 ? baseDamage : bossEntity.getHealth(); + + this.bossManager.updateDamageDealtToBossByPlayer(event.getVictim(), event.getAttacker(), damage); + event.getBoss().updateBossDisplayNameAndHealthDisplay(bossEntity, bossEntity.getHealth() - damage); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onBossOutgoingDamage(BossOutgoingPlayerDamageEvent event) { + event.getBoss().onOutgoingDamage(event.getDamageEvent(), event.getAttacker(), event.getVictim()); + } + + @EventHandler + public void onBossSpawn(BossSpawnEvent event) { + this.bossManager.addBossToCache(event.getEntity(), event.getBoss()); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onBossDeath(BossDeathEvent event) { + BossInfo bossInfo = this.bossManager.getBossInfo(event.getEntity()); + bossInfo.getBoss().handleBossDeath(event, bossInfo); + this.bossManager.removeBossFromCache(event.getEntity()); + for (BossAbility bossAbility : bossInfo.getBoss().getBossAbilities()) { + bossAbility.removeFromCooldownCache(event.getEntity()); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onBossEggClick(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + BossAPI.getBossFromEgg(event.getItem()).ifPresent(boss -> { + event.setCancelled(true); + Location clickedLocation = event.getClickedBlock().getLocation(); + if(boss instanceof WarzoneOnly) { + if (!WorldGuardUtils.getRegionName(clickedLocation).equals("spawn_warzone") || !clickedLocation.getWorld().getName().equals("world")) { + Language.SPAWN_BOSS_IN_WARZONE.send(event.getPlayer()); + return; + } + if (!FactionUtils.isWarZone(clickedLocation)) { + Language.SPAWN_BOSS_IN_WARZONE.send(event.getPlayer()); + return; + } + } + + if(!WorldGuardUtils.canPvPInRegion(clickedLocation)) { + Language.SPAWN_BOSS_IN_WARZONE.send(event.getPlayer()); + return; + } + + if(this.bossManager.getAliveBossesAmount() >= Integer.parseInt(Language.MAX_BOSSES.getValue())) { + Language.TOO_MANY_BOSSES.send(event.getPlayer()); + return; + } + + if (BossAPI.isOnBossPlaceCooldown(event.getPlayer())) { + event.getPlayer().sendMessage(CC.translate("&4&lBoss " + Arrow.arrow() + " &7You cannot place another boss egg for now")); + return; + } + + BossAPI.registerBossPlaceCooldown(event.getPlayer()); + + event.getPlayer().setItemInHand(ItemUtils.decreaseItemStackAmountByOne(event.getItem())); + boss.spawnBoss(event.getClickedBlock().getLocation().add(0.5, 1, 0.5)); + }); + } + + @EventHandler + public void onBossDeath(EntityDeathEvent event) { + if (!this.bossManager.isBoss(event.getEntity())) return; + event.getDrops().clear(); + Player killer = event.getEntity().getKiller(); + Boss boss = this.bossManager.getBoss(event.getEntity()); + BossDeathEvent bossDeathEvent = new BossDeathEvent(boss, event.getEntity(), killer); + Bukkit.getPluginManager().callEvent(bossDeathEvent); + } + + + @EventHandler + public void onBossDamage(EntityDamageEvent event) { + if (!this.bossManager.isBoss(event.getEntity())) return; + + LivingEntity entity = (LivingEntity) event.getEntity(); + Boss boss = this.bossManager.getBoss(entity); + BossAttributes attributes = boss.getAttributes(); + + if(attributes == null) return; + switch (event.getCause()) { + case FALL: + if(attributes.isImmuneToFallDamage()) event.setCancelled(true); + break; + case FIRE: + case LAVA: + if (attributes.isImmuneToFireDamage()) event.setCancelled(true); + break; + case MAGIC: + if (attributes.isImmuneToMagicDamage()) event.setCancelled(true); + break; + case PROJECTILE: + if (attributes.isImmuneToProjectileDamage()) event.setCancelled(true); + break; + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onBossDamagedByPlayer(EntityDamageByEntityEvent event) { + if (!this.bossManager.isBoss(event.getEntity())) return; + if (!(event.getDamager() instanceof Player)) return; + + if (event.isCancelled()) return; + + Player player = ((Player) event.getDamager()); + LivingEntity entity = (LivingEntity) event.getEntity(); + Boss boss = this.bossManager.getBoss(entity); + + BossIncomingPlayerDamageEvent bossIncomingPlayerDamageEvent = new BossIncomingPlayerDamageEvent(boss, entity, player, event); + Bukkit.getPluginManager().callEvent(bossIncomingPlayerDamageEvent); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onBossDamageToPlayer(EntityDamageByEntityEvent event) { + if (!this.bossManager.isBoss(event.getDamager())) return; + if (!(event.getEntity() instanceof Player)) return; + + Player player = ((Player) event.getEntity()); + LivingEntity entity = (LivingEntity) event.getDamager(); + Boss boss = this.bossManager.getBoss(entity); + + BossOutgoingPlayerDamageEvent bossOutgoingPlayerDamageEvent = new BossOutgoingPlayerDamageEvent(boss, entity, player, event); + Bukkit.getPluginManager().callEvent(bossOutgoingPlayerDamageEvent); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/Boss.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/Boss.java new file mode 100644 index 0000000..fed459e --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/Boss.java @@ -0,0 +1,263 @@ +package net.crankedpvp.bosses.struct; + +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.bosses.events.BossDeathEvent; +import net.crankedpvp.bosses.events.BossSpawnEvent; +import net.crankedpvp.bosses.interfaces.Incrementable; +import net.crankedpvp.bosses.interfaces.LootTableLoot; +import net.crankedpvp.bosses.language.Language; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.cratekeys.items.CrateKeyItem; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.*; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +public abstract class Boss implements Listener { + + @Getter + private final transient DamageHandler damageHandler; + private final transient EnumMap fightPhases; + private transient BossPhase previousPhase; + + protected Boss() { + this.damageHandler = CrankedUtils.instance.getDamageHandler(); + this.fightPhases = new EnumMap<>(BossPhase.class); + this.fightPhases.put(BossPhase.PHASE_ONE, this.getPhaseOne()); + this.fightPhases.put(BossPhase.PHASE_TWO, this.getPhaseTwo()); + this.fightPhases.put(BossPhase.PHASE_THREE, this.getPhaseThree()); + this.previousPhase = BossPhase.PHASE_ONE; + } + + public abstract String getName(); + + public abstract String getBossDisplayName(); + + public abstract String getSpawnEggName(); + + public abstract BossGear getBossGear(); + + public abstract List getSpawnEggLore(); + + public abstract BossAttributes getAttributes(); + + public abstract Short getSpawnEggId(); + + public abstract Sound getSpawnSound(); + + public abstract Sound getDeathSound(); + + public abstract List getEffects(); + + public abstract EntityType getEntityType(); + + public abstract boolean isBaby(); + + public abstract LootTableType getLootTableType(); + + public abstract int getRewardAmount(); + + public abstract double getMaxHealth(); + + public abstract boolean showDeathMessage(); + + public abstract BossRewardSystem getBossRewardSystem(); + + public abstract boolean showsInGui(); + + protected abstract BossPhaseInfo getPhaseOne(); + + protected abstract BossPhaseInfo getPhaseTwo(); + + protected abstract BossPhaseInfo getPhaseThree(); + + protected abstract void afterSpawn(LivingEntity livingEntity); + + public double chanceToGetReward() { + return 1; + } + + public void onIncomingDamage(EntityDamageByEntityEvent event, LivingEntity bossEntity, Player player) { + BossPhaseInfo bossPhaseInfo = this.fightPhases.get(this.getBossPhase(bossEntity)); + BossPhase bossPhase = this.getBossPhase(bossEntity); + + if (this.previousPhase != bossPhase) { + this.previousPhase = bossPhase; + for (PotionEffect potionEffect : bossPhaseInfo.getPotionEffects()) { + bossEntity.addPotionEffect(potionEffect); + } + } + + this.getDamageHandler().reduceDamage(bossPhaseInfo.getIncomingDamageDecrease(), event, this.getName()); + + for (BossAbilities ability : bossPhaseInfo.getAbilities()) { + ability.getAbilityInstance().procAbility(this, bossEntity, player); + } + } + + public void onOutgoingDamage(EntityDamageByEntityEvent event, LivingEntity bossEntity, Player player) { + BossPhaseInfo bossPhaseInfo = this.fightPhases.get(this.getBossPhase(bossEntity)); + + this.getDamageHandler().increaseDamage(bossPhaseInfo.getOutgoingDamageIncrease(), event, this.getName()); + } + + protected List getLootForRarity(LootTableType lootTableType) { + return LootTableAPI.getAllLootFromLootTable(lootTableType); + } + + public String getID() { + return this.getName().replace(" ", "").toLowerCase(Locale.ROOT); + } + + + public ItemStack getSpawnEgg() { + ItemStack itemStack = new ItemBuilder(Material.MONSTER_EGG) + .setDurability(this.getSpawnEggId()) + .setLore(this.getSpawnEggLore()) + .setName(this.getSpawnEggName()) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("cosmicData", "boss-egg"); + nbtItem.setString("boss-type", this.getID()); + return nbtItem.getItem(); + } + + public LivingEntity spawnBoss(Location spawnLocation) { + String[] disabledWorlds = new String[]{"world_outpost", "desert_world", "Desert", "world_routpost"}; + if(Arrays.stream(disabledWorlds).anyMatch(worldName -> worldName.equals(spawnLocation.getWorld().getName()))) { + System.out.println("Disabling boss spawn of boss: " + this.getName() + " at " + LocationUtils.locationToFancy(spawnLocation) + " due to being a disabled world"); + return null; + } + LivingEntity boss = (LivingEntity) spawnLocation.getWorld().spawnEntity(spawnLocation, this.getEntityType()); + + boss.setRemoveWhenFarAway(false); + boss.setMaxHealth(this.getMaxHealth()); + boss.setHealth(this.getMaxHealth()); + boss.setCanPickupItems(false); + boss.setCustomNameVisible(true); + this.updateBossDisplayNameAndHealthDisplay(boss, getMaxHealth()); + if(this.getBossGear() != null) this.getBossGear().applyArmorToBoss(boss); + + if (this.getEffects() != null) + this.getEffects().forEach(boss::addPotionEffect); + + if (this.getSpawnSound() != null) + spawnLocation.getWorld().playSound(spawnLocation, this.getSpawnSound(), 1, 1); + + + BossSpawnEvent bossSpawnEvent = new BossSpawnEvent(this, boss); + Bukkit.getPluginManager().callEvent(bossSpawnEvent); + + this.afterSpawn(boss); + return boss; + } + + public void giveLootToPlayer(final Player player, final LootTableType lootTableType) { + if (player == null) return; + + if (this instanceof LootTableLoot) { + for(int i = 0; i < this.getRewardAmount(); i++) { + if (Math.random() < chanceToGetReward()) { + final ItemStack itemStack = LootTableAPI.getRandomLootItem(lootTableType); + PlayerUtils.giveOrDropProtectedItem(player, itemStack, 5); + } + } + return; + } + + for(int i = 0; i < this.getRewardAmount(); i++) { + if (Math.random() < chanceToGetReward()) { + PlayerUtils.giveOrDropProtectedItem(player, CrateKeyItem.getItem(CrateKeyType.valueOf(lootTableType.name())), 5); + player.getLocation().getWorld().playSound(player.getLocation(), this.getDeathSound(), 1, 1); + } + } + } + + public void updateBossDisplayNameAndHealthDisplay(LivingEntity entity, double entityHealth) { + entity.setCustomName(CC.translate(this.getBossDisplayName().replace("{health}", this.getHealthString(entity, entityHealth)))); + } + + public void updateBossDisplayNameAndHealthDisplay(LivingEntity entity) { + entity.setCustomName(CC.translate(this.getBossDisplayName().replace("{health}", this.getHealthString(entity, entity.getHealth())))); + } + + public BossPhase getBossPhase(LivingEntity entity) { + double entityHealth = entity.getHealth(); + double entityMaxHealth = entity.getMaxHealth(); + return entityHealth > entityMaxHealth / 2 ? BossPhase.PHASE_ONE : entityHealth > entityMaxHealth / 4 ? BossPhase.PHASE_TWO : BossPhase.PHASE_THREE; + } + + private String getHealthString(LivingEntity entity, double entityHealth) { + double entityMaxHealth = this.getMaxHealth(); + ChatColor color = entityHealth > entityMaxHealth / 2 ? ChatColor.GREEN : entityHealth > entityMaxHealth / 4 ? ChatColor.GOLD : ChatColor.RED; + return color + "" + (int) entityHealth + "&8/&a" + (int) entityMaxHealth + "&r"; + } + + public void handleBossDeath(BossDeathEvent event, BossInfo bossInfo) { + if(event.getBoss() instanceof Incrementable) { + if(event.getKiller() != null) + LeaderboardsAPI.getPlayerStats(event.getKiller().getUniqueId()).incrementBossKills(); + } + switch (this.getBossRewardSystem()) { + case GIVE_TO_TOP_PLAYER: + if (this.showDeathMessage()) + Language.BOSS_DAMAGE_TITLE.sendPlayers(this.getPlayersWhoReceiveBossDeathMessage(), s -> s.replace("{boss}", event.getBoss().getName())); + + if (bossInfo.getHighestDamage() != null) + this.giveRewardsToOnePlayer(event, bossInfo, 1, bossInfo.getHighestDamage()); + break; + case GIVE_TO_TOP_3_PLAYERS: + int i = 1; + if (this.showDeathMessage()) + Language.BOSS_DAMAGE_TITLE.sendPlayers(this.getPlayersWhoReceiveBossDeathMessage(), s -> s.replace("{boss}", event.getBoss().getName())); + for (Player player : bossInfo.getTop3HighestDamage()) { + this.giveRewardsToOnePlayer(event, bossInfo, i, player); + i++; + } + break; + } + } + + private List getPlayersWhoReceiveBossDeathMessage() { + return Bukkit.getOnlinePlayers().stream().filter(player -> { + CrankedUser crankedUser = CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(player.getUniqueId()); + return crankedUser.isBossDeathMessagesEnabled(); + }).collect(Collectors.toList()); + } + + private void giveRewardsToOnePlayer(BossDeathEvent event, BossInfo bossInfo, int rank, Player player) { + event.getBoss().giveLootToPlayer(event.getKiller(), event.getBoss().getLootTableType()); + double damage = ( bossInfo.getDamageDealtByPlayer(player) / event.getEntity().getMaxHealth()) * 100; + + if (!this.showDeathMessage()) return; + Language.BOSS_DAMAGE_LINE.sendPlayers(getPlayersWhoReceiveBossDeathMessage(), s -> s.replace("{rank}", String.valueOf(rank)).replace("{player}", player.getName()).replace("{damage}", NumberUtils.formatMoney(damage))); + } + + public Set getBossAbilities() { + Set bossAbilities = new HashSet<>(); + Stream.of(this.getPhaseOne().getAbilities(), this.getPhaseTwo().getAbilities(), this.getPhaseThree().getAbilities()) + .forEach(bossAbilities::addAll); + + return bossAbilities.stream().map(BossAbilities::getAbilityInstance).collect(Collectors.toSet()); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbilities.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbilities.java new file mode 100644 index 0000000..7212020 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbilities.java @@ -0,0 +1,29 @@ +package net.crankedpvp.bosses.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.bosses.abilities.*; + +@AllArgsConstructor +public enum BossAbilities { + + LIGHTNING_STRIKE(new LightningStrike()), + BROOD_MOTHER_BLIND(new BroodMotherBlind()), + BROOD_MOTHER_WEB(new BroodMotherWeb()), + BROOD_MOTHER_MINION(new BroodMotherMinion()), + TREASURE_GOBLIN_LOOT(new TreasureGoblinLootDrop()), + TRAP(new Trap()), + + DAMAGE_TICK(new DamageTick()), + HEAL(new Heal()), + KNOCKBACK(new Knockback()), + PULL(new Pull()), + LAUNCH(new Launch()), + SHOOT_ARROW(new ShootArrow()), + //NOPOT(new NoPot()), + ; + + @Getter + private final BossAbility abilityInstance; + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbility.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbility.java new file mode 100644 index 0000000..c6893b3 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbility.java @@ -0,0 +1,50 @@ +package net.crankedpvp.bosses.struct; + +import net.crankedpvp.crankedutils.utils.StringUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Locale; +import java.util.UUID; + +public abstract class BossAbility { + + private final HashMap bossAbilityCooldowns; + + protected BossAbility() { + this.bossAbilityCooldowns = new HashMap<>(); + } + + public abstract String getName(); + + protected abstract void abilityEffect(Boss boss, LivingEntity BossEntity, Player player); + + public abstract int getCooldownLength(); + + public abstract double procChance(); + + public void updateAbilityCooldown(LivingEntity entity) { + this.bossAbilityCooldowns.put(entity.getUniqueId(), System.currentTimeMillis()); + } + + public boolean isAbilityOnCooldown(LivingEntity entity) { + return (this.getCooldownLength() * 1000L) + this.bossAbilityCooldowns.getOrDefault(entity.getUniqueId(), 0L) > System.currentTimeMillis(); + } + + public void removeFromCooldownCache(LivingEntity entity) { + this.bossAbilityCooldowns.remove(entity.getUniqueId()); + } + + public void procAbility(Boss boss, LivingEntity bossEntity, Player player) { + if (this.isAbilityOnCooldown(bossEntity)) return; + if (Math.random() * 100 > this.procChance()) return; + + this.updateAbilityCooldown(bossEntity); + this.abilityEffect(boss, bossEntity, player); + } + + public String getID() { + return StringUtils.toNiceString(this.getName()).toLowerCase(Locale.ROOT); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbilityCooldown.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbilityCooldown.java new file mode 100644 index 0000000..53cdeda --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAbilityCooldown.java @@ -0,0 +1,11 @@ +package net.crankedpvp.bosses.struct; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class BossAbilityCooldown extends CurrentCooldown { + + public BossAbilityCooldown(BossAbility bossAbility, int durationInSeconds) { + super("boss_ability_" + bossAbility.getID(), durationInSeconds); + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAttributes.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAttributes.java new file mode 100644 index 0000000..59d9fea --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossAttributes.java @@ -0,0 +1,18 @@ +package net.crankedpvp.bosses.struct; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class BossAttributes { + + @Builder.Default + private boolean immuneToFireDamage = true; + @Builder.Default + private boolean immuneToFallDamage = true; + @Builder.Default + private boolean immuneToMagicDamage = true; + @Builder.Default + private boolean immuneToProjectileDamage = true; +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossGear.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossGear.java new file mode 100644 index 0000000..f056974 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossGear.java @@ -0,0 +1,62 @@ +package net.crankedpvp.bosses.struct; + +import lombok.Builder; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; + +@Getter +@Builder +public class BossGear { + + @Builder.Default + private ItemBuilder helmet = new ItemBuilder(Material.AIR); + @Builder.Default + private ItemBuilder chestplate = new ItemBuilder(Material.AIR); + @Builder.Default + private ItemBuilder leggings = new ItemBuilder(Material.AIR); + @Builder.Default + private ItemBuilder boots = new ItemBuilder(Material.AIR); + @Builder.Default + private ItemBuilder weapon = new ItemBuilder(Material.AIR); + + public void applyArmorToBoss(LivingEntity entity) { + this.setHelmet(this.helmet, entity); + this.setChestplate(this.chestplate, entity); + this.setLeggings(this.leggings, entity); + this.setBoots(this.boots, entity); + this.setWeapon(this.weapon, entity); + } + + private void setWeapon(ItemBuilder weapon, LivingEntity entity) { + if (ItemUtils.isAirOrNull(weapon.build())) return; + entity.getEquipment().setItemInHand(weapon.setUnbreakable(true).build()); + entity.getEquipment().setItemInHandDropChance(0.0f); + } + + private void setHelmet(ItemBuilder helmet, LivingEntity entity) { + if (ItemUtils.isAirOrNull(helmet.build())) return; + entity.getEquipment().setHelmet(helmet.setUnbreakable(true).build()); + entity.getEquipment().setHelmetDropChance(0.0f); + } + + private void setChestplate(ItemBuilder chest, LivingEntity entity) { + if (ItemUtils.isAirOrNull(chest.build())) return; + entity.getEquipment().setChestplate(chest.setUnbreakable(true).build()); + entity.getEquipment().setChestplateDropChance(0.0f); + } + + private void setLeggings(ItemBuilder legs, LivingEntity entity) { + if (ItemUtils.isAirOrNull(legs.build())) return; + entity.getEquipment().setLeggings(legs.setUnbreakable(true).build()); + entity.getEquipment().setLeggingsDropChance(0.0f); + } + + private void setBoots(ItemBuilder boots, LivingEntity entity) { + if (ItemUtils.isAirOrNull(boots.build())) return; + entity.getEquipment().setBoots(boots.setUnbreakable(true).build()); + entity.getEquipment().setBootsDropChance(0.0f); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossInfo.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossInfo.java new file mode 100644 index 0000000..2945f52 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossInfo.java @@ -0,0 +1,51 @@ +package net.crankedpvp.bosses.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +@AllArgsConstructor +public class BossInfo { + + @Getter + private final Boss boss; + @Getter + private final LivingEntity livingEntity; + private final HashMap damageDealtToBossByPlayers = new HashMap<>(); + + public void updatePlayerDamage(Player player, double damage) { + this.damageDealtToBossByPlayers.put(player.getUniqueId(), damage + this.getDamageDealtByPlayer(player)); + } + + public double getDamageDealtByPlayer(Player player) { + return this.damageDealtToBossByPlayers.getOrDefault(player.getUniqueId(), 0.0); + } + + public List getTop3HighestDamage() { + return this.damageDealtToBossByPlayers.entrySet().stream() + .sorted(Map.Entry.comparingByValue().reversed()) + .limit(3) + .map(Map.Entry::getKey) + .map(Bukkit::getPlayer) + .collect(Collectors.toList()); + } + + public Player getHighestDamage() { + return this.damageDealtToBossByPlayers.entrySet().stream() + .sorted(Map.Entry.comparingByValue().reversed()) + .map(Map.Entry::getKey) + .map(Bukkit::getPlayer) + .findFirst() + .orElse(null) + ; + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossManager.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossManager.java new file mode 100644 index 0000000..b60e735 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossManager.java @@ -0,0 +1,76 @@ +package net.crankedpvp.bosses.struct; + +import net.crankedpvp.bosses.interfaces.Incrementable; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.HashMap; +import java.util.UUID; + +public class BossManager { + + private final HashMap aliveBosses; + + public BossManager() { + this.aliveBosses = new HashMap<>(); + } + + public void addBossToCache(LivingEntity entity, Boss boss) { + this.aliveBosses.put(entity.getUniqueId(), new BossInfo(boss, entity)); + } + + public void removeBossFromCache(Entity entity) { + this.aliveBosses.remove(entity.getUniqueId()); + } + + public Collection getAllAliveBossesInfo() { + return this.aliveBosses.values(); + } + + public Collection getAllAliveBossesIds() { + return this.aliveBosses.keySet(); + } + + public int getAliveBossesAmount() { + int alive = 0; + for(BossInfo boss : this.getAllAliveBossesInfo()) { + if(boss.getBoss() instanceof Incrementable) alive++; + } + return alive; + } + + public boolean isBoss(Entity entity) { + if (!(entity instanceof LivingEntity)) return false; + return this.aliveBosses.containsKey(entity.getUniqueId()); + } + + @Nullable + public Boss getBoss(Entity entity) { + if (!this.aliveBosses.containsKey(entity.getUniqueId())) { + return null; + } + return this.aliveBosses.get(entity.getUniqueId()).getBoss(); + } + + public BossInfo getBossInfo(Entity entity) { + return this.aliveBosses.get(entity.getUniqueId()); + } + + private void clearCache() { + this.aliveBosses.clear(); + } + + public void killAllAliveBosses() { + for (BossInfo bossInfo : this.getAllAliveBossesInfo()) { + bossInfo.getLivingEntity().remove(); + } + this.clearCache(); + } + + public void updateDamageDealtToBossByPlayer(Entity boss, Player player, double damage) { + this.getBossInfo(boss).updatePlayerDamage(player, damage); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPhase.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPhase.java new file mode 100644 index 0000000..a365c6a --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPhase.java @@ -0,0 +1,9 @@ +package net.crankedpvp.bosses.struct; + +public enum BossPhase { + + PHASE_ONE, + PHASE_TWO, + PHASE_THREE, + ; +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPhaseInfo.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPhaseInfo.java new file mode 100644 index 0000000..1bb53e1 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPhaseInfo.java @@ -0,0 +1,24 @@ +package net.crankedpvp.bosses.struct; + +import lombok.Builder; +import lombok.Getter; +import org.bukkit.Effect; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Collections; +import java.util.List; + +@Getter +@Builder +public class BossPhaseInfo { + + @Builder.Default + private List potionEffects = Collections.emptyList(); + @Builder.Default + private List abilities = Collections.emptyList(); + @Builder.Default + private double outgoingDamageIncrease = 0; + @Builder.Default + private double incomingDamageDecrease = 0; +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPlaceCooldown.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPlaceCooldown.java new file mode 100644 index 0000000..bcfc36d --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossPlaceCooldown.java @@ -0,0 +1,13 @@ +package net.crankedpvp.bosses.struct; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class BossPlaceCooldown extends CurrentCooldown { + + public static int BOSS_PLACE_COOLDOWN_TIME = 5; + public static String BOSS_PLACE_COOLDOWN_NAME = "boos-place-cooldown"; + + public BossPlaceCooldown() { + super(BOSS_PLACE_COOLDOWN_NAME, BOSS_PLACE_COOLDOWN_TIME); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossRegister.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossRegister.java new file mode 100644 index 0000000..39e2223 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossRegister.java @@ -0,0 +1,92 @@ +package net.crankedpvp.bosses.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.bosses.*; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.event.HandlerList; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +@Getter +@AllArgsConstructor +public class BossRegister { + + @Getter + private static BossRegister instance; + private final BossPlugin plugin; + private final Map registeredBosses; + + public BossRegister(BossPlugin plugin) { + instance = this; + this.plugin = plugin; + this.registeredBosses = new HashMap<>(); + } + + public void initialize() { + registerAll( + new KingSlime(), + new BroodMother(), + new Gauntlet(), + //new PlagueBloater(), + new TreasureGoblin(), + new CrankedGuardian(), + new Cranker(), + new Warlord(), + new CrazedWerewolf(), + new FireLord(), + new Slimicle(), + new Cerberus() + ); + } + + public void registerAll(Boss... bosses) { + for (Boss boss : bosses) { + register(boss); + } + } + + public void register(Boss boss) { + try { + this.registeredBosses.put(boss.getID(), boss); + this.plugin.getServer().getPluginManager().registerEvents(boss, plugin); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register boss " + boss.getName()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.registeredBosses.forEach(((enchantName, boss) -> HandlerList.unregisterAll(boss))); + this.registeredBosses.clear(); + } + + private void unregister(Boss boss) { + HandlerList.unregisterAll(boss); + this.registeredBosses.remove(boss.getName()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public Collection getBosses() { + return Collections.unmodifiableCollection(this.registeredBosses.values()); + } + + public boolean isBoss(String name) { + return (getBossFromID(name) != null); + } + + public Boss getBossFromID(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + return this.registeredBosses.get(name.toLowerCase()); + } +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossRewardSystem.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossRewardSystem.java new file mode 100644 index 0000000..0f7a350 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/BossRewardSystem.java @@ -0,0 +1,8 @@ +package net.crankedpvp.bosses.struct; + +public enum BossRewardSystem { + + GIVE_TO_TOP_PLAYER, + GIVE_TO_TOP_3_PLAYERS, + ; +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/annotations/ConfigValue.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/annotations/ConfigValue.java new file mode 100644 index 0000000..6b7b28c --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/annotations/ConfigValue.java @@ -0,0 +1,19 @@ +package net.crankedpvp.bosses.struct.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * don't forget to not make the field final when using this annotation + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigValue { + + String path() default "boss."; + String name() default ""; + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/config/BossConfig.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/config/BossConfig.java new file mode 100644 index 0000000..9df9f33 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/config/BossConfig.java @@ -0,0 +1,125 @@ +package net.crankedpvp.bosses.struct.config; + +import lombok.AccessLevel; +import lombok.Getter; +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.bosses.interfaces.Reloadable; +import net.crankedpvp.bosses.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; + +@Getter +public class BossConfig { + + @Getter(value = AccessLevel.PRIVATE) + private final BossPlugin plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + private final Boss boss; + + public BossConfig(BossPlugin plugin, String path, Boss boss) { + this.plugin = plugin; + this.path = path; + this.boss = boss; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public void setupConfigFile() { + this.createDefaultFile(); + this.config = YamlConfiguration.loadConfiguration(configFile); + + this.loadVariables(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path); + e.printStackTrace(); + } + return false; + } + + public void createDefaultFile() { + if (!configFile.exists()) { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path); + e.printStackTrace(); + } + } + } + + public void reloadConfig() { + config = YamlConfiguration.loadConfiguration(configFile); + this.loadVariables(); + } + + public void loadConfigFromDisk() { + try { + config.load(configFile); + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path); + e.printStackTrace(); + } + } + + public void loadVariables() { + boolean needSave = false; + for (Field field : this.boss.getClass().getDeclaredFields()) { + + try { + field.setAccessible(true); + + if (field.isAnnotationPresent(ConfigValue.class)) { + ConfigValue annotationValue = field.getAnnotation(ConfigValue.class); + + String name = annotationValue.name().equals("") ? field.getName() : annotationValue.name(); + + String path = annotationValue.path().endsWith(".") ? annotationValue.path() : annotationValue.path() + "."; + + if (!this.config.contains(path + name)) { + this.config.set(path + name, field.get(this.boss)); + needSave = true; + continue; + } + + Object fieldValue = this.config.get(path + name); + + if (fieldValue instanceof String) fieldValue = CC.translate((String) fieldValue); + + field.set(this.boss, fieldValue); + } + } catch (IllegalAccessException | NullPointerException | IllegalArgumentException e) { + Bukkit.getConsoleSender().sendMessage(CC.translate("&c[CrankedEnchants] - Error invalid config value for boss " + this.boss.getName())); + } + + if (this.boss instanceof Reloadable) { + Reloadable reloadableEnchantment = ((Reloadable) this.boss); + reloadableEnchantment.reloadValues(); + } + } + if (needSave) { + saveConfig(); + reloadConfig(); + } + } + +} diff --git a/Bosses/src/main/java/net/crankedpvp/bosses/struct/config/BossConfigManager.java b/Bosses/src/main/java/net/crankedpvp/bosses/struct/config/BossConfigManager.java new file mode 100644 index 0000000..1d738c7 --- /dev/null +++ b/Bosses/src/main/java/net/crankedpvp/bosses/struct/config/BossConfigManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.bosses.struct.config; + +import lombok.Getter; +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.bosses.struct.Boss; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class BossConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public BossConfigManager(BossPlugin plugin) { + for (Boss boss : plugin.getBossRegister().getBosses()) { + BossConfig BossConfig = new BossConfig(plugin, "bosses/" + boss.getID() + ".yml", boss); + configs.put(boss, BossConfig); + } + } + + public void setupFiles() { + configs.values().forEach(BossConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(BossConfig::reloadConfig); + } + + public BossConfig getAbstractConfig(Boss Boss) { + return configs.get(Boss); + } + + public FileConfiguration getConfig(Boss Boss) { + return getAbstractConfig(Boss).getConfig(); + } +} diff --git a/Bosses/src/main/resources/language.yml b/Bosses/src/main/resources/language.yml new file mode 100644 index 0000000..bbab9bb --- /dev/null +++ b/Bosses/src/main/resources/language.yml @@ -0,0 +1,13 @@ +CBO_COMMAND_HELP: + - "&8--- &4Cranked &cBosses &8---" + - "&4/cbo &cegg &7 [player]" +ADMIN_RELOADING: "&c&l(!) &7Reloading configs now..." +ADMIN_RELOADED: "&c&l(!) &7Reloaded configs and other cool stuff. Took &4%took%ms&7." +BOSS_DAMAGE_TITLE: + - "&c&l(!) &7The {boss} was successfully killed" + - "&7Top Damage:" +BOSS_DAMAGE_LINE: "&6Rank: #{rank} &8- &7{player} &4Damage: &c{damage}%" +SPAWN_BOSS_IN_WARZONE: "&4&lBosses &8➥ &7Boss eggs can only be used in warzone." +TOO_MANY_BOSSES: "&4&lBosses &8➥ &7There are too many bosses spawned in" + +MAX_BOSSES: 100 \ No newline at end of file diff --git a/Bosses/src/main/resources/plugin.yml b/Bosses/src/main/resources/plugin.yml new file mode 100644 index 0000000..ecfe52d --- /dev/null +++ b/Bosses/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedBosses +main: net.crankedpvp.bosses.BossPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/CagePvP/pom.xml b/CagePvP/pom.xml new file mode 100644 index 0000000..feb5220 --- /dev/null +++ b/CagePvP/pom.xml @@ -0,0 +1,47 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + CagePvP + + + 8 + 8 + + + + + sk89q-repo + https://maven.enginehub.org/repo/ + + + + + + net.crankedpvp + Utils + + + net.crankedpvp + CombatLog + 1.0 + + + com.massivecraft + Factions + + + com.sk89q + worldguard + provided + + + + \ No newline at end of file diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/CagePvPPlugin.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/CagePvPPlugin.java new file mode 100644 index 0000000..0ac9b60 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/CagePvPPlugin.java @@ -0,0 +1,109 @@ +package net.crankedpvp.wildpvp; + +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.wildpvp.combattag.CombatTagManager; +import net.crankedpvp.wildpvp.commands.CageMatchCommand; +import net.crankedpvp.wildpvp.factions.FactionsManager; +import net.crankedpvp.wildpvp.immune.ImmuneManager; +import net.crankedpvp.wildpvp.listeners.*; +import net.crankedpvp.wildpvp.playerdata.PlayerDataManager; +import net.crankedpvp.wildpvp.tasks.MatchesTask; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import net.crankedpvp.wildpvp.worldguard.WorldGuardManager; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; + +public class CagePvPPlugin extends JavaPlugin { + private static CagePvPPlugin instance; + + private FileConfiguration configLoad; + + private CageMatchManager cageMatchManager; + + private PlayerDataManager playerDataManager; + + private WorldGuardManager worldGuardManager; + + private FactionsManager factionsManager; + + private ImmuneManager immuneManager; + + private CombatTagManager combatTagManager; + + + public void onEnable() { + instance = this; + saveDefaultConfig(); + this.configLoad = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "config.yml")); + this.cageMatchManager = new CageMatchManager(this); + this.playerDataManager = new PlayerDataManager(); + this.factionsManager = new FactionsManager(); + this.immuneManager = new ImmuneManager(this); + this.combatTagManager = new CombatTagManager(); + this.worldGuardManager = new WorldGuardManager(); + (new MatchesTask(this)).runTaskTimerAsynchronously(this, 0L, 20L); + PluginManager pluginManager = getServer().getPluginManager(); + pluginManager.registerEvents(new JoinListener(this), this); + pluginManager.registerEvents(new QuitListener(this), this); + pluginManager.registerEvents(new MoveListener(this), this); + pluginManager.registerEvents(new ItemListener(this), this); + pluginManager.registerEvents(new DeathListener(this), this); + pluginManager.registerEvents(new BlockListeners(this), this); + pluginManager.registerEvents(new PotionListener(this), this); + pluginManager.registerEvents(new EntityListener(this), this); + pluginManager.registerEvents(new VehicleListener(this), this); + pluginManager.registerEvents(new FactionListener(this), this); + pluginManager.registerEvents(new CommandListener(this), this); + pluginManager.registerEvents(new InteractListener(this), this); + pluginManager.registerEvents(new TeleportListener(this), this); + CommandManager commandManager = new CommandManager(this); + commandManager.register(new CageMatchCommand(this)); + } + + public void onDisable() { + if (this.cageMatchManager != null) + this.cageMatchManager.onDisable(); + } + + public FileConfiguration getConfig() { + return this.configLoad; + } + + public void reloadConfig() { + this.configLoad = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "config.yml")); + } + + public CageMatchManager getWildPvPManager() { + return this.cageMatchManager; + } + + public PlayerDataManager getPlayerDataManager() { + return this.playerDataManager; + } + + public WorldGuardManager getWorldGuardManager() { + return this.worldGuardManager; + } + + public FactionsManager getFactionsManager() { + return this.factionsManager; + } + + + public ImmuneManager getImmuneManager() { + return this.immuneManager; + } + + public static CagePvPPlugin getInstance() { + return instance; + } + + public CombatTagManager getCombatTagManager() { + return this.combatTagManager; + } + +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/combattag/CombatTagManager.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/combattag/CombatTagManager.java new file mode 100644 index 0000000..72f6d9d --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/combattag/CombatTagManager.java @@ -0,0 +1,19 @@ +package net.crankedpvp.wildpvp.combattag; + + +import net.crankedpvp.combatlog.CombatTagAPI; +import org.bukkit.entity.Player; + +public class CombatTagManager { + public boolean isTagged(Player player) { + return CombatTagAPI.isInCombat(player); + } + + public void removeTag(Player player) { + CombatTagAPI.removePlayerFromCombat(player); + } + + public void giveTag(Player player) { + CombatTagAPI.putPlayerInCombat(player); + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/commands/CageMatchCommand.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/commands/CageMatchCommand.java new file mode 100644 index 0000000..0583133 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/commands/CageMatchCommand.java @@ -0,0 +1,110 @@ +package net.crankedpvp.wildpvp.commands; + + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.combattag.CombatTagManager; +import net.crankedpvp.wildpvp.menus.Matches; +import net.crankedpvp.wildpvp.utils.TitleManager; +import net.crankedpvp.wildpvp.wildpvp.CageMatch; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +@Command("1v1") +public class CageMatchCommand extends CommandBase { + + private final CagePvPPlugin plugin; + private final CombatTagManager combatTagManager; + private final CageMatchManager cageMatchManager; + private final FileConfiguration configLoad; + + public CageMatchCommand(CagePvPPlugin plugin) { + this.plugin = plugin; + this.combatTagManager = this.plugin.getCombatTagManager(); + this.cageMatchManager = this.plugin.getWildPvPManager(); + this.configLoad = this.plugin.getConfig(); + } + + @Default + public void defaultCommand(Player player) { + this.plugin.getPlayerDataManager().getPlayerData(player).setPage(1); + Matches.getInstance().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 1.0F, 1.0F); + } + + @SubCommand("leave") + public void leaveCommand(Player player) { + if (!cageMatchManager.hasWildPvP(player)) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Match.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + } else { + if (combatTagManager.isTagged(player) && cageMatchManager.getWildPvP(player).hasStarted()) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.CombatTag.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + } else { + CageMatch cageMatch = cageMatchManager.getWildPvP(player); + cageMatch.setEnded(true); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(player, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Title.SubTitle")), 0, 30, 10); + } + + if (cageMatch.hasJoined()) { + Player creator; + if (cageMatch.isJoined(player)) { + creator = cageMatch.getCreator(); + + + cageMatch.teleportToJoinLocation(player); + + cageMatch.hideBorder(player); + cageMatch.hideBorder(creator); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Player.Participant.Message").replace("%player", creator.getName()))); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Teleported.Message"))); + player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 1.0F, 1.0F); + creator.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Participant.Message").replace("%player", player.getName()))); + creator.playSound(creator.getLocation(), Sound.IRONGOLEM_HIT, 1.0F, 1.0F); + } else { + creator = cageMatch.getJoined(); + cageMatch.teleportToJoinLocation(creator); + cageMatch.hideBorder(player); + cageMatch.hideBorder(creator); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Player.Participant.Message").replace("%player", creator.getName()))); + player.playSound(player.getLocation(), Sound.IRONGOLEM_HIT, 1.0F, 1.0F); + creator.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Participant.Message").replace("%player", player.getName()))); + + creator.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Teleported.Message"))); + + creator.playSound(creator.getLocation(), Sound.ENDERMAN_TELEPORT, 1.0F, 1.0F); + } + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(creator, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Title.SubTitle")), 0, 30, 10); + } + } else { + cageMatch.hideBorder(player); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Player.Alone.Message"))); + player.playSound(player.getLocation(), Sound.IRONGOLEM_HIT, 1.0F, 1.0F); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(player, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Commands.WildPvP.Leave.Left.Title.SubTitle")), 0, 30, 10); + } + } + + if (combatTagManager.isTagged(cageMatch.getCreator())) { + combatTagManager.removeTag(cageMatch.getCreator()); + } + + if (cageMatch.hasJoined() && combatTagManager.isTagged(cageMatch.getJoined())) { + combatTagManager.removeTag(cageMatch.getJoined()); + } + + cageMatchManager.removeWildPvP(cageMatch); + } + } + + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/factions/FactionsManager.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/factions/FactionsManager.java new file mode 100644 index 0000000..dd77cab --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/factions/FactionsManager.java @@ -0,0 +1,54 @@ +package net.crankedpvp.wildpvp.factions; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.perms.Relation; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginManager; + +public class FactionsManager { + private boolean factionsPlugin; + + public FactionsManager() { + this.registerFactions(); + } + + public String getFactionName(Player player) { + return FPlayers.getInstance().getByPlayer(player).getFaction().getTag(); + } + + public boolean isFactionMember(Player player1, Player player2) { + FPlayers fPlayers = FPlayers.getInstance(); + return fPlayers.getByPlayer(player1).getFaction().getRelationTo(fPlayers.getByPlayer(player2).getFaction()) == Relation.MEMBER; + } + + public boolean isFactionAlly(Player player1, Player player2) { + FPlayers fPlayers = FPlayers.getInstance(); + return fPlayers.getByPlayer(player1).getFaction().getRelationTo(fPlayers.getByPlayer(player2).getFaction()) == Relation.ALLY; + } + + public boolean isWilderness(Location location) { + Faction factionAtLocation = Board.getInstance().getFactionAt(new FLocation(location)); + return factionAtLocation == null || factionAtLocation.isWilderness(); + } + + public void registerFactions() { + PluginManager pluginManager = Bukkit.getServer().getPluginManager(); + if (pluginManager.getPlugin("Factions") != null) { + this.factionsPlugin = pluginManager.getPlugin("Factions") != null; + } + + } + + public boolean hasFactions() { + if (!this.factionsPlugin) { + this.registerFactions(); + } + + return this.factionsPlugin; + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/immune/Immune.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/immune/Immune.java new file mode 100644 index 0000000..ac615a0 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/immune/Immune.java @@ -0,0 +1,63 @@ +package net.crankedpvp.wildpvp.immune; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.utils.TitleManager; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +public class Immune { + private final CagePvPPlugin instance; + private final Player player; + private boolean cancelled = false; + + public Immune(CagePvPPlugin instance, Player player) { + this.instance = instance; + this.player = player; + } + + public Player getPlayer() { + return this.player; + } + + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void start() { + final ImmuneManager immuneManager = this.instance.getImmuneManager(); + final FileConfiguration configLoad = this.instance.getConfig(); + this.player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Immune.Countdown.Started.Message"))); + (new BukkitRunnable() { + int countdown = 20; + + public void run() { + if (!Immune.this.cancelled && Immune.this.player.isOnline() && this.countdown >= 0) { + if (this.countdown == 15 || this.countdown == 10 || this.countdown > 0 && this.countdown <= 5) { + Immune.this.player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Immune.Countdown.Ending.Message").replace("%countdown", String.valueOf(this.countdown)))); + TitleManager.sendTitle(Immune.this.player, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Immune.Countdown.Ending.Title.Title").replace("%countdown", String.valueOf(this.countdown))), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Immune.Countdown.Ending.Title.SubTitle").replace("%countdown", String.valueOf(this.countdown))), 0, 30, 0); + Immune.this.player.playSound(Immune.this.player.getLocation(), Sound.NOTE_STICKS, 1.0F, 1.0F); + } else if (this.countdown == 0) { + Immune.this.cancelled = true; + this.cancel(); + immuneManager.removeImmune(Immune.this.player); + Immune.this.player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Immune.Countdown.Ended.Message").replace("%countdown", String.valueOf(this.countdown)))); + TitleManager.sendTitle(Immune.this.player, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Immune.Countdown.Ended.Title.Title").replace("%countdown", String.valueOf(this.countdown))), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Immune.Countdown.Ended.Title.SubTitle").replace("%countdown", String.valueOf(this.countdown))), 0, 30, 10); + Immune.this.player.playSound(Immune.this.player.getLocation(), Sound.FIZZ, 1.0F, 1.0F); + } + + --this.countdown; + } else { + immuneManager.removeImmune(Immune.this.player); + this.cancel(); + } + } + }).runTaskTimerAsynchronously(this.instance, 0L, 20L); + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/immune/ImmuneManager.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/immune/ImmuneManager.java new file mode 100644 index 0000000..7f87fa6 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/immune/ImmuneManager.java @@ -0,0 +1,59 @@ +package net.crankedpvp.wildpvp.immune; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class ImmuneManager { + private final CagePvPPlugin instance; + private final List immunes = new ArrayList(); + + public ImmuneManager(CagePvPPlugin instance) { + this.instance = instance; + } + + public Immune createImmune(Player player) { + Immune immune = new Immune(this.instance, player); + this.immunes.add(immune); + return immune; + } + + public void removeImmune(Immune immune) { + this.immunes.remove(immune); + } + + public void removeImmune(Player player) { + Iterator immuneIterator = this.immunes.iterator(); + + while(immuneIterator.hasNext()) { + Immune immune = immuneIterator.next(); + if (immune.getPlayer().getUniqueId().equals(player.getUniqueId())) { + immuneIterator.remove(); + break; + } + } + + } + + public Immune getImmune(Player player) { + Iterator var2 = this.immunes.iterator(); + + Immune immune; + do { + if (!var2.hasNext()) { + return null; + } + + immune = var2.next(); + } while(!immune.getPlayer().getUniqueId().equals(player.getUniqueId())); + + return immune; + } + + public boolean hasImmune(Player player) { + return this.getImmune(player) != null; + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/BlockListeners.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/BlockListeners.java new file mode 100644 index 0000000..1286ff5 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/BlockListeners.java @@ -0,0 +1,77 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityExplodeEvent; + +import java.util.Iterator; + +public class BlockListeners implements Listener { + private final CagePvPPlugin instance; + + public BlockListeners(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onBlockPlace(BlockPlaceEvent event) { + Player player = event.getPlayer(); + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + FileConfiguration configLoad = this.instance.getConfig(); + if (cageMatchManager.hasWildPvP(player)) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Block.Place.Match.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } else if (cageMatchManager.hasWildPvP(event.getBlock().getChunk())) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Block.Place.Chunk.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } + + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onBlockBreak(BlockBreakEvent event) { + Player player = event.getPlayer(); + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + FileConfiguration configLoad = this.instance.getConfig(); + if (cageMatchManager.hasWildPvP(player)) { + if(event.getBlock().getType() == Material.DOUBLE_PLANT) return; + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Block.Break.Match.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } else if (cageMatchManager.hasWildPvP(event.getBlock().getChunk())) { + if(event.getBlock().getType() == Material.DOUBLE_PLANT) return; + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Block.Break.Chunk.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } + + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onEntityExplode(EntityExplodeEvent event) { + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + if (!this.instance.getConfig().getBoolean("WildPvP.EntityExplosion.Enable")) { + Iterator blockListIterator = event.blockList().iterator(); + + while(blockListIterator.hasNext()) { + org.bukkit.block.Block block = (org.bukkit.block.Block)blockListIterator.next(); + if (cageMatchManager.hasWildPvP(block.getChunk())) { + blockListIterator.remove(); + } + } + + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/CommandListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/CommandListener.java new file mode 100644 index 0000000..64e503b --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/CommandListener.java @@ -0,0 +1,47 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +import java.util.Iterator; + +public class CommandListener implements Listener { + private final CagePvPPlugin instance; + + public CommandListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { + if (!event.getMessage().toLowerCase().startsWith("/wildpvp") && !event.getMessage().toLowerCase().startsWith("/1v1")) { + if(event.getPlayer().hasPermission("cranked.admin")) return; + Player player = event.getPlayer(); + FileConfiguration configLoad = this.instance.getConfig(); + Iterator var4 = configLoad.getStringList("Listeners.Command.AllowedCommands").iterator(); + + String allowedCommand; + do { + if (!var4.hasNext()) { + if (!this.instance.getWildPvPManager().hasWildPvP(player)) { + return; + } + + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Command.Match.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + allowedCommand = (String)var4.next(); + } while(!event.getMessage().split(" ")[0].toLowerCase().equalsIgnoreCase("/" + allowedCommand.toLowerCase())); + + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/DeathListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/DeathListener.java new file mode 100644 index 0000000..4587ec1 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/DeathListener.java @@ -0,0 +1,112 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.combattag.CombatTagManager; +import net.crankedpvp.wildpvp.immune.Immune; +import net.crankedpvp.wildpvp.immune.ImmuneManager; +import net.crankedpvp.wildpvp.utils.TitleManager; +import net.crankedpvp.wildpvp.wildpvp.CageMatch; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; + +import java.util.Iterator; + +public class DeathListener implements Listener { + private final CagePvPPlugin instance; + + public DeathListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onPlayerDeath(PlayerDeathEvent event) { + Player player = event.getEntity(); + CombatTagManager combatTagManager = this.instance.getCombatTagManager(); + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + ImmuneManager immuneManager = this.instance.getImmuneManager(); + FileConfiguration configLoad = this.instance.getConfig(); + if (cageMatchManager.hasWildPvP(player)) { + CageMatch cageMatch = cageMatchManager.getWildPvP(player); + if (cageMatch.hasJoined()) { + cageMatch.setEnded(true); + Player creator; + Immune immune; + Iterator var10; + Player all; + if (cageMatch.isJoined(player)) { + creator = cageMatch.getCreator(); + cageMatch.hideBorder(player); + cageMatch.hideBorder(creator); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Lost.Message").replace("%player", creator.getName()))); + player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 1.0F, 5.0F); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(player, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Lost.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Lost.Title.SubTitle")), 0, 30, 10); + } + + creator.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Won.Message").replace("%player", player.getName()))); + creator.playSound(creator.getLocation(), Sound.ENDERDRAGON_GROWL, 1.0F, 5.0F); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(creator, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Won.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Won.Title.SubTitle")), 0, 30, 10); + } + + immune = immuneManager.createImmune(creator); + immune.start(); + var10 = Bukkit.getOnlinePlayers().iterator(); + + while(var10.hasNext()) { + all = (Player)var10.next(); + if (!all.getUniqueId().equals(player.getUniqueId()) && !all.getUniqueId().equals(creator.getUniqueId())) { + all.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Broadcast.Message").replace("%winner", creator.getName()).replace("%loser", player.getName()))); + } + } + + if (combatTagManager.isTagged(creator)) { + combatTagManager.removeTag(creator); + } + } else { + creator = cageMatch.getJoined(); + cageMatch.hideBorder(player); + cageMatch.hideBorder(creator); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Lost.Message").replace("%player", creator.getName()))); + player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 1.0F, 5.0F); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(player, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Lost.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Lost.Title.SubTitle")), 0, 30, 10); + } + + creator.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Won.Message").replace("%player", player.getName()))); + creator.playSound(creator.getLocation(), Sound.ENDERMAN_TELEPORT, 1.0F, 5.0F); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(creator, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Won.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Won.Title.SubTitle")), 0, 30, 10); + } + + immune = immuneManager.createImmune(creator); + immune.start(); + var10 = Bukkit.getOnlinePlayers().iterator(); + + while(var10.hasNext()) { + all = (Player)var10.next(); + if (!all.getUniqueId().equals(player.getUniqueId()) && !all.getUniqueId().equals(creator.getUniqueId())) { + all.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Death.Broadcast.Message").replace("%winner", creator.getName()).replace("%loser", player.getName()))); + } + } + + if (combatTagManager.isTagged(creator)) { + combatTagManager.removeTag(creator); + } + } + } else { + player.sendMessage(configLoad.getString("Listeners.Death.Alone.Message")); + player.playSound(player.getLocation(), Sound.IRONGOLEM_HIT, 1.0F, 1.0F); + } + + cageMatchManager.removeWildPvP(cageMatch); + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/EntityListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/EntityListener.java new file mode 100644 index 0000000..0e73932 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/EntityListener.java @@ -0,0 +1,83 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.immune.ImmuneManager; +import net.crankedpvp.wildpvp.wildpvp.CageMatch; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class EntityListener implements Listener { + private final CagePvPPlugin instance; + + public EntityListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + if (!event.isCancelled()) { + Player damaged; + Player damager; + if (event.getEntity() instanceof Player && event.getDamager() instanceof Player) { + damaged = (Player)event.getEntity(); + damager = (Player)event.getDamager(); + } else { + label64: { + if (event.getEntity() instanceof Player && event.getDamager() instanceof Projectile) { + Projectile projectile = (Projectile)event.getDamager(); + if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) { + damaged = (Player)event.getEntity(); + damager = (Player)projectile.getShooter(); + if (damaged.getUniqueId().equals(damager.getUniqueId())) { + return; + } + break label64; + } + + return; + } + + return; + } + } + + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + ImmuneManager immuneManager = this.instance.getImmuneManager(); + FileConfiguration configLoad = this.instance.getConfig(); + if (immuneManager.hasImmune(damager)) { + event.setCancelled(true); + damager.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Damage.Immune.Immune.Message"))); + damager.playSound(damager.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } else if (immuneManager.hasImmune(damaged)) { + event.setCancelled(true); + damager.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Damage.Immune.Player.Message"))); + damager.playSound(damager.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } else if (cageMatchManager.hasWildPvP(damager)) { + CageMatch cageMatch = cageMatchManager.getWildPvP(damager); + if (cageMatch.isParticipant(damaged)) { + if (cageMatch.isGrace()) { + event.setCancelled(true); + damager.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Damage.Grace.Message"))); + damager.playSound(damager.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } + + } else { + event.setCancelled(true); + damager.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Damage.Match.Participant.Message"))); + damager.playSound(damager.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } + } else if (cageMatchManager.hasWildPvP(damaged)) { + event.setCancelled(true); + damager.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Damage.Match.Player.Message"))); + damager.playSound(damager.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/FactionListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/FactionListener.java new file mode 100644 index 0000000..9516e4d --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/FactionListener.java @@ -0,0 +1,33 @@ +package net.crankedpvp.wildpvp.listeners; + +import com.massivecraft.factions.event.LandClaimEvent; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class FactionListener implements Listener { + private final CagePvPPlugin instance; + + public FactionListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onLandClaim(LandClaimEvent event) { + if (event.getLocation() != null) { + if (this.instance.getWildPvPManager().hasWildPvP(event.getLocation().getChunk())) { + if (event.getfPlayer() != null && event.getfPlayer().getPlayer() != null) { + event.setCancelled(true); + Player player = event.getfPlayer().getPlayer(); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', this.instance.getConfig().getString("Listeners.Claim.Match.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + } else { + event.setCancelled(true); + } + } + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/InteractListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/InteractListener.java new file mode 100644 index 0000000..9f2711c --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/InteractListener.java @@ -0,0 +1,62 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class InteractListener implements Listener { + private final CagePvPPlugin instance; + + public InteractListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onPlayerInteract(PlayerInteractEvent event) { + if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { + Player player = event.getPlayer(); + if (this.instance.getWildPvPManager().hasWildPvP(player)) { + FileConfiguration configLoad = this.instance.getConfig(); + + for (String block : configLoad.getStringList("WildPvP.Match.BlockInteractBlacklist")) { + if (event.getClickedBlock().getType().name().equalsIgnoreCase(block)) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Interact.Match.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + break; + } + } + + } + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPearl(PlayerInteractEvent event) { + Player player = event.getPlayer(); + if (this.instance.getWildPvPManager().hasWildPvP(player)) { + if (player.getItemInHand() != null) { + if (player.getItemInHand().getType() == Material.ENDER_PEARL) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', this.instance.getConfig().getString("Listeners.Teleport.Match.Participant.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + event.setCancelled(true); + event.setUseItemInHand(Event.Result.DENY); + player.updateInventory(); + } + } + } + + + } + +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/ItemListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/ItemListener.java new file mode 100644 index 0000000..d7da123 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/ItemListener.java @@ -0,0 +1,32 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerPickupItemEvent; + +public class ItemListener implements Listener { + private final CagePvPPlugin instance; + + public ItemListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onPlayerPickupItem(PlayerPickupItemEvent event) { + if (!event.isCancelled()) { + Player player = event.getPlayer(); + if (this.instance.getWildPvPManager().hasWildPvP(player)) { + + //for(String item : this.instance.getConfig().getStringList("WildPvP.Match.ItemPickupBlacklist")) { + //if(event.getItem().getItemStack().getType().name().equalsIgnoreCase(item)) { + event.setCancelled(true); + //break; + //} + //} + + } + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/JoinListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/JoinListener.java new file mode 100644 index 0000000..874d40c --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/JoinListener.java @@ -0,0 +1,35 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +public class JoinListener implements Listener { + private final CagePvPPlugin instance; + + public JoinListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + this.instance.getPlayerDataManager().createPlayerData(player); + if (this.instance.getWildPvPManager().hasWildPvP(player.getLocation().getChunk())) { + FileConfiguration configLoad = this.instance.getConfig(); + + for(String command : configLoad.getStringList("WildPvP.Join.Commands")) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), command.replace("%player", player.getName())); + } + + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Join.Teleported.Message"))); + player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 1.0F, 1.0F); + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/MoveListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/MoveListener.java new file mode 100644 index 0000000..3c07bad --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/MoveListener.java @@ -0,0 +1,70 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.wildpvp.CageMatch; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + +public class MoveListener implements Listener { + private final CagePvPPlugin instance; + + public MoveListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onPlayerMoveOutsideChunk(PlayerMoveEvent event) { + Player player = event.getPlayer(); + Location fromLocation = event.getFrom(); + Location toLocation = event.getTo(); + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + if (cageMatchManager.hasWildPvP(player)) { + if (player.hasPermission("cranked.admin")) return; + CageMatch cageMatch = cageMatchManager.getWildPvP(player); + if (fromLocation.getChunk().getX() == cageMatch.getChunk().getX() && fromLocation.getChunk().getZ() == cageMatch.getChunk().getZ() && (toLocation.getChunk().getX() != cageMatch.getChunk().getX() || toLocation.getChunk().getZ() != cageMatch.getChunk().getZ())) { + Location location = player.getLocation().clone().add(fromLocation.toVector().subtract(toLocation.toVector()).normalize().multiply(2.0D)); + if (location.getBlock().getType().isSolid()) { + location.setY(location.getWorld().getHighestBlockYAt(location)); + } + + player.teleport(location, TeleportCause.UNKNOWN); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', this.instance.getConfig().getString("Listeners.Move.Chunk.Participant.Message"))); + player.playSound(player.getLocation(), Sound.FIREWORK_LAUNCH, 1.0F, 5.0F); + } + } + } + + @EventHandler + public void onPlayerMoveInsideChunk(PlayerMoveEvent event) { + Player player = event.getPlayer(); + if (player.getGameMode() != GameMode.SPECTATOR) { + Location fromLocation = event.getFrom(); + Location toLocation = event.getTo(); + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + if (cageMatchManager.hasWildPvP(toLocation.getChunk())) { + if (player.hasPermission("cranked.admin")) return; + if (player.hasPermission("essentials.tp.others")) return; + + CageMatch cageMatch = cageMatchManager.getWildPvP(toLocation.getChunk()); + if (!cageMatch.isParticipant(player)) { + Location location = player.getLocation().clone().add(fromLocation.toVector().subtract(toLocation.toVector()).normalize().multiply(2.0D)); + if (location.getBlock().getType().isSolid()) { + location.setY(location.getWorld().getHighestBlockYAt(location)); + } + + player.teleport(location, TeleportCause.UNKNOWN); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', this.instance.getConfig().getString("Listeners.Move.Chunk.Match.Message"))); + player.playSound(player.getLocation(), Sound.FIREWORK_LAUNCH, 1.0F, 5.0F); + } + } + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/PotionListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/PotionListener.java new file mode 100644 index 0000000..35b035c --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/PotionListener.java @@ -0,0 +1,103 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.immune.ImmuneManager; +import net.crankedpvp.wildpvp.wildpvp.CageMatch; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.ThrownPotion; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PotionSplashEvent; + +import java.util.Iterator; + +public class PotionListener implements Listener { + private final CagePvPPlugin instance; + + public PotionListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onPotionSplash(PotionSplashEvent event) { + if (event.getAffectedEntities().size() != 0) { + ThrownPotion thrownPotion = event.getPotion(); + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + ImmuneManager immuneManager = this.instance.getImmuneManager(); + Iterator affectedEntitiesIterator = event.getAffectedEntities().iterator(); + if (thrownPotion.getShooter() != null && thrownPotion.getShooter() instanceof Player) { + Player shooter = (Player)thrownPotion.getShooter(); + if (cageMatchManager.hasWildPvP(shooter)) { + CageMatch cageMatch = cageMatchManager.getWildPvP(shooter); + + while(affectedEntitiesIterator.hasNext()) { + LivingEntity livingEntity = (LivingEntity)affectedEntitiesIterator.next(); + if (livingEntity instanceof Player) { + Player player = (Player)livingEntity; + if (!player.getUniqueId().equals(shooter.getUniqueId()) && !cageMatch.isParticipant(player)) { + affectedEntitiesIterator.remove(); + event.setIntensity(livingEntity, 0.0D); + } + } + } + } else { + LivingEntity livingEntity; + Player player; + if (immuneManager.hasImmune(shooter)) { + while(affectedEntitiesIterator.hasNext()) { + livingEntity = (LivingEntity)affectedEntitiesIterator.next(); + if (livingEntity instanceof Player) { + player = (Player)livingEntity; + if (!player.getUniqueId().equals(shooter.getUniqueId())) { + affectedEntitiesIterator.remove(); + event.setIntensity(livingEntity, 0.0D); + } + } + } + } else { + while(true) { + do { + do { + do { + if (!affectedEntitiesIterator.hasNext()) { + return; + } + + livingEntity = (LivingEntity)affectedEntitiesIterator.next(); + } while(!(livingEntity instanceof Player)); + + player = (Player)livingEntity; + } while(player.getUniqueId().equals(shooter.getUniqueId())); + } while(!cageMatchManager.hasWildPvP(player) && !immuneManager.hasImmune(player)); + + affectedEntitiesIterator.remove(); + event.setIntensity(livingEntity, 0.0D); + } + } + } + } else { + while(true) { + LivingEntity livingEntity; + Player player; + do { + do { + if (!affectedEntitiesIterator.hasNext()) { + return; + } + + livingEntity = (LivingEntity)affectedEntitiesIterator.next(); + } while(!(livingEntity instanceof Player)); + + player = (Player)livingEntity; + } while(!cageMatchManager.hasWildPvP(player) && !immuneManager.hasImmune(player)); + + affectedEntitiesIterator.remove(); + event.setIntensity(livingEntity, 0.0D); + } + } + + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/QuitListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/QuitListener.java new file mode 100644 index 0000000..9f6e72a --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/QuitListener.java @@ -0,0 +1,107 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.combattag.CombatTagManager; +import net.crankedpvp.wildpvp.immune.Immune; +import net.crankedpvp.wildpvp.immune.ImmuneManager; +import net.crankedpvp.wildpvp.utils.TitleManager; +import net.crankedpvp.wildpvp.wildpvp.CageMatch; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.util.Iterator; + +public class QuitListener implements Listener { + private final CagePvPPlugin instance; + + public QuitListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + public void onPlayerQuit(PlayerQuitEvent event) { + Player player = event.getPlayer(); + this.instance.getPlayerDataManager().removePlayerData(player); + CombatTagManager combatTagManager = this.instance.getCombatTagManager(); + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + ImmuneManager immuneManager = this.instance.getImmuneManager(); + FileConfiguration configLoad = this.instance.getConfig(); + if (immuneManager.hasImmune(player)) { + Immune immune = immuneManager.getImmune(player); + immune.setCancelled(true); + immuneManager.removeImmune(immune); + } + + if (cageMatchManager.hasWildPvP(player)) { + CageMatch cageMatch = cageMatchManager.getWildPvP(player); + cageMatch.setEnded(true); + if (cageMatch.hasJoined()) { + Player joined; + if (!combatTagManager.isTagged(player)) { + if (cageMatch.isJoined(player)) { + joined = cageMatch.getCreator(); + cageMatch.teleportToJoinLocation(player); + cageMatch.hideBorder(joined); + joined.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Left.Message").replace("%player", player.getName()))); + joined.playSound(joined.getLocation(), Sound.IRONGOLEM_HIT, 1.0F, 1.0F); + + } else { + joined = cageMatch.getJoined(); + cageMatch.teleportToJoinLocation(joined); + cageMatch.hideBorder(joined); + joined.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Left.Message").replace("%player", player.getName()))); + joined.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Teleported.Message").replace("%player", player.getName()))); + joined.playSound(joined.getLocation(), Sound.ENDERMAN_TELEPORT, 1.0F, 1.0F); + + } + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(joined, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Left.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Left.Title.SubTitle")), 0, 30, 10); + } + } else { + Immune immune; + Iterator var10; + Player all; + if (cageMatch.isJoined(player)) { + joined = cageMatch.getCreator(); + + } else { + joined = cageMatch.getJoined(); + + } + cageMatch.hideBorder(joined); + joined.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Won.Message").replace("%player", player.getName()))); + joined.playSound(joined.getLocation(), Sound.ENDERDRAGON_GROWL, 1.0F, 5.0F); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(joined, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Won.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Won.Title.SubTitle")), 0, 30, 10); + } + combatTagManager.removeTag(joined); + immune = immuneManager.createImmune(joined); + immune.start(); + var10 = Bukkit.getOnlinePlayers().iterator(); + while(var10.hasNext()) { + all = (Player)var10.next(); + if (!all.getUniqueId().equals(joined.getUniqueId())) { + all.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Quit.Broadcast.Message").replace("%winner", joined.getName()).replace("%loser", player.getName()))); + } + } + } + if (combatTagManager.isTagged(joined)) { + combatTagManager.removeTag(joined); + } + } + + cageMatchManager.removeWildPvP(cageMatch); + } + + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/TeleportListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/TeleportListener.java new file mode 100644 index 0000000..082586a --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/TeleportListener.java @@ -0,0 +1,56 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + +public class TeleportListener implements Listener { + private final CagePvPPlugin instance; + + public TeleportListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onPlayerTeleportParticipant(PlayerTeleportEvent event) { + if (!event.isCancelled()) { + if (event.getCause() != TeleportCause.UNKNOWN) { + Player player = event.getPlayer(); + if (this.instance.getWildPvPManager().hasWildPvP(player)) { + if(event.getPlayer().hasPermission("cranked.admin")) return; + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', this.instance.getConfig().getString("Listeners.Teleport.Match.Participant.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } + } + } + } + + @EventHandler + public void onPlayerTeleportMatch(PlayerTeleportEvent event) { + if (!event.isCancelled()) { + if (event.getCause() == TeleportCause.UNKNOWN || event.getCause() == TeleportCause.ENDER_PEARL) return; + Player player = event.getPlayer(); + if (player.getGameMode() != GameMode.SPECTATOR) { + + CageMatchManager cageMatchManager = this.instance.getWildPvPManager(); + if (cageMatchManager.hasWildPvP(event.getTo().getChunk())) { + if(event.getPlayer().hasPermission("cranked.admin")) return; + if (!cageMatchManager.getWildPvP(event.getTo().getChunk()).isParticipant(player)) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', this.instance.getConfig().getString("Listeners.Teleport.Match.Match.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } + } + } + + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/VehicleListener.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/VehicleListener.java new file mode 100644 index 0000000..f4f97f4 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/listeners/VehicleListener.java @@ -0,0 +1,29 @@ +package net.crankedpvp.wildpvp.listeners; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.vehicle.VehicleEnterEvent; + +public class VehicleListener implements Listener { + private final CagePvPPlugin instance; + + public VehicleListener(CagePvPPlugin instance) { + this.instance = instance; + } + + @EventHandler + public void onVehicleEnter(VehicleEnterEvent event) { + if (event.getEntered() instanceof Player) { + Player player = (Player)event.getEntered(); + if (this.instance.getWildPvPManager().hasWildPvP(player)) { + event.setCancelled(true); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', this.instance.getConfig().getString("Listeners.Vehicle.Match.Message"))); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1.0F, 1.0F); + } + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/menus/Matches.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/menus/Matches.java new file mode 100644 index 0000000..6379312 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/menus/Matches.java @@ -0,0 +1,245 @@ +package net.crankedpvp.wildpvp.menus; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.combattag.CombatTagManager; +import net.crankedpvp.wildpvp.factions.FactionsManager; +import net.crankedpvp.wildpvp.immune.ImmuneManager; +import net.crankedpvp.wildpvp.playerdata.PlayerData; +import net.crankedpvp.wildpvp.utils.*; +import net.crankedpvp.wildpvp.utils.inventory.Placeholder; +import net.crankedpvp.wildpvp.utils.inventory.nInventoryUtil; +import net.crankedpvp.wildpvp.wildpvp.CageMatch; +import net.crankedpvp.wildpvp.wildpvp.CageMatchManager; +import net.crankedpvp.wildpvp.worldguard.WorldGuardManager; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.ItemStack; + +import java.util.Objects; +import java.util.UUID; + +public class Matches { + private static Matches instance; + + public static Matches getInstance() { + if (instance == null) { + instance = new Matches(); + } + + return instance; + } + + public void open(final Player player) { + final CagePvPPlugin instance = CagePvPPlugin.getInstance(); + Bukkit.getServer().getScheduler().runTaskAsynchronously(instance, new Runnable() { + public void run() { + final WorldGuardManager worldGuardManager = instance.getWorldGuardManager(); + final CombatTagManager combatTagManager = instance.getCombatTagManager(); + final FactionsManager factionsManager = instance.getFactionsManager(); + final CageMatchManager cageMatchManager = instance.getWildPvPManager(); + final ImmuneManager immuneManager = instance.getImmuneManager(); + final FileConfiguration configLoad = instance.getConfig(); + final PlayerData playerData = instance.getPlayerDataManager().getPlayerData(player); + final nInventoryUtil inv = new nInventoryUtil(player, event -> { + ItemStack is = event.getItem(); + if (is.getType() == Material.FENCE_GATE) { + player.playSound(player.getLocation(), Sound.CHEST_CLOSE, 1.0F, 1.0F); + } else if (is.getType() == Material.ARROW && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Items.Next.Unavailable.Displayname"))) || is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Items.Previous.Unavailable.Displayname"))))) { + event.setWillClose(false); + event.setWillDestroy(false); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + } else if (is.getType() == Material.ARROW) { + event.setWillClose(false); + event.setWillDestroy(false); + if (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Items.Next.Available.Displayname")))) { + playerData.setPage(playerData.getPage() + 1); + } else if (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Items.Previous.Available.Displayname")))) { + playerData.setPage(playerData.getPage() - 1); + } + + Matches.this.open(player); + player.playSound(player.getLocation(), Sound.ARROW_HIT, 1.0F, 1.0F); + } else if (is.getType() == Material.BOOK) { + event.setWillClose(false); + event.setWillDestroy(false); + if (cageMatchManager.hasWildPvP(player)) { + Bukkit.getServer().dispatchCommand(player, "1v1 leave"); + Matches.this.open(player); + return; + } + + if (immuneManager.hasImmune(player)) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Immune.Create.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + if (combatTagManager.isTagged(player)) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.CombatTag.Create.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + if (worldGuardManager.hasWorldGuard() && worldGuardManager.isRegionAtLocation(player.getLocation())) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Region.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + if (factionsManager.hasFactions() && !factionsManager.isWilderness(player.getLocation())) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Wilderness.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + if (cageMatchManager.hasWildPvP(player.getLocation().getChunk())) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Chunk.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + if (EntityUtil.getPlayersInChunk(player.getLocation().getChunk()).size() - 1 != 0) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Players.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + CageMatch wildPvPx = cageMatchManager.createWildPvP(player, true); + wildPvPx.showBorder(player); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Queued.Player.Message"))); + player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 1.0F, 1.0F); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(player, ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Queued.Player.Title.Title")), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Queued.Player.Title.SubTitle")), 0, 30, 10); + } + + player.closeInventory(); + if (configLoad.getBoolean("WildPvP.Match.Broadcast")) { + + for (Player all : Bukkit.getOnlinePlayers()) { + if (!all.getUniqueId().equals(player.getUniqueId())) { + all.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Queued.Broadcast.Message").replace("%player", player.getName()))); + } + } + } + } else if (is.getType() == Material.STAINED_GLASS_PANE) { + event.setWillClose(false); + event.setWillDestroy(false); + player.playSound(player.getLocation(), Sound.GLASS, 1.0F, 1.0F); + } else if (is.getType() == Material.SKULL_ITEM) { + event.setWillClose(false); + event.setWillDestroy(false); + UUID uuid = UUID.fromString(Objects.requireNonNull(NBTUtil.getTag(is, "Match"))); + Player creator = Bukkit.getServer().getPlayer(uuid); + if (cageMatchManager.hasWildPvP(creator)) { + final CageMatch cageMatch = cageMatchManager.getWildPvP(creator); + if (cageMatch.isParticipant(player)) { + Bukkit.getServer().dispatchCommand(player, "1v1 leave"); + Matches.this.open(player); + return; + } + + if (event.getClick() == ClickType.LEFT) { + if (cageMatchManager.hasWildPvP(player)) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Already.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + if (cageMatch.hasJoined()) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Started.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + if (immuneManager.hasImmune(player)) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Immune.Join.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + if (combatTagManager.isTagged(player)) { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.CombatTag.Join.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + return; + } + + cageMatch.setJoinLocation(player.getLocation().clone()); + cageMatch.teleport(player); + cageMatch.setJoined(player); + cageMatch.startMatch(); + Bukkit.getServer().getScheduler().runTaskLater(instance, new Runnable() { + public void run() { + cageMatch.showBorder(player); + } + }, 30L); + } else if (event.getClick() == ClickType.RIGHT) { + player.performCommand("invsee " + creator.getName()); + //Invsee.getInstance().open(player, creator); + player.playSound(player.getLocation(), Sound.WOOD_CLICK, 1.0F, 1.0F); + } + } else { + player.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Listeners.Inventory.Matches.Available.Message"))); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0F, 1.0F); + } + } + + }); + inv.setTitle(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Title"))); + inv.setRows(3); + if (cageMatchManager.hasWildPvP(player)) { + inv.addItem(inv.createItem(new ItemStack(Material.BOOK), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Items.Information.Displayname")), configLoad.getStringList("Menus.Matches.Items.Information.Leave.Lore"), new Placeholder[]{new Placeholder("%active", NumberUtil.formatNumberByCommas(cageMatchManager.getActiveWildPvPs().size())), new Placeholder("%queued", NumberUtil.formatNumberByCommas(cageMatchManager.getPendingWildPvPs().size()))}, null, null), 22); + } else { + inv.addItem(inv.createItem(new ItemStack(Material.BOOK), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Items.Information.Displayname")), configLoad.getStringList("Menus.Matches.Items.Information.Create.Lore"), new Placeholder[]{new Placeholder("%active", NumberUtil.formatNumberByCommas(cageMatchManager.getActiveWildPvPs().size())), new Placeholder("%queued", NumberUtil.formatNumberByCommas(cageMatchManager.getPendingWildPvPs().size()))}, null, null), 22); + } + + int index = playerData.getPage() * 36 - 36; + int endIndex = index >= cageMatchManager.getPendingWildPvPs().size() ? cageMatchManager.getPendingWildPvPs().size() - 1 : index + 36; + int invSlot = -1; + int nextEndIndex = 0; + for(; index < endIndex; ++index) { + if (cageMatchManager.getPendingWildPvPs().size() > index) { + ++invSlot; + CageMatch cageMatch = cageMatchManager.getPendingWildPvPs().get(index); + Placeholder[] placeholder; + if (factionsManager.hasFactions()) { + placeholder = new Placeholder[]{new Placeholder("%playersnearby", String.valueOf(EntityUtil.getPlayersNearby(cageMatch.getLocation(), configLoad.getInt("WildPvP.Queued.PlayersNearby.Radius")).size() - 1)), new Placeholder("%player", cageMatch.getCreator().getName()), new Placeholder("%health", String.valueOf((int) cageMatch.getCreator().getHealth())), new Placeholder("%faction", factionsManager.getFactionName(cageMatch.getCreator()))}; + } else { + placeholder = new Placeholder[]{new Placeholder("%playersnearby", String.valueOf(EntityUtil.getPlayersNearby(cageMatch.getLocation(), configLoad.getInt("WildPvP.Queued.PlayersNearby.Radius")).size() - 1)), new Placeholder("%player", cageMatch.getCreator().getName()), new Placeholder("%health", String.valueOf((int) cageMatch.getCreator().getHealth())), new Placeholder("%faction", "")}; + } + + if (cageMatch.isCreator(player)) { + inv.addItem(inv.createItem(SkullUtil.getPlayerSkull(cageMatch.getCreator()), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Items.Match.Displayname").replace("%player", cageMatch.getCreator().getName())), configLoad.getStringList("Menus.Matches.Items.Match.Leave.Lore"), placeholder, null, null), invSlot); + } else { + inv.addItem(inv.createItem(SkullUtil.getPlayerSkull(cageMatch.getCreator()), ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Items.Match.Displayname").replace("%player", cageMatch.getCreator().getName())), configLoad.getStringList("Menus.Matches.Items.Match.Enter.Lore"), placeholder, null, null), invSlot); + } + + inv.createInventory(); + inv.addItemStack(NBTUtil.addTag(inv.getInventory().getItem(invSlot), "Match", cageMatch.getCreator().getUniqueId().toString()), invSlot); + } + + + nextEndIndex = cageMatchManager.getPendingWildPvPs().size() - playerData.getPage() * 36; + } + + if (playerData.getPage() == 1) { + inv.addItem(inv.createItem(new ItemStack(Material.ARROW), configLoad.getString("Menus.Matches.Items.Previous.Unavailable.Displayname"), null, null, null, null), 18); + } else { + inv.addItem(inv.createItem(new ItemStack(Material.ARROW), configLoad.getString("Menus.Matches.Items.Previous.Available.Displayname"), null, null, null, null), 18); + } + + if (nextEndIndex != 0 && nextEndIndex >= 0) { + inv.addItem(inv.createItem(new ItemStack(Material.ARROW), configLoad.getString("Menus.Matches.Items.Next.Available.Displayname"), null, null, null, null), 26); + } else { + inv.addItem(inv.createItem(new ItemStack(Material.ARROW), configLoad.getString("Menus.Matches.Items.Next.Unavailable.Displayname"), null, null, null, null), 26); + } + + Bukkit.getServer().getScheduler().runTask(instance, inv::open); + } + }); + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/playerdata/PlayerData.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/playerdata/PlayerData.java new file mode 100644 index 0000000..7fe5a18 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/playerdata/PlayerData.java @@ -0,0 +1,13 @@ +package net.crankedpvp.wildpvp.playerdata; + +public class PlayerData { + private int page = 1; + + public void setPage(int page) { + this.page = page; + } + + public int getPage() { + return this.page; + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/playerdata/PlayerDataManager.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/playerdata/PlayerDataManager.java new file mode 100644 index 0000000..a7aba72 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/playerdata/PlayerDataManager.java @@ -0,0 +1,48 @@ +package net.crankedpvp.wildpvp.playerdata; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class PlayerDataManager { + private Map playerDataStorage = new HashMap(); + + public PlayerDataManager() { + + for(Player all : Bukkit.getOnlinePlayers()) { + this.createPlayerData(all); + } + + } + + public void createPlayerData(Player player) { + this.playerDataStorage.put(player.getUniqueId(), new PlayerData()); + } + + public PlayerData getPlayerData(UUID uuid) { + return (PlayerData)this.playerDataStorage.get(uuid); + } + + public PlayerData getPlayerData(Player player) { + return (PlayerData)this.playerDataStorage.get(player.getUniqueId()); + } + + public void removePlayerData(UUID uuid) { + this.playerDataStorage.remove(uuid); + } + + public void removePlayerData(Player player) { + this.playerDataStorage.remove(player.getUniqueId()); + } + + public boolean hasPlayerData(UUID uuid) { + return this.playerDataStorage.containsKey(uuid); + } + + public boolean hasPlayerData(Player player) { + return this.playerDataStorage.containsKey(player.getUniqueId()); + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/tasks/MatchesTask.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/tasks/MatchesTask.java new file mode 100644 index 0000000..92fcf9f --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/tasks/MatchesTask.java @@ -0,0 +1,30 @@ +package net.crankedpvp.wildpvp.tasks; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.menus.Matches; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.InventoryView; +import org.bukkit.scheduler.BukkitRunnable; + +public class MatchesTask extends BukkitRunnable { + private final CagePvPPlugin instance; + + public MatchesTask(CagePvPPlugin instance) { + this.instance = instance; + } + + public void run() { + FileConfiguration configLoad = this.instance.getConfig(); + + for (Player all : Bukkit.getOnlinePlayers()) { + InventoryView inv = all.getOpenInventory(); + if (inv != null && inv.getTitle().equalsIgnoreCase(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menus.Matches.Title")))) { + Matches.getInstance().open(all); + } + } + + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/EntityUtil.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/EntityUtil.java new file mode 100644 index 0000000..3ef8724 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/EntityUtil.java @@ -0,0 +1,35 @@ +package net.crankedpvp.wildpvp.utils; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class EntityUtil { + public static List getPlayersNearby(Location location, int radius) { + List players = new ArrayList<>(); + for (Entity entity : location.getWorld().getNearbyEntities(location, radius, 255.0D, radius)) { + if (!(entity instanceof Player)) + continue; + players.add((Player)entity); + } + return players; + } + + public static List getPlayersInChunk(Chunk chunk) { + List players = new ArrayList<>(); + byte b; + int i; + Entity[] arrayOfEntity; + for (i = (arrayOfEntity = chunk.getEntities()).length, b = 0; b < i; ) { + Entity entity = arrayOfEntity[b]; + if (entity instanceof Player) + players.add((Player)entity); + b = (byte)(b + 1); + } + return players; + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NBTUtil.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NBTUtil.java new file mode 100644 index 0000000..d997586 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NBTUtil.java @@ -0,0 +1,66 @@ +package net.crankedpvp.wildpvp.utils; + +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class NBTUtil { + private static final Class CraftItemStackClass = NMSUtil.getCraftClass("inventory.CraftItemStack"); + private static final Class NBTTagCompoundClass = NMSUtil.getNMSClass("NBTTagCompound"); + private static final Class NBTTagStringClass = NMSUtil.getNMSClass("NBTTagString"); + private static final Class NBTBaseClass = NMSUtil.getNMSClass("NBTBase"); + + public static ItemStack addTag(ItemStack item, String tag, String data) { + try { + Object NMSItemStack = CraftItemStackClass.getMethod("asNMSCopy", ItemStack.class).invoke((Object)null, item); + Field tagField = NMSItemStack.getClass().getDeclaredField("tag"); + tagField.setAccessible(true); + Object NBTTagCompound = tagField.get(NMSItemStack); + if (NBTTagCompound == null) { + NBTTagCompound = NBTTagCompoundClass.newInstance(); + } + + Object NBTTagString = NBTTagStringClass.getConstructor(String.class).newInstance(data); + Method setMethod = NBTTagCompoundClass.getMethod("set", String.class, NBTBaseClass); + setMethod.setAccessible(true); + setMethod.invoke(NBTTagCompound, tag, NBTTagString); + tagField.set(NMSItemStack, NBTTagCompound); + Object object1 = CraftItemStackClass.getMethod("asBukkitCopy", NMSItemStack.getClass()).invoke((Object)null, NMSItemStack); + return (ItemStack)object1; + } catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | NoSuchFieldException | InstantiationException | IllegalAccessException var9) { + var9.printStackTrace(); + return null; + } + } + + public static String getTag(ItemStack item, String tag) { + try { + Object NMSItemStack = CraftItemStackClass.getMethod("asNMSCopy", ItemStack.class).invoke((Object)null, item); + Field tagField = NMSItemStack.getClass().getDeclaredField("tag"); + tagField.setAccessible(true); + Object NBTTagCompound = tagField.get(NMSItemStack); + if (NBTTagCompound == null) { + return null; + } else { + Method getStringMethod = NBTTagCompound.getClass().getMethod("getString", String.class); + getStringMethod.setAccessible(true); + return (String)getStringMethod.invoke(NBTTagCompound, tag); + } + } catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | NoSuchFieldException | IllegalAccessException var6) { + var6.printStackTrace(); + return null; + } + } + + public static boolean hasTag(ItemStack item, String tag) { + String data = getTag(item, tag); + return data != null && data != ""; + } + + public static boolean hasTag(ItemStack item, String tag, String searchData) { + String data = getTag(item, tag); + return data != null && data.equals(searchData); + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NMSUtil.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NMSUtil.java new file mode 100644 index 0000000..1aeb62c --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NMSUtil.java @@ -0,0 +1,96 @@ +package net.crankedpvp.wildpvp.utils; + + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.lang.reflect.Field; + +public class NMSUtil { + public static String getVersion(){ + String name = Bukkit.getServer().getClass().getPackage().getName(); + return name.substring(name.lastIndexOf('.') + 1) + "."; + } + + public static int getVersionNumber(){ + String name = getVersion().substring(3); + return Integer.parseInt(name.substring(0, name.length() - 4)); + } + + public static int getVersionReleaseNumber(){ + String NMSVersion = getVersion(); + return Integer.parseInt(NMSVersion.substring(NMSVersion.length() - 2).replace(".", "")); + } + + public static Class getNMSClass(String className){ + try { + String fullName = "net.minecraft.server." + getVersion() + className; + Class clazz = Class.forName(fullName); + return clazz; + } catch (Exception e){ + e.printStackTrace(); + return null; + } + } + + public static Class getCraftClass(String className){ + try { + String fullName = "org.bukkit.craftbukkit." + getVersion() + className; + Class clazz = Class.forName(fullName); + return clazz; + } catch (Exception e){ + e.printStackTrace(); + return null; + } + } + + public static Field getField(Class clazz, String name, boolean declared){ + try { + Field field; + if(declared) { + field = clazz.getDeclaredField(name); + } else{ + field = clazz.getField(name); + } + field.setAccessible(true); + return field; + } catch (Exception e){ + e.printStackTrace(); + return null; + } + } + + public static Object getFieldObject(Object object, Field field){ + try { + return field.get(object); + } catch (Exception e){ + e.printStackTrace(); + return null; + } + } + + public static void setField(Object object, String fieldName, Object fieldValue, boolean declared){ + try { + Field field; + if(declared) { + field = object.getClass().getDeclaredField(fieldName); + } else{ + field = object.getClass().getField(fieldName); + } + field.setAccessible(true); + field.set(object, fieldValue); + } catch (Exception e){ + e.printStackTrace(); + } + } + + public static void sendPacket(Player player, Object packet){ + try { + Object handle = player.getClass().getMethod("getHandle", new Class[0]).invoke(player); + Object playerConnection = handle.getClass().getField("playerConnection").get(handle); + playerConnection.getClass().getMethod("sendPacket", new Class[]{getNMSClass("Packet")}).invoke(playerConnection, packet); + } catch (Exception e){ + e.printStackTrace(); + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NumberUtil.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NumberUtil.java new file mode 100644 index 0000000..bac6523 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/NumberUtil.java @@ -0,0 +1,38 @@ +package net.crankedpvp.wildpvp.utils; + +import java.math.BigInteger; +import java.text.DecimalFormat; + +public class NumberUtil { + private static final DecimalFormat decimalFormat = new DecimalFormat("##.#"); + + public static String formatNumberByCommas(int number){ + return String.format("%,d", number); + } + + public static String formatNumberByCommas(String number){ + String numberValue = "", numberDecimalValue = ""; + if(number.contains(".")) { + numberDecimalValue = "." + number.split("\\.")[1]; + numberValue = number.replace(numberDecimalValue, ""); + } else{ + return String.format("%,d", new BigInteger(number)); + } + if(numberDecimalValue.equals(".0")) numberDecimalValue = ""; + return String.format("%,d", new BigInteger(numberValue)) + numberDecimalValue; + } + + public static String formatNumberByDecimal(float number){ + return decimalFormat.format(number); + } + + public static String formatNumberBySuffix(double number){ + if(number < 1000.0D) return String.valueOf(number); + int exp = (int) (Math.log(number) / Math.log(1000.0D)); + return String.format("%.1f%c", number / Math.pow(1000.0D, exp), "kMBTPE".charAt(exp - 1)); + } + + public static int formatNumberByText(String text) { + return Integer.parseInt(text.replace("k", "000").replace("m", "000000").replace("b", "000000000")); + } +} \ No newline at end of file diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/SkullUtil.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/SkullUtil.java new file mode 100644 index 0000000..f850477 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/SkullUtil.java @@ -0,0 +1,25 @@ +package net.crankedpvp.wildpvp.utils; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import java.lang.reflect.InvocationTargetException; + +public class SkullUtil { + public static ItemStack getPlayerSkull(Player player) { + ItemStack is = new ItemStack(Material.SKULL_ITEM, 1, (short)3); + SkullMeta sm = (SkullMeta)is.getItemMeta(); + + try { + Object EntityPlayer = player.getClass().getMethod("getHandle").invoke(player); + NMSUtil.setField(sm, "profile", NMSUtil.getFieldObject(EntityPlayer, NMSUtil.getField(EntityPlayer.getClass().getSuperclass(), "bH", true)), true); + } catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | IllegalAccessException var4) { + var4.printStackTrace(); + } + + is.setItemMeta(sm); + return is; + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/TitleManager.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/TitleManager.java new file mode 100644 index 0000000..70e35a5 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/TitleManager.java @@ -0,0 +1,32 @@ +package net.crankedpvp.wildpvp.utils; + +import org.bukkit.entity.Player; + +import java.lang.reflect.Constructor; + +public class TitleManager { + private static final Class PacketPlayOutTitle = NMSUtil.getNMSClass("PacketPlayOutTitle"); + private static final Class IChatBaseComponent = NMSUtil.getNMSClass("IChatBaseComponent"); + + public static void sendTitle(Player player, String titleText, String subtitleText, int fadeIn, int stay, int fadeOut) { + try { + assert PacketPlayOutTitle != null; + Object enumTitle = PacketPlayOutTitle.getDeclaredClasses()[0].getField("TITLE").get((Object)null); + assert IChatBaseComponent != null; + Object titleChat = IChatBaseComponent.getDeclaredClasses()[0].getMethod("a", String.class).invoke((Object)null, "{\"text\":\"" + titleText + "\"}"); + Object enumSubtitle = PacketPlayOutTitle.getDeclaredClasses()[0].getField("SUBTITLE").get((Object)null); + Object subtitleChat = IChatBaseComponent.getDeclaredClasses()[0].getMethod("a", String.class).invoke((Object)null, "{\"text\":\"" + subtitleText + "\"}"); + Object enumTimes = PacketPlayOutTitle.getDeclaredClasses()[0].getField("TIMES").get((Object)null); + Constructor titleConstructor = PacketPlayOutTitle.getConstructor(PacketPlayOutTitle.getDeclaredClasses()[0], IChatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE); + Object titlePacket = titleConstructor.newInstance(enumTitle, titleChat, 0, 0, 0); + Object subtitlePacket = titleConstructor.newInstance(enumSubtitle, subtitleChat, 0, 0, 0); + Object timesPacket = titleConstructor.newInstance(enumTimes, null, fadeIn, stay, fadeOut); + NMSUtil.sendPacket(player, titlePacket); + NMSUtil.sendPacket(player, subtitlePacket); + NMSUtil.sendPacket(player, timesPacket); + } catch (Exception var15) { + var15.printStackTrace(); + } + + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/inventory/Placeholder.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/inventory/Placeholder.java new file mode 100644 index 0000000..c39d036 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/inventory/Placeholder.java @@ -0,0 +1,20 @@ +package net.crankedpvp.wildpvp.utils.inventory; + +public class Placeholder { + private final String placeholder; + + private final String result; + + public Placeholder(String placeholder, String result){ + this.placeholder = placeholder; + this.result = result; + } + + public String getPlaceholder(){ + return this.placeholder; + } + + public String getResult(){ + return this.result; + } +} \ No newline at end of file diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/inventory/nInventoryUtil.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/inventory/nInventoryUtil.java new file mode 100644 index 0000000..e1c9cce --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/utils/inventory/nInventoryUtil.java @@ -0,0 +1,298 @@ +package net.crankedpvp.wildpvp.utils.inventory; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class nInventoryUtil { + private final Player player; + + private Listener listener; + + private Inventory inv; + + private String title; + + private int size = 9; + + private InventoryType type; + + private final Map items = new HashMap<>(); + + public nInventoryUtil(final Player player, final ClickEventHandler handler){ + this.player = player; + if(handler != null) { + this.listener = new Listener() { + @EventHandler + public void onInventoryClick(InventoryClickEvent event){ + if(! (event.getWhoClicked() instanceof Player)) return; + if(nInventoryUtil.this.inv != null && event.getInventory().equals(nInventoryUtil.this.inv)) { + event.setCancelled(true); + if(event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR || event.getRawSlot() > nInventoryUtil.this.size) + return; + ClickEvent clickEvent = new ClickEvent(event.getClick(), event.getSlot(), event.getCurrentItem()); + handler.onClick(clickEvent); + if(! clickEvent.getCancelled()) event.setCancelled(false); + if(clickEvent.getWillClose()) event.getWhoClicked().closeInventory(); + if(clickEvent.getWillDestroy()) nInventoryUtil.this.destroy(); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event){ + if(! (event.getPlayer() instanceof Player)) return; + Inventory inv = event.getInventory(); + if(inv.equals(nInventoryUtil.this.inv)) { + inv.clear(); + nInventoryUtil.this.destroy(); + } + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event){ + if(event.getPlayer().getUniqueId().equals(player.getUniqueId())) nInventoryUtil.this.destroy(); + } + }; + Bukkit.getPluginManager().registerEvents(this.listener, CagePvPPlugin.getInstance()); + } + } + + public void addItem(Item item, int... slots){ + byte b; + int i; + int[] arrayOfInt; + for(i = (arrayOfInt = slots).length, b = 0; b < i; ) { + int slotList = arrayOfInt[b]; + this.items.put(slotList, item.prepareItem()); + b++; + } + } + + public void addItemStack(ItemStack is, int... slots){ + byte b; + int i; + int[] arrayOfInt; + for(i = (arrayOfInt = slots).length, b = 0; b < i; ) { + int slotList = arrayOfInt[b]; + this.items.put(slotList, is); + b++; + } + } + + public Map getItems(){ + return this.items; + } + + public Item createItem(ItemStack is, String itemDisplayname, List itemLore, Placeholder[] placeholders, Enchantment[] itemEnchantments, ItemFlag[] itemFlags){ + return new Item(is, itemDisplayname, itemLore, placeholders, itemEnchantments, itemFlags); + } + + public void open(){ + createInventory(); + this.player.openInventory(this.inv); + } + + public void setTitle(String title){ + this.title = title; + } + + public void setType(InventoryType type){ + this.type = type; + } + + public void setRows(int rows){ + if(rows > 6 || rows < 0) { + this.size = 9; + return; + } + this.size = rows * 9; + } + + public void setSize(int size){ + this.size = size; + } + + public void createInventory(){ + if(this.type == null) { + if(this.title == null) { + this.inv = Bukkit.createInventory(null, this.size); + } else{ + this.inv = Bukkit.createInventory(null, this.size, this.title); + } + } else if(this.title == null) { + this.inv = Bukkit.createInventory(null, this.type); + } else{ + this.inv = Bukkit.createInventory(null, this.type, this.title); + } + for(int i = 0; i < this.items.size(); i++) { + int slot = (Integer) this.items.keySet().toArray()[i]; + this.inv.setItem(slot, this.items.get(slot)); + } + } + + public Inventory getInventory(){ + return this.inv; + } + + public void setInventory(Inventory inv){ + this.inv = inv; + } + + public void destroy(){ + if(this.listener != null) HandlerList.unregisterAll(this.listener); + this.title = null; + this.type = null; + this.inv = null; + this.items.clear(); + this.listener = null; + } + + public interface ClickEventHandler { + void onClick(ClickEvent param1ClickEvent); + } + + public class Item { + private final ItemStack is; + + private final String itemDisplayname; + + private List itemLore; + + private final Placeholder[] placeholders; + + private final Enchantment[] itemEnchantments; + + private final ItemFlag[] itemFlags; + + public Item(ItemStack is, String itemDisplayname, List itemLore, Placeholder[] placeholders, Enchantment[] itemEnchantments, ItemFlag[] itemFlags){ + this.is = is; + this.itemDisplayname = ChatColor.translateAlternateColorCodes('&', itemDisplayname); + this.itemLore = itemLore; + this.placeholders = placeholders; + this.itemEnchantments = itemEnchantments; + this.itemFlags = itemFlags; + } + + public void setLore(){ + if(this.itemLore != null) { + ArrayList formattedItemLore = new ArrayList<>(); + for(String itemLoreList : this.itemLore) { + if(this.placeholders != null) { + byte b; + int i; + Placeholder[] arrayOfPlaceholder; + for(i = (arrayOfPlaceholder = this.placeholders).length, b = 0; b < i; ) { + Placeholder placeholderList = arrayOfPlaceholder[b]; + if(itemLoreList.contains(placeholderList.getPlaceholder())) + itemLoreList = ChatColor.translateAlternateColorCodes('&', itemLoreList.replace(placeholderList.getPlaceholder(), placeholderList.getResult())); + b++; + } + } + formattedItemLore.add(ChatColor.translateAlternateColorCodes('&', itemLoreList)); + } + this.itemLore.clear(); + this.itemLore = formattedItemLore; + } + } + + public void setItemMeta(){ + ItemMeta im = this.is.hasItemMeta() ? this.is.getItemMeta() : Bukkit.getItemFactory().getItemMeta(this.is.getType()); + im.setDisplayName(this.itemDisplayname); + im.setLore(this.itemLore); + if(this.itemFlags != null) im.addItemFlags(this.itemFlags); + if(this.itemEnchantments != null) { + byte b; + int i; + Enchantment[] arrayOfEnchantment; + for(i = (arrayOfEnchantment = this.itemEnchantments).length, b = 0; b < i; ) { + Enchantment itemEnchantmentList = arrayOfEnchantment[b]; + im.addEnchant(itemEnchantmentList, 1, true); + b++; + } + } + this.is.setItemMeta(im); + } + + public ItemStack prepareItem(){ + setLore(); + setItemMeta(); + return this.is; + } + } + + public class ClickEvent { + private final ClickType click; + + private final int slot; + + private final ItemStack is; + + private boolean close = true; + + private boolean destroy = true; + + private boolean cancelled = true; + + public ClickEvent(ClickType click, int slot, ItemStack is){ + this.click = click; + this.slot = slot; + this.is = is; + } + + public ClickType getClick(){ + return this.click; + } + + public int getSlot(){ + return this.slot; + } + + public ItemStack getItem(){ + return this.is; + } + + public boolean getWillClose(){ + return this.close; + } + + public void setWillClose(boolean close){ + this.close = close; + } + + public boolean getWillDestroy(){ + return this.destroy; + } + + public void setWillDestroy(boolean destroy){ + this.destroy = destroy; + } + + public boolean getCancelled(){ + return this.cancelled; + } + + public void setCancelled(boolean cancelled){ + this.cancelled = cancelled; + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/wildpvp/CageMatch.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/wildpvp/CageMatch.java new file mode 100644 index 0000000..adb4c88 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/wildpvp/CageMatch.java @@ -0,0 +1,229 @@ +package net.crankedpvp.wildpvp.wildpvp; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import net.crankedpvp.wildpvp.utils.TitleManager; +import org.bukkit.*; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Random; + + +public class CageMatch { + private final CagePvPPlugin instance; + private final Player creator; + private Player joined; + private final Location location; + private Location joinLocation; + private boolean grace = true; + private boolean ended = false; + + public CageMatch(CagePvPPlugin instance, Player creator, Location location) { + this.instance = instance; + this.creator = creator; + this.location = location; + } + + public Player getCreator() { + return this.creator; + } + + public boolean isCreator(Player player) { + return this.creator.getUniqueId().equals(player.getUniqueId()); + } + + public void setJoined(Player joined) { + this.joined = joined; + } + + public Player getJoined() { + return this.joined; + } + + public boolean isJoined(Player player) { + return this.joined != null && this.joined.getUniqueId().equals(player.getUniqueId()); + } + + public boolean hasJoined() { + return this.joined != null; + } + + public boolean isParticipant(Player player) { + return this.creator.getUniqueId().equals(player.getUniqueId()) || this.joined != null && this.joined.getUniqueId().equals(player.getUniqueId()); + } + + public Location getLocation() { + return this.location; + } + + public void setJoinLocation(Location joinLocation) { + this.joinLocation = joinLocation; + } + + public Location getJoinLocation() { + return this.joinLocation; + } + + public void teleportToJoinLocation(Player player) { + Location location = this.joinLocation.clone(); + if (location.getBlock().getType().isSolid() || location.clone().add(0.0D, 1.0D, 0.0D).getBlock().getType().isSolid()) { + location.setY(location.getWorld().getHighestBlockYAt(location)); + } + + player.teleport(location, TeleportCause.UNKNOWN); + } + + public Chunk getChunk() { + return this.location.getChunk(); + } + + public boolean isGrace() { + return this.grace; + } + + public void setEnded(boolean ended) { + this.ended = ended; + } + + public boolean hasEnded() { + return this.ended; + } + + public boolean hasStarted() { + return this.creator != null && this.joined != null; + } + + public void showBorder(Player player) { + Chunk chunk = this.getChunk(); + Location corner1 = chunk.getBlock(0, 0, 0).getLocation(); + Location corner2 = chunk.getBlock(15, 0, 0).getLocation(); + Location corner3 = chunk.getBlock(0, 0, 15).getLocation(); + Location corner4 = chunk.getBlock(15, 0, 15).getLocation(); + + for(int y = 0; y < 130; ++y) { + for(int xz = 0; xz < 15; ++xz) { + corner1 = chunk.getBlock(xz, y, 0).getLocation(); + corner2 = chunk.getBlock(15, y, xz).getLocation(); + corner3 = chunk.getBlock(15 - xz, y, 15).getLocation(); + corner4 = chunk.getBlock(0, y, 15 - xz).getLocation(); + if (corner1.getBlock().getType() == Material.AIR) { + //player.sendBlockChange(corner1, Material.STAINED_GLASS, (byte)14); + player.sendBlockChange(corner1, Material.IRON_FENCE, (byte)0); + + } + + if (corner2.getBlock().getType() == Material.AIR) { + //player.sendBlockChange(corner2, Material.STAINED_GLASS, (byte)14); + player.sendBlockChange(corner2, Material.IRON_FENCE, (byte)0); + + } + + if (corner3.getBlock().getType() == Material.AIR) { + //player.sendBlockChange(corner3, Material.STAINED_GLASS, (byte)14); + player.sendBlockChange(corner3, Material.IRON_FENCE, (byte)0); + + } + + if (corner4.getBlock().getType() == Material.AIR) { + //player.sendBlockChange(corner4, Material.STAINED_GLASS, (byte)14); + player.sendBlockChange(corner4, Material.IRON_FENCE, (byte)0); + + } + } + } + + } + + public void hideBorder(Player player) { + Chunk chunk = this.getChunk(); + Location corner1 = chunk.getBlock(0, 0, 0).getLocation(); + Location corner2 = chunk.getBlock(15, 0, 0).getLocation(); + Location corner3 = chunk.getBlock(0, 0, 15).getLocation(); + Location corner4 = chunk.getBlock(15, 0, 15).getLocation(); + + for(int y = 0; y < 130; ++y) { + for(int xz = 0; xz < 15; ++xz) { + corner1 = chunk.getBlock(xz, y, 0).getLocation(); + corner2 = chunk.getBlock(15, y, xz).getLocation(); + corner3 = chunk.getBlock(15 - xz, y, 15).getLocation(); + corner4 = chunk.getBlock(0, y, 15 - xz).getLocation(); + if (corner1.getBlock().getType() == Material.AIR) { + player.sendBlockChange(corner1, Material.AIR, (byte)0); + } + + if (corner2.getBlock().getType() == Material.AIR) { + player.sendBlockChange(corner2, Material.AIR, (byte)0); + } + + if (corner3.getBlock().getType() == Material.AIR) { + player.sendBlockChange(corner3, Material.AIR, (byte)0); + } + + if (corner4.getBlock().getType() == Material.AIR) { + player.sendBlockChange(corner4, Material.AIR, (byte)0); + } + } + } + + } + + public void teleport(Player player) { + Random random = new Random(); + Location location = this.getChunk().getBlock(random.nextInt(14) + 1, 0, random.nextInt(14) + 1).getLocation().clone(); + location.setY(location.getWorld().getHighestBlockYAt(location)); + player.teleport(location, TeleportCause.UNKNOWN); + } + + public void startMatch() { + if (this.joined != null) { + final FileConfiguration configLoad = this.instance.getConfig(); + this.creator.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Joined.Creator.Message").replace("%player", this.joined.getName()))); + this.creator.playSound(this.creator.getLocation(), Sound.ENDERMAN_TELEPORT, 1.0F, 5.0F); + if (configLoad.getBoolean("WildPvP.Match.Title")) { + TitleManager.sendTitle(this.creator, ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Joined.Creator.Title.Title").replace("%player", this.joined.getName())), ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Joined.Creator.Title.SubTitle").replace("%player", this.joined.getName())), 0, 30, 10); + } + + this.joined.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Joined.Joiner.Message").replace("%player", this.creator.getName()))); + this.joined.playSound(this.joined.getLocation(), Sound.ENDERMAN_TELEPORT, 1.0F, 5.0F); + (new BukkitRunnable() { + int countdown = 10; + + public void run() { + if (!CageMatch.this.ended && this.countdown >= 0) { + if (this.countdown == 8) { + TitleManager.sendTitle(CageMatch.this.creator, ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Versus.Title.Title").replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName())), ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Versus.Title.SubTitle").replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName())), 10, 30, 10); + TitleManager.sendTitle(CageMatch.this.joined, ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Versus.Title.Title").replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName())), ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Versus.Title.SubTitle").replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName())), 10, 30, 10); + CageMatch.this.creator.playSound(CageMatch.this.creator.getLocation(), Sound.VILLAGER_YES, 0.5F, 1.0F); + CageMatch.this.joined.playSound(CageMatch.this.joined.getLocation(), Sound.VILLAGER_YES, 0.5F, 1.0F); + } else if (this.countdown > 0 && this.countdown <= 5) { + CageMatch.this.creator.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ending.Message").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.joined.getName()))); + CageMatch.this.joined.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ending.Message").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.creator.getName()))); + TitleManager.sendTitle(CageMatch.this.creator, ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ending.Title.Title").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.joined.getName())), ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ending.Title.SubTitle").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.joined.getName())), 0, 30, 0); + TitleManager.sendTitle(CageMatch.this.joined, ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ending.Title.Title").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.creator.getName())), ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ending.Title.SubTitle").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.creator.getName())), 0, 30, 0); + CageMatch.this.creator.playSound(CageMatch.this.creator.getLocation(), Sound.NOTE_STICKS, 1.0F, 1.0F); + CageMatch.this.joined.playSound(CageMatch.this.joined.getLocation(), Sound.NOTE_STICKS, 1.0F, 1.0F); + } else if (this.countdown == 0) { + CageMatch.this.grace = false; + this.cancel(); + CageMatch.this.creator.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ended.Message").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.joined.getName()))); + CageMatch.this.joined.sendMessage(ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ended.Message").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.creator.getName()))); + TitleManager.sendTitle(CageMatch.this.creator, ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ended.Title.Title").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.joined.getName())), ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ended.Title.SubTitle").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.joined.getName())), 0, 30, 10); + TitleManager.sendTitle(CageMatch.this.joined, ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ended.Title.Title").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.creator.getName())), ChatColor.translateAlternateColorCodes('&', configLoad.getString("WildPvP.Countdown.Grace.Ended.Title.SubTitle").replace("%countdown", String.valueOf(this.countdown)).replace("%creator", CageMatch.this.creator.getName()).replace("%joined", CageMatch.this.joined.getName()).replace("%versus", CageMatch.this.creator.getName())), 0, 30, 10); + CageMatch.this.creator.playSound(CageMatch.this.creator.getLocation(), Sound.WITHER_SHOOT, 1.0F, 10.0F); + CageMatch.this.joined.playSound(CageMatch.this.joined.getLocation(), Sound.WITHER_SHOOT, 1.0F, 10.0F); + instance.getCombatTagManager().giveTag(CageMatch.this.creator); + instance.getCombatTagManager().giveTag(CageMatch.this.joined); + + } + + --this.countdown; + } else { + this.cancel(); + } + } + }).runTaskTimerAsynchronously(this.instance, 0L, 20L); + } + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/wildpvp/CageMatchManager.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/wildpvp/CageMatchManager.java new file mode 100644 index 0000000..2febb59 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/wildpvp/CageMatchManager.java @@ -0,0 +1,110 @@ +package net.crankedpvp.wildpvp.wildpvp; + +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Chunk; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class CageMatchManager { + private final CagePvPPlugin instance; + private List cageMatches = new ArrayList(); + + public CageMatchManager(CagePvPPlugin instance) { + this.instance = instance; + } + + public void onDisable() { + + for(CageMatch cageMatch : this.cageMatches) { + cageMatch.hideBorder(cageMatch.getCreator()); + if(cageMatch.hasJoined()) { + cageMatch.teleportToJoinLocation(cageMatch.getJoined()); + cageMatch.hideBorder(cageMatch.getJoined()); + } + } + + } + + public CageMatch createWildPvP(Player player, boolean teleport) { + CageMatch cageMatch = new CageMatch(this.instance, player, player.getLocation().clone()); + if (teleport) { + cageMatch.teleport(player); + } + + this.cageMatches.add(cageMatch); + return cageMatch; + } + + public void removeWildPvP(CageMatch cageMatch) { + this.cageMatches.remove(cageMatch); + } + + public CageMatch getWildPvP(Player player) { + Iterator var2 = this.cageMatches.iterator(); + + CageMatch cageMatch; + do { + if (!var2.hasNext()) { + return null; + } + + cageMatch = (CageMatch)var2.next(); + } while(!cageMatch.isCreator(player) && !cageMatch.isJoined(player)); + + return cageMatch; + } + + public boolean hasWildPvP(Player player) { + return this.getWildPvP(player) != null; + } + + public CageMatch getWildPvP(Chunk chunk) { + Iterator var2 = this.cageMatches.iterator(); + + CageMatch cageMatch; + do { + if (!var2.hasNext()) { + return null; + } + + cageMatch = (CageMatch)var2.next(); + } while(cageMatch.getChunk().getX() != chunk.getX() || cageMatch.getChunk().getZ() != chunk.getZ()); + + return cageMatch; + } + + public boolean hasWildPvP(Chunk chunk) { + return this.getWildPvP(chunk) != null; + } + + public List getActiveWildPvPs() { + List activeCageMatches = new ArrayList(); + + for(CageMatch cageMatch : this.cageMatches) { + if(cageMatch.hasJoined()) { + activeCageMatches.add(cageMatch); + } + } + + return activeCageMatches; + } + + public List getPendingWildPvPs() { + List pendingCageMatches = new ArrayList(); + + for(CageMatch cageMatch : this.cageMatches) { + if(!cageMatch.hasJoined()) { + pendingCageMatches.add(cageMatch); + } + } + + return pendingCageMatches; + } + + public List getWildPvPs() { + return this.cageMatches; + } +} diff --git a/CagePvP/src/main/java/net/crankedpvp/wildpvp/worldguard/WorldGuardManager.java b/CagePvP/src/main/java/net/crankedpvp/wildpvp/worldguard/WorldGuardManager.java new file mode 100644 index 0000000..6aa6be4 --- /dev/null +++ b/CagePvP/src/main/java/net/crankedpvp/wildpvp/worldguard/WorldGuardManager.java @@ -0,0 +1,42 @@ +package net.crankedpvp.wildpvp.worldguard; + +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.managers.RegionManager; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.plugin.PluginManager; + +public class WorldGuardManager { + private WorldGuardPlugin worldGuard; + + public WorldGuardManager() { + registerWorldGuard(); + } + + public void registerWorldGuard() { + PluginManager pluginManager = Bukkit.getServer().getPluginManager(); + if (pluginManager.getPlugin("WorldGuard") != null) { + System.out.println("Hooked into Worldguard!"); + this.worldGuard = (WorldGuardPlugin) pluginManager.getPlugin("WorldGuard"); + } else { + System.out.println("Could not find worldguard :("); + } + } + + public boolean isRegionAtLocation(Location location) { + RegionManager regionManager = this.worldGuard.getRegionManager(location.getWorld()); + ApplicableRegionSet regionsAtLocation = regionManager.getApplicableRegions(location); + return regionsAtLocation.size() != 0; + } + + public WorldGuardPlugin getWorldGuard() { + if (this.worldGuard == null) + registerWorldGuard(); + return this.worldGuard; + } + + public boolean hasWorldGuard() { + return (getWorldGuard() != null); + } +} diff --git a/CagePvP/src/main/resources/config.yml b/CagePvP/src/main/resources/config.yml new file mode 100644 index 0000000..348a6e2 --- /dev/null +++ b/CagePvP/src/main/resources/config.yml @@ -0,0 +1,308 @@ +Commands: + WildPvP: + Leave: + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou are not in a &6&nWildPvP&r &ematch." + CombatTag: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eleave a &6&nWildPvP&r &ematch while combat tagged." + Left: + Player: + Participant: + Message: "&6&lWild PvP &8➥ &eYou have &c&lLEFT ðe &6&nWildPvP&r &ematch with the player &7%player&e." + Alone: + Message: "&6&lWild PvP &8➥ &eYou have &c&lENDED &eyour &6&nWildPvP&r &ematch." + Participant: + Message: "&6&lWild PvP &8➥ &7%player &ehas &c&lLEFT ðe &6&nWildPvP&r &ematch." + Title: + Title: "&6&nWildPvP" + SubTitle: "&cMatch Ended!" + Teleported: + Message: "&6&lWild PvP &8➥ &7&oYou have been teleported to your last location." +WildPvP: + EntityExplosion: + Enable: false + Match: + Broadcast: true + Title: true + ItemPickupBlacklist: + - "POTION" + BlockInteractBlacklist: + - "CHEST" + - "ANVIL" + - "BEACON" + - "ENCHANTMENT_TABLE" + - "ENDER_CHEST" + - "FURNACE" + - "HOPPER" + - "TRAPPED_CHEST" + Queued: + PlayersNearby: + Radius: 30 + Join: + Commands: + - "spawn %player" + Joined: + Creator: + Message: "&6&lWild PvP &8➥ &7%player &ehas &a&lJOINED &eyour &6&nWildPvP&r &ematch." + Title: + Title: "&6&nWildPvP" + SubTitle: "&a%player Joined" + Joiner: + Message: "&6&lWild PvP &8➥ &eYou have &a&lJOINED ðe player &7%player's &6&nWildPvP&r &ematch." + Countdown: + Versus: + Title: + Title: "&6&nWildPvP" + SubTitle: "&a%creator v %joined" + Grace: + Ending: + Message: "&6&lWild PvP &8➥ &8[&6WildPvP &7| &e%versus&8] &dGrace Ending in %countdowns..." + Title: + Title: "&6&nWildPvP" + SubTitle: "&dGrace Ending in %countdowns..." + Ended: + Message: "&6&lWild PvP &8➥ &8[&6WildPvP &7| &e%versus&8] &dGrace Ended!" + Title: + Title: "&6&nWildPvP" + SubTitle: "&dGrace Ended!" +Immune: + Countdown: + Started: + Message: "&6&lWild PvP &8➥ &eYou will receive &b&lIMMUNITY &efor &d20 Seconds&e." + Ending: + Message: "&6&lWild PvP &8➥ &8[&6WildPvP&8] &dImmunity Ending in %countdowns..." + Title: + Title: "&b&nIMMUNE" + SubTitle: "&dEnding in %countdowns..." + Ended: + Message: "&6&lWild PvP &8➥ &8[&6WildPvP&8] &cYou are no longer &4&lIMMUNE&c." + Title: + Title: "&b&nIMMUNE" + SubTitle: "&cImmunity Ended!" +Listeners: + Inventory: + Matches: + Immune: + Create: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ecreate a &6&nWildPvP&r &ematch while immune." + Join: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ejoin a &6&nWildPvP&r &ematch while immune." + CombatTag: + Create: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ecreate a &6&nWildPvP&r &ematch while combat tagged." + Join: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ejoin a &6&nWildPvP&r &ematch while combat tagged." + Region: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ecreate a &6&nWildPvP&r &ematch while in a region." + Wilderness: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ecreate a &6&nWildPvP&r &ematch because you must be in the &2&nWilderness&e." + Chunk: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ecreate a &6&nWildPvP&r &ematch in a chunk that has a &6&nWildPvP&r &ematch." + Queued: + Player: + Message: "&6&lWild PvP &8➥ &aInfo&8: &eYou have &b&lQUEUED &ea &6&nWildPvP&r &ematch." + Title: + Title: "&6&nWildPvP" + SubTitle: "&aQueued..." + Broadcast: + Message: "&6&lWild PvP &8➥ &7%player &ehas &b&lQUEUED &ea &6&nWildPvP&r &ematch." + Available: + Message: "&6&lWild PvP &8➥ &cError&8: &eThat &6&nWildPvP&r &ematch is no longer available." + Already: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou are already in a &6&nWildPvP&r &ematch." + Started: + Message: "&6&lWild PvP &8➥ &cError&8: &eThat &6&nWildPvP&r &ematch has already started." + Players: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ecreate a &6&nWildPvP&r &ematch while there's a player in the chunk." + Damage: + Immune: + Immune: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &edamage players while &b&lIMMUNE &eafter a &6&nWildPvP&r &ematch." + Player: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &edamage that player while they're &b&lIMMUNE &eafter a &6&nWildPvP&r &ematch." + Match: + Participant: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &edamage players while in a &6&nWildPvP&r &ematch." + Player: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &edamage that player while they're in a &6&nWildPvP&r &ematch." + Grace: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &edamage that player until &d&nGrace Period&r &ehas ended." + Command: + AllowedCommands: + - "heal" + - "feed" + - "eat" + - "near" + - "fix" + - "fixall" + - "repair" + - "repairall" + - "bless" + - "enderchest" + - "echest" + - "ec" + - "playervault" + - "playervaults" + - "pv" + - "shop" + - "factions" + - "f" + - "msgtoggle" + - "msg" + - "w" + - "m" + - "t" + - "pm" + - "tell" + - "whisper" + - "reply" + - "r" + - "paytoggle" + - "trash" + - "bin" + - "dispose" + - "disposal" + - "invsee" + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eperform that command while in a &6&nWildPvP&r &ematch." + Move: + Chunk: + Participant: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ego outside of the chunk while in a &6&nWildPvP&r &ematch." + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eenter that chunk while there's a &6&nWildPvP&r &ematch." + Teleport: + Match: + Participant: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eteleport while in a &6&nWildPvP&r &ematch." + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eteleport to that location while there's a &6&nWildPvP&r &ematch." + Join: + Teleported: + Message: "&6&lWild PvP &8➥ &eYou have been &b&lTELEPORTED &eto the spawn point because there was a &6&nWildPvP&r &ematch at the chunk you were at." + Quit: + Won: + Message: "&6&lWild PvP &8➥ &eYou &a&lWON ðe &6&nWildPvP&r &ematch against the player &7%player&e." + Title: + Title: "&6&nWildPvP" + SubTitle: "&a&lWINNER!" + Broadcast: + Message: "&6&lWild PvP &8➥ &7%winner &ehas &c&lDEFEATED ðe player &7%loser &ein a &6&nWildPvP&r &ematch." + Left: + Message: "&6&lWild PvP &8➥ &7%player &ehas left the &6&nWildPvP&r &ematch." + Title: + Title: "&6&nWildPvP" + SubTitle: "&cMatch Ended!" + Teleported: + Message: "&6&lWild PvP &8➥ &7&oYou have been teleported to your last location." + Death: + Alone: + Message: "&6&lWild PvP &8➥ &eYour &6&nWildPvP&r &ematch has been &c&lREMOVED&e." + Won: + Message: "&6&lWild PvP &8➥ &eYou &a&lWON ðe &6&nWildPvP&r &ematch against the player &7%player&e." + Title: + Title: "&6&nWildPvP" + SubTitle: "&a&lWINNER!" + Lost: + Message: "&6&lWild PvP &8➥ &eYou &c&lLOST ðe &6&nWildPvP&r &ematch against the player &7%player&e." + Title: + Title: "&6&nWildPvP" + SubTitle: "&c&lLOSER!" + Broadcast: + Message: "&6&lWild PvP &8➥ &7%winner &ehas &c&lDEFEATED ðe player &7%loser &ein a &6&nWildPvP&r &ematch." + Claim: + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eclaim this chunk while a &6&nWildPvP&r &eis taking place in it." + Block: + Place: + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eplace a block while in a &6&nWildPvP&r &ematch." + Chunk: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eplace that block at that chunk while there's a &6&nWildPvP&r &ematch there." + Break: + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ebreak a block while in a &6&nWildPvP&r &ematch." + Chunk: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &ebreak that block at that chunk while there's a &6&nWildPvP&r &ematch there." + Interact: + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &einteract with that block while in a &6&nWildPvP&r &ematch." + Vehicle: + Match: + Message: "&6&lWild PvP &8➥ &cError&8: &eYou &c&lCANNOT &eenter that vehicle while in a &6&nWildPvP&r &ematch." +Menus: + Matches: + Title: "Cage Match Queue" + Items: + Exit: + Displayname: "&cExit WildPvP Matches" + Previous: + Available: + Displayname: "&aPrevious Page <" + Unavailable: + Displayname: "&cPrevious Page <" + Next: + Available: + Displayname: "&aNext Page >" + Unavailable: + Displayname: "&cNext Page >" + Information: + Displayname: "&bInformation" + Create: + Lore: + - "&7Active&8:" + - "&f%active" + - "" + - "&7Queued&8:" + - "&f%queued" + - "" + - "&eClick to &a&lCREATE &ea match!" + Leave: + Lore: + - "&7Active&8:" + - "&f%active" + - "" + - "&7Queued&8:" + - "&f%queued" + - "" + - "&eClick to &c&lLEAVE &eyour match!" + Glass: + Displayname: "&6Astro&fPvP" + Match: + Displayname: "&b%player" + Leave: + Lore: + - "&7Health&8:" + - "&f%health" + - "" + - "&7Faction&8:" + - "&f%faction" + - "" + - "&7Players Nearby&8:" + - "&f%playersnearby Players" + - "" + - "&eClick to &c&lLEAVE &ematch!" + Enter: + Lore: + - "&7Health&8:" + - "&f%health" + - "" + - "&7Faction&8:" + - "&f%faction" + - "" + - "&7Players Nearby&8:" + - "&f%playersnearby Players" + - "" + - "&eLeft-Click to &a&lENTER &ematch!" + - "&eRight-Click to &b&lVIEW &einventory!" + None: + Displayname: "&c&oThere are no active WildPvP matches!" + Lore: + - "&7&oPlease check back later!" + Invsee: + Title: "%player's Inventory" + Items: + Glass: + Displayname: "" + Return: + Displayname: "&cReturn to WildPvP Matches" \ No newline at end of file diff --git a/CagePvP/src/main/resources/plugin.yml b/CagePvP/src/main/resources/plugin.yml new file mode 100644 index 0000000..6d0f78f --- /dev/null +++ b/CagePvP/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedCagePvP +main: net.crankedpvp.wildpvp.CagePvPPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - Factions \ No newline at end of file diff --git a/Captcha/pom.xml b/Captcha/pom.xml new file mode 100644 index 0000000..97d903d --- /dev/null +++ b/Captcha/pom.xml @@ -0,0 +1,26 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Captcha + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + + \ No newline at end of file diff --git a/Captcha/src/main/java/net/crankedpvp/captcha/CaptchaAPI.java b/Captcha/src/main/java/net/crankedpvp/captcha/CaptchaAPI.java new file mode 100644 index 0000000..52188ff --- /dev/null +++ b/Captcha/src/main/java/net/crankedpvp/captcha/CaptchaAPI.java @@ -0,0 +1,27 @@ +package net.crankedpvp.captcha; + +import net.crankedpvp.captcha.inventory.CaptchaInventory; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +public class CaptchaAPI { + + public static void forceCaptchaForPlayer(Player player) { + CaptchaInventory captchaInventory = new CaptchaInventory(player); + captchaInventory.getCaptchaInventory().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0f, 2.0f); + //player.sendMessage(CC.translate("&cYou must complete the captcha to close this inventory")); + } + + public static void incrementInventoriesOpened(Player player) { + CaptchaPlugin.getInstance().getCaptchaManager().increment(player); + } + + public static int getAmountOfInventoriesOpened(Player player) { + return CaptchaPlugin.getInstance().getCaptchaManager().getAmountOfInventoriesOpened(player); + } + + public static void resetAmountOfInventoriesOpened(Player player) { + CaptchaPlugin.getInstance().getCaptchaManager().reset(player); + } +} diff --git a/Captcha/src/main/java/net/crankedpvp/captcha/CaptchaPlugin.java b/Captcha/src/main/java/net/crankedpvp/captcha/CaptchaPlugin.java new file mode 100644 index 0000000..af5ed31 --- /dev/null +++ b/Captcha/src/main/java/net/crankedpvp/captcha/CaptchaPlugin.java @@ -0,0 +1,36 @@ +package net.crankedpvp.captcha; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.captcha.commands.AdminCaptchaCommand; +import net.crankedpvp.captcha.struct.CaptchaManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class CaptchaPlugin extends JavaPlugin { + + @Getter + private static CaptchaPlugin instance; + + @Getter + private CommandManager commandManager; + + @Getter + private CaptchaManager captchaManager; + + @Override + public void onEnable() { + instance = this; + + this.commandManager = new CommandManager(this); + this.commandManager.register(new AdminCaptchaCommand(this)); + + this.captchaManager = new CaptchaManager(this); + + } + + @Override + public void onDisable() { + instance = null; + } + +} \ No newline at end of file diff --git a/Captcha/src/main/java/net/crankedpvp/captcha/commands/AdminCaptchaCommand.java b/Captcha/src/main/java/net/crankedpvp/captcha/commands/AdminCaptchaCommand.java new file mode 100644 index 0000000..930fad0 --- /dev/null +++ b/Captcha/src/main/java/net/crankedpvp/captcha/commands/AdminCaptchaCommand.java @@ -0,0 +1,36 @@ +package net.crankedpvp.captcha.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.captcha.CaptchaPlugin; +import net.crankedpvp.captcha.inventory.CaptchaInventory; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("acaptcha") +@Alias("admincaptcha") +public class AdminCaptchaCommand extends CommandBase { + + private final CaptchaPlugin plugin; + public AdminCaptchaCommand(CaptchaPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender) { + } + + @SubCommand("force") + @Permission("captcha.force") + @WrongUsage("&c/acaptcha force ") + public void forceCaptchaCommand(final CommandSender commandSender, Player player) { + CaptchaInventory captchaInventory = new CaptchaInventory(player); + captchaInventory.getCaptchaInventory().open(player); + commandSender.sendMessage(CC.translate("&aForcefully setup a captcha for player: " + player.getName())); + SoundUtils.playSoundIfPlayer(commandSender, Sound.SUCCESSFUL_HIT); + } + +} \ No newline at end of file diff --git a/Captcha/src/main/java/net/crankedpvp/captcha/inventory/CaptchaInventory.java b/Captcha/src/main/java/net/crankedpvp/captcha/inventory/CaptchaInventory.java new file mode 100644 index 0000000..315d243 --- /dev/null +++ b/Captcha/src/main/java/net/crankedpvp/captcha/inventory/CaptchaInventory.java @@ -0,0 +1,110 @@ +package net.crankedpvp.captcha.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.captcha.CaptchaAPI; +import net.crankedpvp.captcha.CaptchaPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Random; + +public class CaptchaInventory { + + @Getter + private final Gui captchaInventory; + + private final Material materialToClick; + private final Player player; + + private boolean clickSuccess = false; + private int errors = 0; + + public CaptchaInventory(Player player) { + player.closeInventory(); + if(CaptchaAPI.getAmountOfInventoriesOpened(player) >= 5) { + CaptchaAPI.resetAmountOfInventoriesOpened(player); + player.kickPlayer(CC.translate("&4&lLucifier &8- &cAuto Grinding")); + } + this.materialToClick = generateRandomMaterial(); + this.player = player; + + this.captchaInventory = new Gui(6, "Click the " + materialToClick.name()); + this.captchaInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.captchaInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(clickSuccess) return; + Bukkit.getScheduler().runTaskLater(CaptchaPlugin.getInstance(), () -> { + player.closeInventory(); + this.captchaInventory.open(player); + }, 1L); + }); + + setupRandomMaterials(); + setupFinalMaterial(); + + } + + private void setupFinalMaterial() { + if(!this.player.getOpenInventory().getTopInventory().getName().contains("Click the")) return; + this.captchaInventory.setItem(new Random().nextInt(this.captchaInventory.getInventory().getContents().length), new GuiItem(materialToClick, event -> { + if(!event.getCurrentItem().getType().equals(materialToClick)) { + wrongMaterial(); + return; + } + correctMaterial(); + })); + } + + private void setupRandomMaterials() { + if(!this.player.getOpenInventory().getTopInventory().getName().contains("Click the")) return; + for(int i = 0; i < this.captchaInventory.getInventory().getContents().length; i++) { + Material material = generateRandomMaterial(); + this.captchaInventory.addItem(new GuiItem(new ItemStack(material), event -> { + if(!event.getCurrentItem().getType().equals(materialToClick)) { + wrongMaterial(); + return; + } + correctMaterial(); + })); + } + } + + private void correctMaterial() { + clickSuccess = true; + this.player.closeInventory(); + this.player.playSound(this.player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0f, 2.0f); + CaptchaAPI.resetAmountOfInventoriesOpened(this.player); + } + + private void wrongMaterial() { + this.errors++; + if(this.errors >= 10) { + clickSuccess = true; + this.player.closeInventory(); + CaptchaInventory captchaInventory = new CaptchaInventory(this.player); + captchaInventory.getCaptchaInventory().open(this.player); + CaptchaAPI.incrementInventoriesOpened(player); + } + this.player.playSound(this.player.getLocation(), Sound.ANVIL_LAND, 1.0f, 1.0f); + } + + Material[] validMaterials = new Material[]{ + Material.DIAMOND_HELMET, Material.DIAMOND_LEGGINGS, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_BOOTS, + Material.DIRT, Material.STAINED_CLAY, Material.STONE, Material.WOOD, Material.GRAVEL, Material.SADDLE, + Material.SAND, Material.TORCH, Material.REDSTONE, Material.DIODE, Material.JACK_O_LANTERN, Material.PUMPKIN, + Material.PUMPKIN_PIE, Material.COBBLESTONE, Material.DIAMOND_ORE, Material.GOLD_BLOCK, Material.SLIME_BLOCK, + Material.CACTUS, Material.FLOWER_POT_ITEM, Material.YELLOW_FLOWER, Material.DAYLIGHT_DETECTOR, Material.VINE, + Material.RED_SANDSTONE_STAIRS, Material.LAPIS_ORE, Material.SANDSTONE, Material.SHEARS, Material.BOOK, + Material.BOOKSHELF, Material.BOW, Material.FISHING_ROD, Material.RAW_FISH, Material.QUARTZ_BLOCK + }; + + private Material generateRandomMaterial() { + int pick = new Random().nextInt(validMaterials.length); + return validMaterials[pick]; + } +} diff --git a/Captcha/src/main/java/net/crankedpvp/captcha/struct/CaptchaManager.java b/Captcha/src/main/java/net/crankedpvp/captcha/struct/CaptchaManager.java new file mode 100644 index 0000000..a279d14 --- /dev/null +++ b/Captcha/src/main/java/net/crankedpvp/captcha/struct/CaptchaManager.java @@ -0,0 +1,45 @@ +package net.crankedpvp.captcha.struct; + +import net.crankedpvp.captcha.CaptchaPlugin; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class CaptchaManager { + + private final CaptchaPlugin plugin; + public CaptchaManager(CaptchaPlugin plugin) { + this.plugin = plugin; + this.captchaInventoriesOpened = new HashMap<>(); + } + + private Map captchaInventoriesOpened; + + public int getAmountOfInventoriesOpened(Player player) { + UUID uuid = player.getUniqueId(); + + if(this.captchaInventoriesOpened.containsKey(uuid)) { + return this.captchaInventoriesOpened.get(uuid); + } + return 0; + } + + public void increment(Player player) { + + UUID uuid = player.getUniqueId(); + + if(this.captchaInventoriesOpened.containsKey(uuid)) { + int amount = this.captchaInventoriesOpened.get(uuid); + this.captchaInventoriesOpened.put(uuid, amount+1); + return; + } + this.captchaInventoriesOpened.put(uuid, 1); + } + + public void reset(Player player) { + UUID uuid = player.getUniqueId(); + this.captchaInventoriesOpened.remove(uuid); + } +} diff --git a/Captcha/src/main/resources/plugin.yml b/Captcha/src/main/resources/plugin.yml new file mode 100644 index 0000000..5c462e3 --- /dev/null +++ b/Captcha/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedCaptcha +main: net.crankedpvp.captcha.CaptchaPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/ChatTitles/pom.xml b/ChatTitles/pom.xml new file mode 100644 index 0000000..3d949fd --- /dev/null +++ b/ChatTitles/pom.xml @@ -0,0 +1,33 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + ChatTitles + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/ChatTitlesAPI.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/ChatTitlesAPI.java new file mode 100644 index 0000000..2cfa12b --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/ChatTitlesAPI.java @@ -0,0 +1,62 @@ +package net.crankedpvp.chattitles; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.chattitles.data.Title; +import net.crankedpvp.chattitles.data.TitlePlayer; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class ChatTitlesAPI { + + private static final ChatTitlesPlugin plugin = ChatTitlesPlugin.getInstance(); + + public static TitlePlayer getTitlePlayer(Player player) { + return plugin.getTitlePlayerManager().getTitlePlayer(player.getUniqueId()); + } + + public static boolean playerHasTitleEquipped(Player player) { + return getTitlePlayer(player).getCurrentTitle() != null; + } + + public static boolean playerHasTitleEquipped(Player player, String title) { + return getTitlePlayer(player).getCurrentTitle().getId().equals(title); + } + + public static void setPlayerTitleEquipped(Player player, Title title) { + getTitlePlayer(player).setCurrentTitle(title); + } + + public static String getEquippedTitle(Player player) { + if(!playerHasTitleEquipped(player)) return "&fNone"; + return getTitlePlayer(player).getCurrentTitle().getFancyName(); + } + + public static boolean playerHasTitleUnlocked(Player player, Title title) { + return getTitlePlayer(player).getTitlesIDs().contains(title.getId()); + } + + public static boolean playerHasTitleUnlocked(Player player, String title) { + return getTitlePlayer(player).getTitlesIDs().contains(title); + } + + public static void addTitleToPlayersClaimedTitles(Player player, Title title) { + getTitlePlayer(player).addTitle(title.getId()); + } + + public static void addTitleToPlayersClaimedTitles(Player player, String title) { + getTitlePlayer(player).addTitle(title); + } + + public static ItemStack buildVoucher(String titleID) { + //ItemBuilder itemBuilder = new ItemBuilder(Material.PAPER, "&b&lTITLE \"&f" + plugin.getTitleRegister().getTitle(titleID).getFancyName() + "&b&l\""); + ItemBuilder itemBuilder = new ItemBuilder(Material.PAPER, "&8<" + plugin.getTitleRegister().getTitle(titleID).getFancyName() + "&8> &fTag"); + itemBuilder.setLore("&7Right-Click this title voucher to permanently", "&7unlock the &f" + ChatColor.stripColor(plugin.getTitleRegister().getTitle(titleID).getFancyName()) + " &7title on cranked"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("titleID", titleID); + nbtItem.setString("crankedCustomItem", "title"); + return nbtItem.getItem(); + } +} diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/ChatTitlesPlugin.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/ChatTitlesPlugin.java new file mode 100644 index 0000000..a4e1823 --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/ChatTitlesPlugin.java @@ -0,0 +1,48 @@ +package net.crankedpvp.chattitles; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.chattitles.commands.TitleCommand; +import net.crankedpvp.chattitles.data.TitlePlayerManager; +import net.crankedpvp.chattitles.listeners.ApplyTitleVoucher; +import net.crankedpvp.chattitles.struct.TitleRegister; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class ChatTitlesPlugin extends JavaPlugin { + + @Getter + private static ChatTitlesPlugin instance; + + @Getter + private TitlePlayerManager titlePlayerManager; + @Getter + private TitleRegister titleRegister; + private CommandManager commandManager; + + @Override + public void onEnable() { + instance = this; + this.titleRegister = new TitleRegister(this); + this.titleRegister.loadTitles(); + this.titleRegister.loadHiddenTitles(); + this.titlePlayerManager = new TitlePlayerManager(this); + this.titlePlayerManager.loadAll(); + this.commandManager = new CommandManager(this); + this.commandManager.register(new TitleCommand(this)); + + this.registerListeners(); + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new ApplyTitleVoucher(this), this); + } + + @Override + public void onDisable() { + this.titleRegister.saveTitles(); + this.titleRegister.saveHiddenTitles(); + this.titlePlayerManager.saveAll(); + } +} diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/commands/TitleCommand.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/commands/TitleCommand.java new file mode 100644 index 0000000..e175911 --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/commands/TitleCommand.java @@ -0,0 +1,111 @@ +package net.crankedpvp.chattitles.commands; + +import de.tr7zw.nbtapi.NBTItem; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.chattitles.ChatTitlesAPI; +import net.crankedpvp.chattitles.ChatTitlesPlugin; +import net.crankedpvp.chattitles.data.Title; +import net.crankedpvp.chattitles.inventory.TitleInventory; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("title") +@Alias({"tag", "tags", "titles"}) +public class TitleCommand extends CommandBase { + + private final ChatTitlesPlugin plugin; + public TitleCommand(ChatTitlesPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender) { + Player player = ((Player) commandSender); + TitleInventory titleInventory = new TitleInventory(player); + titleInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("create") + @Permission("chattitles.*") + @WrongUsage("&eUsage: &f/title create ") + public void createCommand(CommandSender commandSender, String title, Boolean hidden, String[] fancyName) { + Player player = ((Player) commandSender); + if(plugin.getTitleRegister().isTitle(title)) { + player.sendMessage(CC.translate("&cThis is already a registered title")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(hidden == null || !hidden) { + plugin.getTitleRegister().register(new Title(title, String.join(" ", fancyName))); + player.getInventory().addItem(ChatTitlesAPI.buildVoucher(title)); + player.sendMessage(CC.translate("&cSuccessfully registered title named " + title)); + } else { + plugin.getTitleRegister().registerHidden(new Title(title, String.join(" ", fancyName))); + player.getInventory().addItem(ChatTitlesAPI.buildVoucher(title+"-hidden")); + player.sendMessage(CC.translate("&cSuccessfully registered a hidden title named " + title+"-hidden")); + } + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @SubCommand("edit") + @Permission("chattitles.*") + @WrongUsage("&eUsage: &f/title edit ") + public void editCommand(CommandSender commandSender, String title, String[] fancyName) { + Player player = ((Player) commandSender); + if(!plugin.getTitleRegister().isTitle(title)) { + player.sendMessage(CC.translate("&cThis is not a valid title")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + plugin.getTitleRegister().register(new Title(title, String.join(" ", fancyName))); + player.sendMessage(CC.translate("&cSuccessfully edited title named " + title)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @SubCommand("voucher") + @Permission("chattitles.*") + @WrongUsage("&eUsage: &f/title voucher ") + public void createCommand(CommandSender commandSender, Player player, String title) { + Player sender = ((Player) commandSender); + if(!plugin.getTitleRegister().isTitle(title)) { + sender.sendMessage(CC.translate("&cThis is not a registered title")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + sender.sendMessage(CC.translate("&cSuccessfully given a title voucher of " + title)); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + player.getInventory().addItem(ChatTitlesAPI.buildVoucher(title)); + } + + @SubCommand("search") + public void searchCommand(CommandSender commandSender, String toSearch) { + Player player = ((Player) commandSender); + TitleInventory titleInventory = new TitleInventory(player, false, toSearch); + titleInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("help") + public void helpCommand(CommandSender commandSender) { + Player sender = ((Player) commandSender); + if(sender.hasPermission("chattitles.*")) { + sender.sendMessage(CC.translate("&bChat Titles &7(Tags)")); + sender.sendMessage(CC.translate(" &f/tag create ")); + sender.sendMessage(CC.translate(" &f/tag edit ")); + sender.sendMessage(CC.translate(" &f/tag delete ")); + sender.sendMessage(CC.translate(" &f/tag voucher ")); + sender.sendMessage(""); + } + } + + +} diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/Title.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/Title.java new file mode 100644 index 0000000..e83d526 --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/Title.java @@ -0,0 +1,10 @@ +package net.crankedpvp.chattitles.data; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter @AllArgsConstructor +public class Title { + private String id; + private String fancyName; +} diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/TitlePlayer.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/TitlePlayer.java new file mode 100644 index 0000000..4f7b69a --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/TitlePlayer.java @@ -0,0 +1,40 @@ +package net.crankedpvp.chattitles.data; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.storageutils.utils.KeyToSave; + +import java.util.List; +import java.util.UUID; + +@Getter @AllArgsConstructor +public class TitlePlayer implements KeyToSave { + + private UUID playerUUID; + private final List titlesIDs; + private Title currentTitle; + + + public void setCurrentTitle(String title) { + } + + public void setCurrentTitle(Title title) { + this.currentTitle = title; + } + + public void addTitle(String title) { + this.titlesIDs.add(title); + } + + + @Override + public String getKey() { + return playerUUID.toString(); + } + + @Override + public void setKey(String s) { + this.playerUUID = UUID.fromString(s); + } + +} diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/TitlePlayerManager.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/TitlePlayerManager.java new file mode 100644 index 0000000..336de8d --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/data/TitlePlayerManager.java @@ -0,0 +1,22 @@ +package net.crankedpvp.chattitles.data; + +import net.crankedpvp.chattitles.ChatTitlesPlugin; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; + +import java.util.ArrayList; +import java.util.UUID; + +public class TitlePlayerManager extends SaveLoadManager { + public TitlePlayerManager(ChatTitlesPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "data/", TitlePlayer.class); + } + + public TitlePlayer getTitlePlayer(UUID uuid) { + if (!containsKey(uuid.toString())) { + TitlePlayer titlePlayer = new TitlePlayer(uuid, new ArrayList<>(), null); + addToCache(titlePlayer); + } + return getFromCache(uuid.toString()); + } +} diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/inventory/TitleInventory.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/inventory/TitleInventory.java new file mode 100644 index 0000000..327984c --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/inventory/TitleInventory.java @@ -0,0 +1,174 @@ +package net.crankedpvp.chattitles.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.chattitles.ChatTitlesAPI; +import net.crankedpvp.chattitles.ChatTitlesPlugin; +import net.crankedpvp.chattitles.data.Title; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + + +public class TitleInventory { + + private final ChatTitlesPlugin plugin = ChatTitlesPlugin.getInstance(); + + private boolean onCooldown = false; + + private final PaginatedGui titleInventory; + + public PaginatedGui getUI() { + return this.titleInventory; + } + + public TitleInventory(Player player) { + this(player, false, "NOSEARCH"); + } + + public TitleInventory(Player player, boolean hidden) { + this(player, hidden, "NOSEARCH"); + } + + public TitleInventory(Player player, boolean hidden, String searched) { + this.titleInventory = new PaginatedGui(6, 36, "Cranked Titles"); + this.titleInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.titleInventory.getFiller().fillBottom(new GuiItem(createFillerItem())); + this.titleInventory.getFiller().fillTop(new GuiItem(createFillerItem())); + ItemStack prevPage = new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.").colorize().build(); + ItemStack nextPage = new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.").colorize().build(); + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, "&bCranked Titles Info").colorize().build(); + this.titleInventory.setItem(1, 5, new GuiItem(info)); + this.titleInventory.setItem(6, 1, new GuiItem(prevPage, event -> { + this.titleInventory.previous(); + event.setCancelled(true); + })); + this.titleInventory.setItem(6, 9, new GuiItem(nextPage, event -> { + this.titleInventory.next(); + event.setCancelled(true); + })); + + addRegisteredTitles(player, hidden, searched); + addRemoveTitleItem(player); + addChangeTitlesTypeButton(player, hidden); + } + + private void addChangeTitlesTypeButton(Player player, boolean hidden) { + ItemBuilder itemBuilder = hidden ? new ItemBuilder(Material.SUGAR) : new ItemBuilder(Material.REDSTONE); + String name = hidden ? "&b&lConvert to main titles" : "&c&lConvert to hidden titles"; + List lore = hidden ? Arrays.asList("&7Click this button to convert the GUI", + "&7to show the main titles that are", + "&7available to everyone on the server") : Arrays.asList("&7Click this button to convert this GUI", + "&7to show the hidden titles that", + "&7you currently have access to"); + itemBuilder.setName(name).setLore(lore); + + this.titleInventory.updateItem(1, 9, new GuiItem(itemBuilder.colorize().build(), event -> { + player.closeInventory(); + TitleInventory titleInventory = new TitleInventory(player, !hidden); + titleInventory.getUI().open(player); + })); + } + + private void addRegisteredTitles(Player player, boolean hidden, String lookingFor) { + List titleIds = hidden ? plugin.getTitleRegister().getTitles().keySet().stream().filter(key -> key.contains("hidden")).collect(Collectors.toList()) : plugin.getTitleRegister().getTitles().keySet().stream().filter(key -> !key.contains("hidden")).collect(Collectors.toList()); + List searchedFor = titleIds.stream().filter(string -> string.contains(lookingFor)).collect(Collectors.toList()); + titleIds.removeIf(string -> string.contains(lookingFor)); + + if(titleIds.size() <= 0) { + ItemBuilder itemBuilder = new ItemBuilder(Material.BARRIER, "&cNo titles", "&7There are no titles to display", "&7in this sub category"); + this.titleInventory.setItem(3, 5, new GuiItem(itemBuilder.colorize().build())); + return; + } + + searchedFor.addAll(titleIds); + searchedFor.forEach(id -> { + + if(!plugin.getTitleRegister().isTitle(id)) { + System.out.println("[ChatTitles] " + id + " is not a valid title"); + return; + } + + Title title = plugin.getTitleRegister().getTitle(id); + if(!ChatTitlesAPI.playerHasTitleUnlocked(player, id) && hidden) return; + + short data = ChatTitlesAPI.playerHasTitleUnlocked(player, id) ? (short)5 : (short)14; + ItemBuilder itemBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, data, "&b&lTITLE \"&f" + title.getFancyName() + "&b&l\""); + itemBuilder.setLore("&7Click this item to equip this", "&7title on cranked. You can", "&7equip another title whenever", "&7you want to."); + + if(player.hasPermission("titles.*")) { + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&7Right click to receive title voucher"); + itemBuilder.addLoreLine("&7Shift-Right click to delete title"); + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&7Tag ID: " + id); + } + if(ChatTitlesAPI.playerHasTitleUnlocked(player, id)) itemBuilder.setGlowing(); + + this.titleInventory.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + + if(player.hasPermission("titles.*") && event.getClick() == ClickType.RIGHT) { + + player.getInventory().addItem(ChatTitlesAPI.buildVoucher(id)); + player.sendMessage(CC.translate("&aSuccessfully received voucher for title: " + title.getFancyName())); + return; + + } + + if(player.hasPermission("titles.*") && event.getClick() == ClickType.SHIFT_RIGHT) { + plugin.getTitleRegister().getTitles().remove(id); + player.sendMessage(CC.translate("&aSuccessfully deleted title named: " + id)); + player.closeInventory(); + TitleInventory titleInventory = new TitleInventory(player, !hidden); + titleInventory.getUI().open(player); + return; + } + + if(ChatTitlesAPI.playerHasTitleUnlocked(player, id) && !onCooldown) { + + this.onCooldown = true; + plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, () -> this.onCooldown = false, 15L); + + ChatTitlesAPI.setPlayerTitleEquipped(player, title); + addRemoveTitleItem(player); + player.sendMessage(CC.translate("&aEquipped title: " + title.getFancyName())); + + } + })); + }); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("")); + item.setItemMeta(meta); + return item; + } + + private void addRemoveTitleItem(Player player) { + ItemStack itemStack = new ItemBuilder(Material.BARRIER, "&cRemove current title", + "&7Click this item to remove your", + "&7currently equipped title.", "").addLoreLine("&fEquipped: " + ChatTitlesAPI.getEquippedTitle(player)).colorize().build(); + + this.titleInventory.updateItem(6, 5, new GuiItem(itemStack, event -> { + if(ChatTitlesAPI.playerHasTitleEquipped(player) && !onCooldown) { + ChatTitlesAPI.setPlayerTitleEquipped(player, null); + addRemoveTitleItem(player); + this.onCooldown = true; + plugin.getServer().getScheduler().runTaskLater(plugin, () -> this.onCooldown = false, 15L); + } + })); + } +} diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/listeners/ApplyTitleVoucher.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/listeners/ApplyTitleVoucher.java new file mode 100644 index 0000000..39eb723 --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/listeners/ApplyTitleVoucher.java @@ -0,0 +1,63 @@ +package net.crankedpvp.chattitles.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.chattitles.ChatTitlesAPI; +import net.crankedpvp.chattitles.ChatTitlesPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class ApplyTitleVoucher implements Listener { + + private final ChatTitlesPlugin plugin; + public ApplyTitleVoucher(ChatTitlesPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void applyTitleVoucher(PlayerInteractEvent event) { + if(event.getAction() == null) return; + if(event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if(event.getItem() == null || event.getItem().getType() == Material.AIR) return; + + Player player = event.getPlayer(); + ItemStack itemStack = event.getItem(); + NBTItem nbtItem = new NBTItem(itemStack); + + if(!nbtItem.hasNBTData()) return; + if(!nbtItem.hasKey("crankedCustomItem")) return; + if(!nbtItem.hasKey("titleID")) return; + + String titleId = nbtItem.getString("titleID"); + if(!plugin.getTitleRegister().getTitles().containsKey(titleId)) { + player.sendMessage(CC.translate("&cThis title is no longer valid")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(plugin.getTitlePlayerManager().getTitlePlayer(player.getUniqueId()).getTitlesIDs().contains(titleId)) { + player.sendMessage(CC.translate("&cYou have already redeemed this title")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + event.setCancelled(true); + int amount = itemStack.getAmount(); + if (amount <= 1) { + event.getPlayer().setItemInHand(null); + } else { + itemStack.setAmount(amount - 1); + event.getPlayer().setItemInHand(itemStack); + } + ChatTitlesAPI.addTitleToPlayersClaimedTitles(event.getPlayer(), titleId); + player.sendMessage(CC.translate("&aSuccessfully claimed the " + plugin.getTitleRegister().getTitle(titleId).getFancyName() + " title")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + + } +} diff --git a/ChatTitles/src/main/java/net/crankedpvp/chattitles/struct/TitleRegister.java b/ChatTitles/src/main/java/net/crankedpvp/chattitles/struct/TitleRegister.java new file mode 100644 index 0000000..a4084cf --- /dev/null +++ b/ChatTitles/src/main/java/net/crankedpvp/chattitles/struct/TitleRegister.java @@ -0,0 +1,131 @@ +package net.crankedpvp.chattitles.struct; + +import com.google.common.collect.Maps; +import lombok.Getter; +import lombok.SneakyThrows; +import net.crankedpvp.chattitles.ChatTitlesPlugin; +import net.crankedpvp.chattitles.data.Title; +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +public class TitleRegister { + + private final ChatTitlesPlugin plugin; + + @Getter + private final Map titles; + + public TitleRegister(ChatTitlesPlugin plugin) { + this.plugin = plugin; + this.titles = Maps.newConcurrentMap(); + } + + @SneakyThrows + public void loadTitles() { + File file = new File(this.plugin.getDataFolder(), "titles.yml"); + checkExists(file); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + if(!yamlConfiguration.contains("Titles")) + yamlConfiguration.createSection("Titles"); + + yamlConfiguration.getConfigurationSection("Titles").getKeys(false).forEach(title -> register(new Title(title, yamlConfiguration.getString("Titles."+title)))); + } + + @SneakyThrows + public void loadHiddenTitles() { + File file = new File(this.plugin.getDataFolder(), "hidden-titles.yml"); + checkExists(file); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + if(!yamlConfiguration.contains("Titles")) + yamlConfiguration.createSection("Titles"); + + yamlConfiguration.getConfigurationSection("Titles").getKeys(false).forEach(title -> registerHidden(new Title(title, yamlConfiguration.getString("Titles."+title)))); + } + + @SneakyThrows + public void saveTitles() { + File file = new File(this.plugin.getDataFolder(), "titles.yml"); + checkExists(file); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + this.titles.forEach((id, title) -> { + if(!id.contains("hidden")) + yamlConfiguration.set("Titles."+id, title.getFancyName()); + }); + yamlConfiguration.save(file); + } + + @SneakyThrows + public void saveHiddenTitles() { + File file = new File(this.plugin.getDataFolder(), "hidden-titles.yml"); + checkExists(file); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + this.titles.forEach((id, title) -> { + if(id.contains("hidden")) + yamlConfiguration.set(("Titles."+id).replace("-hidden", ""), title.getFancyName()); + }); + yamlConfiguration.save(file); + } + + private void checkExists(File file) { + if(file.exists()) return; + boolean ignored = file.getParentFile().mkdirs(); + try { + boolean ignore = file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void register(Title title) { + try { + this.titles.put(title.getId(), title); + this.plugin.getLogger().info("Successfully registered title: " + title.getId()); + } catch (Exception var3) { + System.err.println("&8(&c!&8) Failed to register title, " + title.getId()); + } + } + + public void registerHidden(Title title) { + try { + this.titles.put(title.getId() + "-hidden", title); + this.plugin.getLogger().info("Successfully registered hidden title: " + title.getId()); + } catch (Exception var3) { + System.err.println("&8(&c!&8) Failed to register hidden title, " + title.getId()); + } + } + + public boolean isTitle(String name) { + return (getTitle(name) != null); + } + + public Title getTitle(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + return this.titles.get(name); + } + +} diff --git a/ChatTitles/src/main/resources/plugin.yml b/ChatTitles/src/main/resources/plugin.yml new file mode 100644 index 0000000..a321273 --- /dev/null +++ b/ChatTitles/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedChatTitles +main: net.crankedpvp.chattitles.ChatTitlesPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - StorageUtil \ No newline at end of file diff --git a/Christmas/pom.xml b/Christmas/pom.xml new file mode 100644 index 0000000..7c8f5ff --- /dev/null +++ b/Christmas/pom.xml @@ -0,0 +1,33 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Christmas + + + 8 + 8 + + + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + Utils + net.crankedpvp + + + + \ No newline at end of file diff --git a/Christmas/src/main/java/net/crankedpvp/christmas/ChristmasPlugin.java b/Christmas/src/main/java/net/crankedpvp/christmas/ChristmasPlugin.java new file mode 100644 index 0000000..fb0db46 --- /dev/null +++ b/Christmas/src/main/java/net/crankedpvp/christmas/ChristmasPlugin.java @@ -0,0 +1,40 @@ +package net.crankedpvp.christmas; + + +import net.crankedpvp.christmas.commands.ChristmasCommand; +import net.crankedpvp.christmas.managers.ChristmasManager; +import org.bukkit.command.CommandExecutor; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; + +public class ChristmasPlugin extends JavaPlugin { + private static ChristmasPlugin instance; + private ChristmasManager christmasManager; + + public void onEnable() { + instance = this; + File file = new File(this.getDataFolder() + File.separator + "config.yml"); + if (!file.exists()) { + this.saveDefaultConfig(); + } + this.christmasManager = new ChristmasManager(); + this.christmasManager.loadAll(); + this.getCommand("christmas").setExecutor((CommandExecutor)new ChristmasCommand()); + } + + public void onDisable() { + this.getChristmasManager().saveShop(); + this.christmasManager.saveAll(); + instance = null; + } + + + public static ChristmasPlugin getInstance() { + return instance; + } + + public ChristmasManager getChristmasManager() { + return this.christmasManager; + } +} diff --git a/Christmas/src/main/java/net/crankedpvp/christmas/commands/ChristmasCommand.java b/Christmas/src/main/java/net/crankedpvp/christmas/commands/ChristmasCommand.java new file mode 100644 index 0000000..6a89228 --- /dev/null +++ b/Christmas/src/main/java/net/crankedpvp/christmas/commands/ChristmasCommand.java @@ -0,0 +1,40 @@ +package net.crankedpvp.christmas.commands; + + +import net.crankedpvp.christmas.ChristmasPlugin; +import net.crankedpvp.christmas.inventories.ChristmasInventory; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class ChristmasCommand implements CommandExecutor { + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { + if (!(commandSender instanceof Player)) { + return true; + } + Player player = (Player)commandSender; + if (!player.isOp() || args.length == 0) { + ChristmasInventory christmasInventory = new ChristmasInventory(); + christmasInventory.getGui().open(player); + player.sendMessage(CC.translate((String)"&a&l(!)&a Opening the Christmas Present Menu.")); + return true; + } + if (args[0].equalsIgnoreCase("setitem") && args.length == 1) { + ChristmasPlugin.getInstance().getChristmasManager().setCurrentItem(player.getItemInHand().clone()); + ChristmasPlugin.getInstance().getChristmasManager().clearAlreadyBought(); + player.sendMessage(CC.translate("&a&l(!)&a You have restocked the santa reward!")); + Bukkit.broadcastMessage((String)""); + Bukkit.broadcastMessage((String) StringUtils.getCenteredMessage((String)(CC.DarkGreenB + CC.Underline + "Christmas Shop"))); + Bukkit.broadcastMessage((String)""); + Bukkit.broadcastMessage((String)StringUtils.getCenteredMessage((String)(CC.Gray + "The " + CC.DarkGreen + "Christmas Shop " + CC.Gray + "has been " + CC.DarkGreen + "restocked"))); + Bukkit.broadcastMessage((String)(StringUtils.getCenteredMessage((String)(CC.Gray + "with " + player.getItemInHand().getItemMeta().getDisplayName())) + CC.Gray + " type /santa to claim it.")); + Bukkit.broadcastMessage((String)""); + return true; + } + return false; + } +} diff --git a/Christmas/src/main/java/net/crankedpvp/christmas/inventories/ChristmasInventory.java b/Christmas/src/main/java/net/crankedpvp/christmas/inventories/ChristmasInventory.java new file mode 100644 index 0000000..90044a2 --- /dev/null +++ b/Christmas/src/main/java/net/crankedpvp/christmas/inventories/ChristmasInventory.java @@ -0,0 +1,50 @@ +package net.crankedpvp.christmas.inventories; + + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.christmas.ChristmasPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +public class ChristmasInventory { + @Getter + private final Gui gui; + public ChristmasInventory() { + this.gui = new Gui(1, "Santa Daily Reward"); + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + this.gui.setItem(3, getCurrentItem()); + this.gui.setItem(5, getInformationBook()); + } + + private GuiItem getCurrentItem() { + ItemStack shopItem = ChristmasPlugin.getInstance().getChristmasManager().getCurrentItem().clone(); + ItemStack item = new ItemBuilder(shopItem).build(); + return new GuiItem(item.clone(), event -> { + Player player = (Player) event.getWhoClicked(); + if (!ChristmasPlugin.getInstance().getChristmasManager().canBuy(player)) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You may only get this item once per restock."); + return; + } + if (player.getInventory().firstEmpty() < 0) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You must have an empty slot to get this item."); + return; + } + ChristmasPlugin.getInstance().getChristmasManager().setAlreadyBought(player); + player.getInventory().addItem(ChristmasPlugin.getInstance().getChristmasManager().getCurrentItem().clone()); + Bukkit.broadcastMessage(CC.translate("&2&l<&a&lSanta&2&l> &f" + player.getName() + " &ahas just claimed the " + getCurrentItem().getItemStack().getItemMeta().getDisplayName() + "&r &afrom the daily &f/santa&a present!")); + }){ + }; + } + + private GuiItem getInformationBook() { + ItemStack item = new ItemBuilder(Material.COOKIE).setName(CC.DarkGreenB + "Christmas Daily Present").addLore(CC.translate("&7This is a place where you you can"), CC.translate("&7claim your daily reward from"), CC.translate("&7Santa Claus. He will give you each item"), CC.translate("&7only once and if you miss it, that"), CC.translate("&7is your own fault, Santa Claus"), CC.translate("&7has got a busy schedule...")).build(); + return new GuiItem(item){}; + } +} diff --git a/Christmas/src/main/java/net/crankedpvp/christmas/managers/ChristmasManager.java b/Christmas/src/main/java/net/crankedpvp/christmas/managers/ChristmasManager.java new file mode 100644 index 0000000..790c9bd --- /dev/null +++ b/Christmas/src/main/java/net/crankedpvp/christmas/managers/ChristmasManager.java @@ -0,0 +1,75 @@ +package net.crankedpvp.christmas.managers; + +import net.crankedpvp.christmas.ChristmasPlugin; +import net.crankedpvp.christmas.utils.ConfigUtils; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class ChristmasManager extends SaveLoadManager { + public ChristmasManager() { + + super(ChristmasPlugin.getInstance(), StorageUtils.getInstance().getGson(), "data/", ChristmasPlayer.class); + } + + public ChristmasPlayer getChristmasPlayer(Player player) { + if (getFromCache(player.getUniqueId().toString()) == null) { + addToCache(new ChristmasPlayer(player.getUniqueId(), player.getAddress().getAddress().toString())); + } + return getFromCache(player.getUniqueId().toString()); + } + + private ItemStack currentItem = ConfigUtils.getItem(ChristmasPlugin.getInstance().getConfig().getString("current-item")); + private Location shopLocation = ConfigUtils.stringToLocation(ChristmasPlugin.getInstance().getConfig().getString("shop-location")); + + + public void saveShop() { + ChristmasPlugin.getInstance().getConfig().set("current-item", (Object)ConfigUtils.toBase64(new ItemStack[]{this.currentItem}, 9)); + ChristmasPlugin.getInstance().getConfig().set("shop-location", (Object)ConfigUtils.locationToString(this.shopLocation)); + ChristmasPlugin.getInstance().saveConfig(); + } + + + public boolean canBuy(Player player) { + ChristmasPlayer christmasPlayer = getChristmasPlayer(player); + return !christmasPlayer.isHasPurchased() && !isUniqueIPAndHasntPurchased(player); + } + + public boolean isUniqueIPAndHasntPurchased(Player player) { + ChristmasPlayer christmasPlayer = getChristmasPlayer(player); + for (ChristmasPlayer other : getCacheValues()) { + if (other.getIp().equals(christmasPlayer.getIp()) && other.isHasPurchased()) { + return true; + } + } + return false; + } + + public void setAlreadyBought(Player player) { + getChristmasPlayer(player).setHasPurchased(true); + } + + public void clearAlreadyBought() { + for (ChristmasPlayer christmasPlayer : getCacheValues()) { + christmasPlayer.setHasPurchased(false); + } + } + + public ItemStack getCurrentItem() { + return this.currentItem; + } + + public void setCurrentItem(ItemStack currentItem) { + this.currentItem = currentItem; + } + + public Location getShopLocation() { + return this.shopLocation; + } + + public void setShopLocation(Location shopLocation) { + this.shopLocation = shopLocation; + } +} diff --git a/Christmas/src/main/java/net/crankedpvp/christmas/managers/ChristmasPlayer.java b/Christmas/src/main/java/net/crankedpvp/christmas/managers/ChristmasPlayer.java new file mode 100644 index 0000000..ac9a4e5 --- /dev/null +++ b/Christmas/src/main/java/net/crankedpvp/christmas/managers/ChristmasPlayer.java @@ -0,0 +1,37 @@ +package net.crankedpvp.christmas.managers; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.storageutils.utils.KeyToSave; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.UUID; + +@Getter +@Setter +public class ChristmasPlayer implements KeyToSave { + private String ip; + private UUID uuid; + private boolean hasPurchased; + + public ChristmasPlayer(UUID uuid, String ip) { + this.uuid = uuid; + this.ip = ip; + this.hasPurchased = false; + } + + public Player getPlayer() { + return Bukkit.getPlayer(uuid); + } + + @Override + public String getKey() { + return uuid.toString(); + } + + @Override + public void setKey(String s) { + this.uuid = UUID.fromString(s); + } +} diff --git a/Christmas/src/main/java/net/crankedpvp/christmas/utils/ConfigUtils.java b/Christmas/src/main/java/net/crankedpvp/christmas/utils/ConfigUtils.java new file mode 100644 index 0000000..37b8f37 --- /dev/null +++ b/Christmas/src/main/java/net/crankedpvp/christmas/utils/ConfigUtils.java @@ -0,0 +1,75 @@ +package net.crankedpvp.christmas.utils; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +public class ConfigUtils { + public static String toBase64(Inventory inventory, int size) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream((OutputStream)outputStream); + dataOutput.writeInt(size); + for (int i = 0; i < inventory.getSize(); ++i) { + dataOutput.writeObject((Object)inventory.getItem(i)); + } + dataOutput.close(); + return Base64Coder.encodeLines((byte[])outputStream.toByteArray()); + } + catch (Exception e) { + throw new IllegalStateException("Cannot into itemstacks!", e); + } + } + + public static String toBase64(ItemStack[] is, int size) { + Inventory inventory = Bukkit.createInventory((InventoryHolder)null, (int)size); + inventory.setContents(is); + return ConfigUtils.toBase64(inventory, size); + } + + public static Inventory fromBase64(String data) { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines((String)data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream((InputStream)inputStream); + Inventory inventory = Bukkit.getServer().createInventory((InventoryHolder)null, dataInput.readInt()); + for (int i = 0; i < inventory.getSize(); ++i) { + inventory.setItem(i, (ItemStack)dataInput.readObject()); + } + dataInput.close(); + return inventory; + } + catch (Exception ex) { + return null; + } + } + + public static ItemStack getItem(String line) { + return ConfigUtils.fromBase64(line.split(":")[0]).getContents()[0]; + } + + public static String locationToString(Location location) { + return location.getWorld().getName() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ() + ":" + location.getYaw(); + } + + public static Location stringToLocation(String s) { + String[] array = s.split(":"); + World world = Bukkit.getWorld(array[0]); + double x = Double.parseDouble(array[1]); + double y = Double.parseDouble(array[2]); + double z = Double.parseDouble(array[3]); + float yaw = Float.parseFloat(array[4]); + return new Location(world, x, y, z, yaw, 0); + } +} + diff --git a/Christmas/src/main/resources/config.yml b/Christmas/src/main/resources/config.yml new file mode 100644 index 0000000..678c03f --- /dev/null +++ b/Christmas/src/main/resources/config.yml @@ -0,0 +1,36 @@ +current-item: "rO0ABXcEAAAACXNyABpvcmcuYnVra2l0LnV0aWwuaW8uV3JhcHBlcvJQR+zxEm8FAgABTAADbWFw + dAAPTGphdmEvdXRpbC9NYXA7eHBzcgA1Y29tLmdvb2dsZS5jb21tb24uY29sbGVjdC5JbW11dGFi + bGVNYXAkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAlsABGtleXN0ABNbTGphdmEvbGFuZy9PYmpl + Y3Q7WwAGdmFsdWVzcQB+AAR4cHVyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4cAAA + AAN0AAI9PXQABHR5cGV0AARtZXRhdXEAfgAGAAAAA3QAHm9yZy5idWtraXQuaW52ZW50b3J5Lkl0 + ZW1TdGFja3QABEJPT0tzcQB+AABzcQB+AAN1cQB+AAYAAAAGcQB+AAh0AAltZXRhLXR5cGV0AAxk + aXNwbGF5LW5hbWV0AARsb3JldAAIZW5jaGFudHN0AAhpbnRlcm5hbHVxAH4ABgAAAAZ0AAhJdGVt + TWV0YXQAClVOU1BFQ0lGSUN0AFvCp3LCpzTCp2s7wqdmwqdswqdu4pyYwqc0wqdrO8KnciDCpzTC + p2xNYXN0ZXJ5IEJvb2sgR2VuZXJhdG9yIMKnNMKnazvCp2bCp2zCp27inJjCpzTCp2s7wqdyc3IA + NmNvbS5nb29nbGUuY29tbW9uLmNvbGxlY3QuSW1tdXRhYmxlTGlzdCRTZXJpYWxpemVkRm9ybQAA + AAAAAAAAAgABWwAIZWxlbWVudHNxAH4ABHhwdXEAfgAGAAAAF3QAA8KnN3QAH8KnN8KnblJpZ2h0 + LUNsaWNrwqc3IHRvIHJlY2VpdmV0AB/CpzdhIHNwZWNpYWwgwqc0TWFzdGVyeSDCpzdCb29rdAAA + dAAjwqdmwqdsUmFuZG9tIExvb3QgKMKnNzEgaXRlbcKnZsKnbCl0ACkgwqdmwqdsKiDCp2YxeCDC + pzTCp2zCp25DaGFpbiBMaWZlc3RlYWwgVnQAJyDCp2bCp2wqIMKnZjF4IMKnNMKnbMKnblJvdCBh + bmQgRGVjYXkgWHQAJiDCp2bCp2wqIMKnZjF4IMKnNMKnbMKnbkxhdmEgU3RyaWRlciBJdAAjIMKn + ZsKnbCogwqdmMXggwqc0wqdswqduQmxhY2tvdXQgSVZ0ACQgwqdmwqdsKiDCp2YxeCDCpzTCp2zC + p25OZXV0cmFsaXplIFZ0ACUgwqdmwqdsKiDCp2YxeCDCpzTCp2zCp25QZXJtYWZyb3N0IFZJdAAk + IMKnZsKnbCogwqdmMXggwqc0wqdswqduV2ViIFdhbGtlciBJdAAnIMKnZsKnbCogwqdmMXggwqc0 + wqdswqduUG9sdGVyZ2Vpc3QgSUlJdAAiIMKnZsKnbCogwqdmMXggwqc0wqdswqduSG9ycmlmeSBJ + VnQAKiDCp2bCp2wqIMKnZjF4IMKnNMKnbMKnbkRlbW9uaWMgR2F0ZXdheSBWSXQAKCDCp2bCp2wq + IMKnZjF4IMKnNMKnbMKnbkRpc2NvbWJvYnVsYXRlIEl0ACYgwqdmwqdsKiDCp2YxeCDCpzTCp2zC + p25EZWF0aCBQYWN0IElJSXQAJSDCp2bCp2wqIMKnZjF4IMKnNMKnbMKnbk1vcnRhbCBDb2lsIFZ0 + ACsgwqdmwqdsKiDCp2YxeCDCpzTCp2zCp25FeHBsb3NpdmVzIEV4cGVydCBJdAAsIMKnZsKnbCog + wqdmMXggwqc0wqdswqduTWFyayBvZiB0aGUgQmVhc3QgVkl0ACYgwqdmwqdsKiDCp2YxeCDCpzTC + p2zCp25Tb3VsIFNpcGhvbiBJVnQAIyDCp2bCp2wqIMKnZjF4IMKnNMKnbMKnbkF1dG8gU2VsbCBJ + dAAmIMKnZsKnbCogwqdmMXggwqc0wqdswqduRmVpZ24gRGVhdGggSVZzcgA3Y29tLmdvb2dsZS5j + b21tb24uY29sbGVjdC5JbW11dGFibGVCaU1hcCRTZXJpYWxpemVkRm9ybQAAAAAAAAAAAgAAeHEA + fgADdXEAfgAGAAAAAXQACkRVUkFCSUxJVFl1cQB+AAYAAAABc3IAEWphdmEubGFuZy5JbnRlZ2Vy + EuKgpPeBhzgCAAFJAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cAAAAAp0 + AFRINHNJQUFBQUFBQUFBT05pWU9CaTRFek96MHVzY0Vrc1NlUmc0TW10TEM1SkxhcDB6a2d0TG1I + ZzlrMEU4NXp5ODdNWkdBQitnSW0xTFFBQUFBPT1wcHBwcHBwcA==" +current-price: 1 +shop-location: "world:0:100:0:0" +already-bought: + - "player1" + - "player2" \ No newline at end of file diff --git a/Christmas/src/main/resources/plugin.yml b/Christmas/src/main/resources/plugin.yml new file mode 100644 index 0000000..13df6e2 --- /dev/null +++ b/Christmas/src/main/resources/plugin.yml @@ -0,0 +1,12 @@ +name: CrankedChristmas +main: net.crankedpvp.christmas.ChristmasPlugin +version: 1.0 +depend: + - CrankedUtils + - StorageUtil +commands: + christmas: + aliases: + - santa + - advent + - adventcalendar \ No newline at end of file diff --git a/Collect/pom.xml b/Collect/pom.xml new file mode 100644 index 0000000..39a4666 --- /dev/null +++ b/Collect/pom.xml @@ -0,0 +1,33 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Collect + + + 8 + 8 + + + + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + Utils + net.crankedpvp + + + \ No newline at end of file diff --git a/Collect/src/main/java/net/crankedpvp/collect/CollectPlugin.java b/Collect/src/main/java/net/crankedpvp/collect/CollectPlugin.java new file mode 100644 index 0000000..8bbc2c4 --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/CollectPlugin.java @@ -0,0 +1,58 @@ +package net.crankedpvp.collect; + +import lombok.Getter; +import net.crankedpvp.collect.commands.CollectCommand; +import net.crankedpvp.collect.commands.CollectSaveCommand; +import net.crankedpvp.collect.listeners.PlayerListener; +import net.crankedpvp.collect.struct.CollectCategory; +import net.crankedpvp.collect.struct.CollectManager; +import net.crankedpvp.collect.struct.PlayerCollect; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.UUID; + +@Getter +public class CollectPlugin extends JavaPlugin { + @Getter + private static CollectPlugin instance; + private CollectManager collectManager; + + public void onEnable() { + instance = this; + + this.collectManager = new CollectManager(this); + this.collectManager.loadAll(); + + this.registerCommands(); + Bukkit.getPluginManager().registerEvents(new PlayerListener(), this); + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, ()-> { + collectManager.saveAll(); + final OfflinePlayer[] onlinePlayers = Bukkit.getOfflinePlayers(); + for (OfflinePlayer player : onlinePlayers) { + UUID uuid = player.getUniqueId(); + PlayerCollect playerCollect = getCollectManager().getFromCache(uuid.toString()); + if (playerCollect == null) continue; + for (CollectCategory category : playerCollect.getCategories()) { + if (category.isExpired()) { + getCollectManager().removeCategoryFromCache(uuid.toString(), category); + System.out.println("[Collect] Removed category for " + uuid + " because it expired!"); + } + } + } + }, 60L, 20*60L); + + } + + public void onDisable() { + this.collectManager.saveAll(); + instance = null; + } + + private void registerCommands() { + getCommand("collect").setExecutor(new CollectCommand()); + getCommand("collectsave").setExecutor(new CollectSaveCommand(this)); + getCommand("collectload").setExecutor(new CollectSaveCommand(this)); + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/commands/CollectCommand.java b/Collect/src/main/java/net/crankedpvp/collect/commands/CollectCommand.java new file mode 100644 index 0000000..64bc5a4 --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/commands/CollectCommand.java @@ -0,0 +1,22 @@ +package net.crankedpvp.collect.commands; + +import net.crankedpvp.collect.inventories.CollectInventory; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CollectCommand implements CommandExecutor { + @Override + public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { + if (!(sender instanceof Player)) + return true; + + + Player player = (Player) sender; + + + new CollectInventory(player).getCollectUI().open(player); + return false; + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/commands/CollectLoadCommand.java b/Collect/src/main/java/net/crankedpvp/collect/commands/CollectLoadCommand.java new file mode 100644 index 0000000..30e5794 --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/commands/CollectLoadCommand.java @@ -0,0 +1,31 @@ +package net.crankedpvp.collect.commands; + +import net.crankedpvp.collect.CollectPlugin; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CollectLoadCommand implements CommandExecutor { + + private final CollectPlugin collectPlugin; + + public CollectLoadCommand(CollectPlugin collectPlugin) { + this.collectPlugin = collectPlugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { + if (!(sender instanceof Player)) + return true; + + + Player player = (Player) sender; + + if (!player.isOp()) return true; + + + this.collectPlugin.getCollectManager().loadAll(); + return true; + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/commands/CollectSaveCommand.java b/Collect/src/main/java/net/crankedpvp/collect/commands/CollectSaveCommand.java new file mode 100644 index 0000000..5ce5a53 --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/commands/CollectSaveCommand.java @@ -0,0 +1,31 @@ +package net.crankedpvp.collect.commands; + +import net.crankedpvp.collect.CollectPlugin; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CollectSaveCommand implements CommandExecutor { + + private final CollectPlugin collectPlugin; + + public CollectSaveCommand(CollectPlugin collectPlugin) { + this.collectPlugin = collectPlugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { + if (!(sender instanceof Player)) + return true; + + + Player player = (Player) sender; + + if (!player.isOp()) return true; + + + this.collectPlugin.getCollectManager().saveAll(); + return true; + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/inventories/CategoryInventory.java b/Collect/src/main/java/net/crankedpvp/collect/inventories/CategoryInventory.java new file mode 100644 index 0000000..c63dfa3 --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/inventories/CategoryInventory.java @@ -0,0 +1,112 @@ +package net.crankedpvp.collect.inventories; + + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.collect.CollectPlugin; +import net.crankedpvp.collect.struct.CollectCategory; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.List; + +public class CategoryInventory { + private final PaginatedGui categoryInventory; + + public PaginatedGui getCollectUI() { + return this.categoryInventory; + } + + public CategoryInventory(Player player, CollectCategory category) { + this.categoryInventory = new PaginatedGui(6, 45, CC.translate(category.getName())); + categoryInventory.setDefaultClickAction(event -> { + event.setCancelled(true); + }); + categoryInventory.getFiller().fillBottom(new GuiItem(createFillerItem())); + + + + + categoryInventory.setItem(6, 1, new GuiItem(createPreviousItem(), event -> { + int pageNum = categoryInventory.getCurrentPageNum(); + PaginatedGui inventory= new CategoryInventory(player, category).getCollectUI(); + inventory.open(player, pageNum); + inventory.previous(); + event.setCancelled(true); + })); + + categoryInventory.setItem(6, 9, new GuiItem(createNextItem(), event -> { + int pageNum = categoryInventory.getCurrentPageNum(); + PaginatedGui inventory= new CategoryInventory(player, category).getCollectUI(); + inventory.open(player, pageNum); + inventory.next(); + + event.setCancelled(true); + })); + + + + categoryInventory.setItem(6, 5, new GuiItem(new ItemBuilder(Material.BED, CC.translate("&c&lMain Menu"), CC.translate("&7Click to go to the main menu")).build(), event -> { + CollectInventory collectInventory = new CollectInventory(player); + collectInventory.getCollectUI().open(player); + }) + ); + + + for (ItemStack item : category.getItems()) { + categoryInventory.addItem(new GuiItem(item, event -> { + + + if (player.getInventory().firstEmpty() == -1) { + player.sendMessage(CC.translate("&c&l(!)&c Please clear some inventory space and try again!")); + event.setCancelled(true); + return; + } + + + player.getInventory().addItem(item); + categoryInventory.getInventory().remove(event.getCurrentItem()); + category.setItems(category.removeItem(item)); + + + if (category.onlyContainsAir()) { + categoryInventory.close(player); + CollectPlugin.getInstance().getCollectManager().removeCategoryFromCache(player.getUniqueId().toString(), category); + player.playSound(player.getLocation(), Sound.ANVIL_BREAK, 1f, 1f); + new CollectInventory(player).getCollectUI().open(player); + } + event.setCancelled(true); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0F, 0.9F); + + })); + } + } + + public ItemStack createPreviousItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&c<- Previous Page"), "&7Right-Click&7 to go to the previous page.").colorize().build(); + } + public ItemStack createNextItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&aNext Page ->"), "&7Right-Click&7 to go to the next page.").colorize().build(); + + } + public ItemStack createFillerItem() { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData())).setName("&7").colorize().build(); + } + + public static boolean isInvEmpty(Inventory inv) { + for (ItemStack item : inv.getContents()) { + if (item != null) { + return false; + } + } + return true; + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/inventories/CollectInventory.java b/Collect/src/main/java/net/crankedpvp/collect/inventories/CollectInventory.java new file mode 100644 index 0000000..156ee7b --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/inventories/CollectInventory.java @@ -0,0 +1,94 @@ +package net.crankedpvp.collect.inventories; + + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.collect.CollectPlugin; +import net.crankedpvp.collect.struct.CollectCategory; +import net.crankedpvp.collect.struct.PlayerCollect; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class CollectInventory { + private final PaginatedGui collectUI; + + public PaginatedGui getCollectUI() { + return this.collectUI; + } + + public CollectInventory(Player player) { + this.collectUI = new PaginatedGui(6, 45, "Collect Menu"); + collectUI.setDefaultClickAction(event -> { + event.setCancelled(true); + }); + + + collectUI.setItem(6, 1, new GuiItem(createPreviousItem(), event -> { + collectUI.previous(); + event.setCancelled(true); + })); + + collectUI.setItem(6, 9, new GuiItem(createNextItem(), event -> { + collectUI.next(); + event.setCancelled(true); + })); + + collectUI.getFiller().fillBottom(new GuiItem(createFillerItem())); + + PlayerCollect collect = CollectPlugin.getInstance().getCollectManager().getOrCreate(player.getUniqueId().toString()); + List categories = collect.getCategories(); + for (CollectCategory cat : categories) { + collectUI.addItem(new GuiItem(getCategoryItem(player, cat), event -> { + if (event.getClick() == ClickType.SHIFT_RIGHT) { + CollectPlugin.getInstance().getCollectManager().removeCategoryFromCache(player.getUniqueId().toString(), cat); + player.playSound(player.getLocation(), Sound.ANVIL_BREAK, 1f, 1f); + CollectInventory collectInventory = new CollectInventory(player); + collectInventory.getCollectUI().open(player); + player.sendMessage(CC.translate("&cRemoved the collect inventory.")); + } else { + new CategoryInventory(player, cat).getCollectUI().open(player); + } + })); + } + } + + + public ItemStack createPreviousItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&c<- Previous Page"), "&7Right-Click&7 to go to the previous page.").colorize().build(); + } + public ItemStack createNextItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&aNext Page ->"), "&7Right-Click&7 to go to the next page.").colorize().build(); + + } + public ItemStack createFillerItem() { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData())).setName("&7").colorize().build(); + } + + private ItemStack getCategoryItem(Player player, CollectCategory cat) { + return new ItemBuilder(cat.getType().getMaterial(), CC.translate(cat.getName()), CC.translate(""), CC.translate("&aLeft-Click&7 to open inventory"), CC.translate("&cSHIFT Right-Click&7 to remove inventory"), "", CC.translate("&6Expires in&7: &f") + + ((cat.getTimeCollected() + 259200000) - System.currentTimeMillis() <= 0 ? "Now" : fancy((cat.getTimeCollected() + 259200000) - System.currentTimeMillis()))).build(); + } + + + + + public String fancy(long seconds) { + seconds = seconds/1000; + int days = (int) TimeUnit.SECONDS.toDays(seconds); + long hours = TimeUnit.SECONDS.toHours(seconds) - (days * 24L); + long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60); + long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60); + + return days + "d " + hours + "h " + minute + "m " + second + "s "; + + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/listeners/PlayerListener.java b/Collect/src/main/java/net/crankedpvp/collect/listeners/PlayerListener.java new file mode 100644 index 0000000..4d9fa6d --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/listeners/PlayerListener.java @@ -0,0 +1,23 @@ +package net.crankedpvp.collect.listeners; + +import net.crankedpvp.collect.CollectPlugin; +import net.crankedpvp.collect.struct.PlayerCollect; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerLoginEvent; + +public class PlayerListener implements Listener { + @EventHandler + public void onJoin(PlayerLoginEvent e) { + PlayerCollect playerCollect = CollectPlugin.getInstance().getCollectManager().getOrCreate(e.getPlayer().getUniqueId().toString()); + if (playerCollect.getCategories().isEmpty()) return; + Bukkit.getScheduler().runTaskLaterAsynchronously(CollectPlugin.getInstance(), () -> { + e.getPlayer().sendMessage(CC.translate("&b&lCollect &8" + Arrow.arrow() + "&7 You have items in your &b\"/collect\"&7, make sure to claim the before they expire!")); + e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.NOTE_PLING, 10, 10); + }, 100L); + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/struct/CollectCategory.java b/Collect/src/main/java/net/crankedpvp/collect/struct/CollectCategory.java new file mode 100644 index 0000000..92a1649 --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/struct/CollectCategory.java @@ -0,0 +1,79 @@ +package net.crankedpvp.collect.struct; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Comparator; + +public class CollectCategory implements Serializable { + private CollectType type; + + public void setItems(ItemStack[] items) { + this.items = items; + } + + public ItemStack[] getItems() { + return items; + } + + private ItemStack[] items; + + private String name; + + private final long timeCollected; + + + + public CollectCategory(CollectType type, ItemStack[] items, String name, long timeCollected) { + this.type = type; + this.items = items; + this.name = name; + this.timeCollected = timeCollected; + } + + public CollectType getType() { + return type; + } + + public String getName() { + return name; + } + + public long getTimeCollected() { + return timeCollected; + } + + + public boolean isExpired() { + return System.currentTimeMillis() > timeCollected + 259200000; + } + + public ItemStack[] removeItem(ItemStack item) { + for (int i = 0; i < items.length; i++) { + if (items[i] == item) { + items[i]=new ItemStack(Material.AIR); + return items; + } + } + return items; + } + + public void sort() { + Arrays.sort(items, Comparator.comparing(a -> a.getItemMeta().getDisplayName())); + + } + + + public boolean onlyContainsAir() { + for (ItemStack item : items) { + if (item.getType() != Material.AIR) { + return false; + + } + } + return true; + } + +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/struct/CollectManager.java b/Collect/src/main/java/net/crankedpvp/collect/struct/CollectManager.java new file mode 100644 index 0000000..cf2e4c1 --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/struct/CollectManager.java @@ -0,0 +1,27 @@ +package net.crankedpvp.collect.struct; + + +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.UUID; + +public class CollectManager extends SaveLoadManager { + + + public CollectManager(JavaPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "data/", PlayerCollect.class); + } + + public void removeCategoryFromCache(String key, CollectCategory category) { + getFromCache(key).getCategories().remove(category); + } + + public PlayerCollect getOrCreate(String key) { + if (getFromCache(key) == null) { + addToCache(new PlayerCollect(UUID.fromString(key))); + } + return getFromCache(key); + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/struct/CollectType.java b/Collect/src/main/java/net/crankedpvp/collect/struct/CollectType.java new file mode 100644 index 0000000..1430848 --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/struct/CollectType.java @@ -0,0 +1,21 @@ +package net.crankedpvp.collect.struct; + +import org.bukkit.Material; + +public enum CollectType { + REVIVE(Material.ENDER_CHEST), + ITEMFLIP(Material.ENCHANTMENT_TABLE), + DUEL(Material.DIAMOND_SWORD), + NETHER_PVP(Material.BLAZE_POWDER), +; + + Material material; + + CollectType(Material material) { + this.material = material; + } + + public Material getMaterial() { + return this.material; + } +} diff --git a/Collect/src/main/java/net/crankedpvp/collect/struct/PlayerCollect.java b/Collect/src/main/java/net/crankedpvp/collect/struct/PlayerCollect.java new file mode 100644 index 0000000..8da38ef --- /dev/null +++ b/Collect/src/main/java/net/crankedpvp/collect/struct/PlayerCollect.java @@ -0,0 +1,38 @@ +package net.crankedpvp.collect.struct; + +import lombok.Getter; +import net.crankedpvp.storageutils.utils.KeyToSave; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Getter +public class PlayerCollect implements KeyToSave { + + private UUID uuid; + private final List categories; + + public PlayerCollect(UUID uuid) { + this.uuid = uuid; + categories = new ArrayList<>(); + } + + public void add(CollectCategory category) { + this.categories.add(category); + } + + public void add(List categories) { + this.categories.addAll(categories); + } + + @Override + public String getKey() { + return uuid.toString(); + } + + @Override + public void setKey(String key) { + this.uuid = UUID.fromString(key); + } +} \ No newline at end of file diff --git a/Collect/src/main/resources/plugin.yml b/Collect/src/main/resources/plugin.yml new file mode 100644 index 0000000..c80dd6f --- /dev/null +++ b/Collect/src/main/resources/plugin.yml @@ -0,0 +1,10 @@ +name: CrankedCollect +main: net.crankedpvp.collect.CollectPlugin +version: 1.0 +depend: + - StorageUtil + - CrankedUtils +commands: + collect: + collectsave: + collectload: diff --git a/Collectors/pom.xml b/Collectors/pom.xml new file mode 100644 index 0000000..5224e3a --- /dev/null +++ b/Collectors/pom.xml @@ -0,0 +1,48 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Collectors + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + com.massivecraft + Factions + + + net.crankedpvp + Spawners + 1.0 + + + net.astropvp + FactionsKore + 0.1 + system + ${project.basedir}/../.lib/FactionsKore-1.3.431.jar + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + \ No newline at end of file diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/CollectorsPlugin.java b/Collectors/src/main/java/net/crankedpvp/collectors/CollectorsPlugin.java new file mode 100644 index 0000000..59e3f59 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/CollectorsPlugin.java @@ -0,0 +1,79 @@ +package net.crankedpvp.collectors; + +import lombok.Getter; +import net.crankedpvp.collectors.collector.Collector; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.collectors.commands.CollectorGiveCommand; +import net.crankedpvp.collectors.commands.ReloadCommand; +import net.crankedpvp.collectors.commands.RemoveCollectorCommand; +import net.crankedpvp.collectors.listeners.collectorlisteners.BlockBreakListener; +import net.crankedpvp.collectors.listeners.collectorlisteners.BlockPlaceListener; +import net.crankedpvp.collectors.listeners.collectorlisteners.PlayerInteractListener; +import net.crankedpvp.collectors.listeners.collectorlisteners.StackedMobDeathListener; +import net.crankedpvp.collectors.listeners.spawnerlisteners.SpawnerEvents; +import net.crankedpvp.collectors.tasks.CollectorWorthUpdateTask; +import net.crankedpvp.collectors.utils.SpawnerUtil; +import net.crankedpvp.collectors.utils.config.ConfigManager; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.util.Objects; + +public class CollectorsPlugin extends JavaPlugin { + + @Getter + private ConfigManager configManager; + @Getter + private SpawnerUtil spawnerUtil; + private final File collectorsFile = new File(this.getDataFolder(), "collectors.json"); + public static CollectorsPlugin INSTANCE; + + @Override + public void onEnable() { + INSTANCE = this; + this.configManager = new ConfigManager(this); + this.configManager.setupFiles(); + this.spawnerUtil = new SpawnerUtil(); + CollectorManager.DELEGATE.loadFromFile(collectorsFile); + + this.registerCommands(); + this.registerListeners(); + new CollectorWorthUpdateTask().runTaskTimer(this, 0L, 100L); + + Bukkit.getScheduler().runTaskLater(this, () -> { + for (Collector collector : CollectorManager.DELEGATE.collectors.values()) { + collector.clearSpawners(); + collector.scanSpawners(Objects.requireNonNull(collector.getLocation())); + } + }, 140L); + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, () -> CollectorManager.DELEGATE.saveToFile(collectorsFile),60L, 60*20); + + } + + @Override + public void onDisable() { + CollectorManager.DELEGATE.saveToFile(collectorsFile); + } + + + + private void registerListeners() { + PluginManager pm = getServer().getPluginManager(); + pm.registerEvents(new BlockPlaceListener(), this); + pm.registerEvents(new BlockBreakListener(this), this); + pm.registerEvents(new PlayerInteractListener(this), this); + //pm.registerEvents(new SpawnerBlockPlaceListener(), this); + //pm.registerEvents(new SpawnerBlockBreakListener(), this); + //pm.registerEvents(new SpawnerExplodeListener(), this); + pm.registerEvents(new StackedMobDeathListener(this), this); + pm.registerEvents(new SpawnerEvents(), this); + } + + private void registerCommands() { + getCommand("c").setExecutor(new CollectorGiveCommand()); + getCommand("removecollector").setExecutor(new RemoveCollectorCommand()); + getCommand("collectorreload").setExecutor(new ReloadCommand()); + } +} \ No newline at end of file diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/collector/Collector.java b/Collectors/src/main/java/net/crankedpvp/collectors/collector/Collector.java new file mode 100644 index 0000000..460d353 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/collector/Collector.java @@ -0,0 +1,296 @@ +package net.crankedpvp.collectors.collector; + +import com.gmail.filoghost.holographicdisplays.api.Hologram; +import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import com.gmail.filoghost.holographicdisplays.api.line.TextLine; +import com.google.common.collect.ImmutableList; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.collectors.CollectorsPlugin; +import net.crankedpvp.collectors.language.Language; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.LocationUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.spawners.SpawnerData; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.block.BlockState; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.LinkedBlockingQueue; + + +public final class Collector { + + @Getter + @Setter + private long lastUpdated; + @Getter + private double worth; + @Getter + private long tnt; + @Getter + private final Map spawnersInChunk; + private final Reference reference; + private final double x, y, z; + private final Queue sellLogs; + @Getter + private Hologram hologram; + + + public Collector(World world, JSONObject data) { + this.reference = new WeakReference<>(world); + + Object potentialLocationArray = data.get("Location"); + if (!(potentialLocationArray instanceof JSONArray)) { + throw new IllegalArgumentException(); + } + JSONArray uncastedLocationArray = (JSONArray) potentialLocationArray; + this.x = Double.parseDouble(String.valueOf(uncastedLocationArray.get(0))); + this.y = Double.parseDouble(String.valueOf(uncastedLocationArray.get(1))); + this.z = Double.parseDouble(String.valueOf(uncastedLocationArray.get(2))); + this.sellLogs = new LinkedBlockingQueue<>(10); + + + this.lastUpdated = (long) data.get("lastUpdated"); + + this.spawnersInChunk = new HashMap<>(); + Object potentialSpawnerArray = data.get("spawners"); + if (!(potentialSpawnerArray instanceof JSONArray)) { + throw new IllegalArgumentException(); + } + JSONArray uncastedSpawnerArray = (JSONArray) potentialSpawnerArray; + for (Object o : uncastedSpawnerArray) { + JSONObject jsonObject = ((JSONObject) o); + EntityType type = EntityType.valueOf(String.valueOf(jsonObject.get("type"))); + int amount = Integer.parseInt(String.valueOf(jsonObject.get("amount"))); + this.spawnersInChunk.put(type, amount); + } + + this.worth = (double) data.get("worth"); + + this.tnt = (long) data.get("tnt"); + Location holoLoc = this.getLocation().clone(); + holoLoc.add(0.5, 2, 0.5); + + this.hologram = HologramsAPI.createHologram(CollectorsPlugin.INSTANCE, holoLoc); + hologram.appendTextLine(CC.translate("&a&lChunk Collector")); + hologram.appendTextLine(CC.translate("&7TnT: &c" + NumberUtils.formatMoney(tnt))); + hologram.appendTextLine(CC.translate("&7Worth: &2$&a" + NumberUtils.formatMoney(getWorth()))); + } + + public Collector(Location location) { + this.reference = new WeakReference<>(location.getWorld()); + this.x = location.getX(); + this.y = location.getY(); + this.z = location.getZ(); + + this.sellLogs = new LinkedBlockingQueue<>(10); + this.lastUpdated = System.currentTimeMillis(); + + this.spawnersInChunk = new HashMap<>(); + this.scanSpawners(location); + + this.worth = 0.0; + this.tnt = 0L; + Location holoLoc = this.getLocation().clone(); + holoLoc.add(0.5, 2, 0.5); + + this.hologram = HologramsAPI.createHologram(CollectorsPlugin.INSTANCE, holoLoc); + hologram.appendTextLine(CC.translate("&b&lChunk Collector")); + hologram.appendTextLine(CC.translate("&7TnT: &c" + NumberUtils.formatMoney(tnt))); + hologram.appendTextLine(CC.translate("&7Worth: &2$&a" + NumberUtils.formatMoney(getWorth()))); + } + + public void scanSpawners(Location location) { + + for (BlockState blockState : location.getChunk().getTileEntities()) { + if (blockState instanceof CreatureSpawner) { + if (SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(blockState.getLocation()) != null) { + SpawnerData data = SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(blockState.getLocation()); + if (data.getEntityType() == EntityType.BLAZE) continue; + this.spawnersInChunk.put(data.getEntityType(), data.getSpawnerAmount()); + } + } + } + } + + public void sellWorth(Player player) { + if (this.worth <= 0) return; + player.playSound(player.getLocation(), Sound.ITEM_PICKUP, 5, 5); + EconomyUtils.depositBalance(player, worth); + Language.COLLECTOR_SELL.send(player, str -> str.replace("%price%", NumberUtils.formatNum((long) this.worth))); + this.worth = 0.0; + } + + public void claimTNT(Player player) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + Faction faction = fplayer.getFaction(); + int amount = (int) this.tnt; + + if (faction.isWilderness()) { + Language.NEED_FACTION.send(player); + return; + } + + if (faction.getMaxTNT() <= faction.getTNTBank()) return; + + if (faction.getMaxTNT() < faction.getTNTBank() + amount) { + amount = faction.getMaxTNT() - faction.getTNTBank(); + faction.setTNTBank(faction.getTNTBank() + amount); + this.tnt = this.tnt - (amount / 2); + } else { + faction.setTNTBank(faction.getTNTBank() + amount); + this.tnt = 0; + } + + int finalAmount = amount; + Language.COLLECTOR_TNT.send(player, str -> str.replace("%tnt%", NumberUtils.formatNum(finalAmount))); + + addTNTSellLog(player, amount); + player.playSound(player.getLocation(), Sound.ITEM_PICKUP, 5, 5); + } + + private double calculateWorth() { + long current = System.currentTimeMillis(); + long secondsPassed = (current - this.getLastUpdated()) / 1000; + double total = 0; + + for (Map.Entry entry : getSpawnersInChunk().entrySet()) { + EntityType type = entry.getKey(); + int amountSpawners = entry.getValue(); + total += CollectorsPlugin.INSTANCE.getSpawnerUtil().getMoneyPerSecond(type) * secondsPassed * amountSpawners; + + } + return total; + } + + private int calculateTnt() { + if (!this.getSpawnersInChunk().containsKey(EntityType.CREEPER)) return 0; + long current = System.currentTimeMillis(); + long secondsPassed = (current - this.getLastUpdated()) / 1000; + double total = CollectorsPlugin.INSTANCE.getSpawnerUtil().getTntPerSecond() * secondsPassed * this.getSpawnersInChunk().get(EntityType.CREEPER); + return (int) total; + } + + public void update() { + this.updateWorth(); + this.updateTnt(); + this.updateHologram(); + this.setLastUpdated(System.currentTimeMillis()); + } + + public void deleteHologram() { + this.hologram.delete(); + } + + private void updateWorth() { + this.addWorth(this.calculateWorth()); + } + + private void updateTnt() { + this.addTnt(this.calculateTnt()); + } + + private void addWorth(double amount) { + this.worth += amount; + } + + private void addTnt(double amount) { + this.tnt += amount; + } + + public void addTNTSellLog(Player seller, int amount) { + boolean canOffer = this.sellLogs.offer(new CollectorSellLog(seller.getName(), CollectorSellLog.SellLogType.TNT, amount)); + + if (!canOffer) { + this.sellLogs.poll(); + this.sellLogs.offer(new CollectorSellLog(seller.getName(), CollectorSellLog.SellLogType.TNT, amount)); + } + } + + public void addMobDropSellLog(Player seller, double worth) { + boolean canOffer = this.sellLogs.offer(new CollectorSellLog(seller.getName(), CollectorSellLog.SellLogType.MOB_DROPS, worth)); + + if (!canOffer) { + this.sellLogs.poll(); + this.sellLogs.offer(new CollectorSellLog(seller.getName(), CollectorSellLog.SellLogType.MOB_DROPS, worth)); + } + } + + public void updateHologram() { + updateHologramLine(1, CC.translate("&7TnT: &c" + NumberUtils.formatMoney(tnt))); + updateHologramLine(2, CC.translate("&7Worth: &2$&a" + NumberUtils.formatMoney(getWorth()))); + } + + public List getSellLogs() { + return ImmutableList.copyOf(sellLogs); + } + + public void clearSpawners() { + this.spawnersInChunk.clear(); + } + + public Location getLocation() { + World world = this.reference.get(); + if (world == null) { + return null; + } + return new Location(world, x, y, z); + } + + void invalidate() { + this.reference.clear(); + } + + @SuppressWarnings("unchecked") + public JSONObject toJsonObject() { + JSONObject jsonObject = new JSONObject(); + + JSONArray location = new JSONArray(); + location.add(x); + location.add(y); + location.add(z); + + jsonObject.put("Location", location); + JSONArray spawners = new JSONArray(); + for (Map.Entry spawnerData : this.spawnersInChunk.entrySet()) { + JSONObject spawner = new JSONObject(); + spawner.put("type", spawnerData.getKey().name()); + spawner.put("amount", spawnerData.getValue()); + spawners.add(spawner); + } + + + jsonObject.put("spawners", spawners); + jsonObject.put("lastUpdated", this.lastUpdated); + jsonObject.put("worth", this.worth); + jsonObject.put("tnt", this.tnt); + return jsonObject; + } + + private void updateHologramLine(int line, String newText) { + if (this.hologram.size() == 0 || this.hologram == null) return; + if(this.hologram.isDeleted()) return; + final TextLine textLine = (TextLine)this.hologram.getLine(line); + if(textLine != null) { + textLine.setText(newText); + } + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorManager.java b/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorManager.java new file mode 100644 index 0000000..73b16d2 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorManager.java @@ -0,0 +1,142 @@ +package net.crankedpvp.collectors.collector; + +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +public class CollectorManager { + + public static final CollectorManager DELEGATE = new CollectorManager(); + + public final Map collectors = new HashMap<>(); + private final JSONParser jsonParser = new JSONParser(); + + private CollectorManager() {} + + public void loadFromFile(File file) { + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try (FileWriter fileWriter = new FileWriter(file)) { + fileWriter.write("{}"); + fileWriter.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + try (FileReader fileReader = new FileReader(file)) { + load((JSONObject)jsonParser.parse(fileReader)); + } catch (IOException | ParseException | ClassCastException e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("rawtypes") + private void load(JSONObject object) { + for (Object obj : object.entrySet()) { + Map.Entry entry = (Map.Entry) obj; + String key = String.valueOf(entry.getKey()); + String[] components = key.split(";"); + if (components.length != 3) { + continue; + } + World world = Bukkit.getWorld(components[0]); + if (world == null) { + continue; + } + Object value = entry.getValue(); + if (!(value instanceof JSONObject)) { + continue; + } + collectors.put(key,new Collector(world, (JSONObject)value)); + } + } + + public void saveToFile(File file) { + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try (FileWriter fileWriter = new FileWriter(file)) { + fileWriter.write(save().toJSONString()); + fileWriter.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("rawtypes") + private JSONObject save() { + JSONObject jsonObject = new JSONObject(); + + collectors.forEach((key,collector) -> jsonObject.put(key,collector.toJsonObject())); + + return jsonObject; + } + + public boolean isCollectorContained(Chunk chunk) { + return collectors.get(chunkToString(chunk)) != null; + } + + public boolean isCollectorContained(Location location) { + return collectors.get(chunkToString(location.getChunk())) != null; + } + + private String chunkToString(Chunk chunk) { + char c = ';'; + return chunk.getWorld().getName() + + c + + chunk.getX() + + c + + chunk.getZ(); + } + + public Collector getCollector(Chunk chunk) { + return collectors.get(chunkToString(chunk)); + } + + public Collector getCollector(Location location) { + return collectors.get(chunkToString(location.getChunk())); + } + + public void removeCollector(Chunk chunk) { + collectors.remove(chunkToString(chunk)).invalidate(); + } + + public void removeCollector(Location location) { + collectors.remove(chunkToString(location.getChunk())).invalidate(); + } + + public Collector newCollector(Location location) { + Collector collector = new Collector(location); + collectors.put(chunkToString(location.getChunk()),collector); + return collector; + } + + public void forEach(Consumer action) { + for (Collector collector : collectors.values()) { + action.accept(collector); + } + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorSellLog.java b/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorSellLog.java new file mode 100644 index 0000000..6e00e1a --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorSellLog.java @@ -0,0 +1,31 @@ +package net.crankedpvp.collectors.collector; + +import lombok.Getter; + +@Getter +public class CollectorSellLog { + + private final long sellDate; + private final String sellerName; + private final SellLogType sellLogType; + private final double worth; + + public CollectorSellLog(String sellerName, SellLogType sellLogType) { + this.sellerName = sellerName; + this.sellLogType = sellLogType; + this.sellDate = System.currentTimeMillis(); + this.worth = 0; + } + + public CollectorSellLog(String sellerName, SellLogType sellLogType, double worth) { + this.sellerName = sellerName; + this.sellLogType = sellLogType; + this.sellDate = System.currentTimeMillis(); + this.worth = worth; + } + + public enum SellLogType { + TNT, + MOB_DROPS + } +} \ No newline at end of file diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorUtils.java b/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorUtils.java new file mode 100644 index 0000000..d5859ca --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/collector/CollectorUtils.java @@ -0,0 +1,29 @@ +package net.crankedpvp.collectors.collector; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class CollectorUtils { + private CollectorUtils() { } + + public static ItemStack createCollector(int amount) { + ItemStack itemStack = new ItemBuilder(Material.BEACON, amount, (short) 0, + ("&b&lChunk Collector"), + + ("&7This collector will automatically generate"), + ("&7money in the same chunk as it's placed in"),("&7based on the spawners placed in this chunk.")) + .colorize().build(); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("crankedCustomItem", "chunkCollector"); + return nbtItem.getItem(); + } + public static boolean isCollector(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return false; + if (itemStack.getType() != Material.BEACON) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if (!nbtItem.hasKey("crankedCustomItem")) return false; + return nbtItem.getString("crankedCustomItem").equalsIgnoreCase("chunkCollector"); + } +} \ No newline at end of file diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/commands/CollectorGiveCommand.java b/Collectors/src/main/java/net/crankedpvp/collectors/commands/CollectorGiveCommand.java new file mode 100644 index 0000000..dc84e6c --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/commands/CollectorGiveCommand.java @@ -0,0 +1,24 @@ +package net.crankedpvp.collectors.commands; + +import net.crankedpvp.collectors.collector.CollectorUtils; +import net.crankedpvp.collectors.language.Language; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CollectorGiveCommand implements CommandExecutor { + + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (args.length != 2) { + Language.COLLECTOR_HELP.send(sender); + return true; + } + Player player = Bukkit.getPlayer(args[0]); + int amount = Integer.parseInt(args[1]); + + player.getInventory().addItem(CollectorUtils.createCollector(amount)); + return true; + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/commands/ReloadCommand.java b/Collectors/src/main/java/net/crankedpvp/collectors/commands/ReloadCommand.java new file mode 100644 index 0000000..8acec87 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/commands/ReloadCommand.java @@ -0,0 +1,21 @@ +package net.crankedpvp.collectors.commands; + +import net.crankedpvp.collectors.CollectorsPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +public class ReloadCommand implements CommandExecutor { + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if(!sender.hasPermission("*")) return true; + CollectorsPlugin.INSTANCE.getConfigManager().reloadFiles(); + CollectorsPlugin.INSTANCE.getSpawnerUtil().reloadTntIncomeValue(); + CollectorsPlugin.INSTANCE.getSpawnerUtil().reloadMobIncomeMap(); + sender.sendMessage(CC.Green + "Reloaded config"); + + return true; + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/commands/RemoveCollectorCommand.java b/Collectors/src/main/java/net/crankedpvp/collectors/commands/RemoveCollectorCommand.java new file mode 100644 index 0000000..8cee503 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/commands/RemoveCollectorCommand.java @@ -0,0 +1,50 @@ +package net.crankedpvp.collectors.commands; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.PermissibleAction; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class RemoveCollectorCommand implements CommandExecutor { + @Override + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { + if (!(commandSender instanceof Player)) return true; + + Location location = ((Player)commandSender).getLocation(); + + Player player = ((Player) commandSender).getPlayer(); + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (!CollectorManager.DELEGATE.isCollectorContained(location.getChunk())) { + player.sendMessage(CC.translate("&c&l(!)&c No collector could be found in this chunk.")); + return true; + } + + Location collectorLocation = CollectorManager.DELEGATE.getCollector(location).getLocation(); + + if (FactionUtils.getFaction(player) != FactionUtils.getFactionAt(collectorLocation) && !player.isOp()) { + player.sendMessage(CC.translate("&c&l(!)&c You need to be in the " + FactionUtils.getFactionAt(collectorLocation).getTag()) + " to remove this collector!"); + return true; + } + boolean hasAccess = fPlayer.getFaction().hasAccess(fPlayer, PermissibleAction.COLLECTOR_ACCESS); + + if (!hasAccess && !fPlayer.isAdminBypassing()) { + player.sendMessage(CC.translate("&c&l(!)&c You need a higher role in your faction to remove this collector.")); + return true; + } + + assert collectorLocation != null; + CollectorManager.DELEGATE.removeCollector(location); + collectorLocation.getBlock().setType(Material.AIR,true); + commandSender.sendMessage(CC.translate("&a&l(!)&a You have removed the chunk collector in this chunk. You may now place a new one!")); + return true; + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/inventories/CollectorsUI.java b/Collectors/src/main/java/net/crankedpvp/collectors/inventories/CollectorsUI.java new file mode 100644 index 0000000..c0bb1d0 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/inventories/CollectorsUI.java @@ -0,0 +1,226 @@ +package net.crankedpvp.collectors.inventories; + +import com.golfing8.kore.FactionsKore; +import com.golfing8.kore.feature.OutpostFeature; +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; +import dev.triumphteam.gui.builder.item.ItemBuilder; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.collectors.CollectorsPlugin; +import net.crankedpvp.collectors.collector.Collector; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.collectors.collector.CollectorSellLog; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitTask; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +public class CollectorsUI { + + @Getter + private final Gui collectorUI; + private final Collector collector; + + public CollectorsUI(CollectorsPlugin plugin, Player player, Location location) { + CollectorManager collectorManager = CollectorManager.DELEGATE; + collector = collectorManager.getCollector(location); + FLocation fLocation = new FLocation(location); + Faction faction = Board.getInstance().getFactionAt(fLocation); + + collectorUI = new Gui(5, ChatColor.DARK_GRAY + faction.getTag() + "'s Collector"); + + BukkitTask runnable = Bukkit.getScheduler().runTaskTimer(plugin, this::updateItems, 20L, 20L); + + collectorUI.setCloseGuiAction(event -> runnable.cancel()); + + collectorUI.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemStack glass = new net.crankedpvp.crankedutils.utils.items.ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7)).setName("").build(); + collectorUI.getFiller().fillBorder(new GuiItem(glass)); + + collectorUI.setItem(3,3, ItemBuilder + .from(Material.GOLD_NUGGET) + .setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Mob Drops") + .setLore(getMobDropsLore()) + .asGuiItem(event -> { + if (collector.getWorth() == 0) return; + event.setCancelled(true); + collector.addMobDropSellLog(player, collector.getWorth()); + collector.sellWorth(player); + updateItems(); + })); + + collectorUI.setItem(3,4, ItemBuilder + .from(Material.TNT) + .setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "TNT Drops") + .setLore(getTntLore()) + .asGuiItem(event -> { + if (collector.getTnt() == 0) return; + event.setCancelled(true); + long amount = collector.getTnt(); + if (amount == 0) return; + collector.claimTNT(player); + updateItems(); + })); + + collectorUI.setItem(3,6, ItemBuilder + .from(Material.PAPER) + .setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Sell Logs") + .setLore(getSellLogLore()) + .asGuiItem(event -> event.setCancelled(true))); + + collectorUI.setItem(3,7, ItemBuilder + .from(Material.MOB_SPAWNER) + .setName(ChatColor.GOLD + ChatColor.BOLD.toString() + "Active Spawners") + .setLore(getSpawnersLore()) + .asGuiItem(event -> event.setCancelled(true))); + + if (player.isOp()) { + collectorUI.setItem(5,9, ItemBuilder + .from(Material.HOPPER_MINECART) + .setName(ChatColor.GREEN + ChatColor.BOLD.toString() + CC.translate("Scan Spawners &8(&7Admin Only&8)")) + .setLore( + CC.translate(""), + CC.translate("&7Right-Click this item when having issues with"), + CC.translate("&7missing spawners in the collector,"), + CC.translate("&7this will rescan the chunk to find any missing spawners"), + CC.translate(""), + CC.translate("&c&l(!)&c This item only appears when an admin opens the GUI") + ) + .asGuiItem(event -> { + event.setCancelled(true); + this.collector.clearSpawners(); + this.collector.scanSpawners(this.collector.getLocation()); + player.closeInventory(); + })); + } + } + + public void updateItems() { + + collectorUI.updateItem(3, 3, ItemBuilder + .from(Material.GOLD_NUGGET) + .setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Mob Drops") + .setLore(CC.translate(getMobDropsLore())) + .asGuiItem().getItemStack()); + + collectorUI.updateItem(3,4, ItemBuilder + .from(Material.TNT) + .setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "TNT Drops") + .setLore(CC.translate(getTntLore())) + .asGuiItem().getItemStack()); + + collectorUI.updateItem(3,6, ItemBuilder + .from(Material.PAPER) + .setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Sell Logs") + .setLore(CC.translate(getSellLogLore())) + .asGuiItem().getItemStack()); + + collectorUI.update(); + } + + private List getSpawnersLore() { + List lore = new ArrayList<>(); + double totalPerHour = 0; + + boolean hasDemonicStronghold = FactionsKore.get().getFeature(OutpostFeature.class).getOutpost("demonic").getControllingID().equals(FactionUtils.getFactionAt(collector.getLocation()).getId()); + + lore.add(CC.translate("&e&lSpawners:")); + for (Map.Entry entry : collector.getSpawnersInChunk().entrySet()) { + EntityType type = entry.getKey(); + int amount = entry.getValue(); + if (type == EntityType.BLAZE) continue; + if (type == EntityType.CREEPER) { + lore.add(CC.translate("&e&l * &f" + amount + "x " + getEntityName(type) + " Spawners &8➥ &a" + NumberUtils.formatMoney(CollectorsPlugin.INSTANCE.getSpawnerUtil().getTnTPerHour() * amount) + " TnT/hour")); + + } else { + double value = CollectorsPlugin.INSTANCE.getSpawnerUtil().getMoneyPerMinute(type); + if (hasDemonicStronghold) { + value *= 1.5; + } + lore.add(CC.translate("&e&l * &f" + amount + "x " + getEntityName(type) + " Spawners &8➥ &a$" + NumberUtils.formatMoney(value * 60 * amount) + "/hour")); + totalPerHour += value * amount * 60; + } + } + lore.add(""); + lore.add(CC.translate("&e&lMultipliers:")); + if(hasDemonicStronghold) { + lore.add(CC.translate("&e&l * &fDemonic Stronghold&7 (1.5x Multiplier)")); + } + /* + if (hasFrozenStronghold) { + lore.add(CC.translate("&e&l * &fFrozen Stronghold&7 (1.25x Multiplier)")); + } + if (hasPlutoOutpost) { + lore.add(CC.translate("&e&l * &fPluto Outpost&7 (1.25x Multiplier)")); + } + + */ + lore.add(""); + lore.add(CC.translate("&e&lTotal: &a$" + NumberUtils.formatMoney(totalPerHour) + "/hour")); + lore.add(""); + lore.add(CC.translate("&7The chunkcollector system allows spawners to")); + lore.add(CC.translate("&7activate while the chunk is unloaded.")); + lore.add(CC.translate("&7The amount you make per hour increases depending")); + lore.add(CC.translate("&7on how many and which spawners you have placed.")); + + return lore; + } + + private List getSellLogLore() { + List sellLogs = collector.getSellLogs(); + List sellLogsLore = new ArrayList<>(); + if (!sellLogs.isEmpty()) { + sellLogsLore.add(""); + } + sellLogs.stream().limit(10).forEach(log -> { + String sellTypeString = log.getSellLogType() == CollectorSellLog.SellLogType.TNT ? "Deposited &c" + NumberUtils.formatNum((long) log.getWorth()) + "&7 TNT" : "Sold &a&2$&a" + NumberUtils.formatNum(log.getWorth()) + "&7 Worth of drops"; + sellLogsLore.add(1, CC.translate("&7&o" + log.getSellerName() + "&r&7 " + sellTypeString + " &8(&7" + TimeUtils.formatSeconds((System.currentTimeMillis() - log.getSellDate()) / 1000) + "ago&8)")); + }); + return sellLogsLore; + } + + private List getTntLore() { + return CC.translate(Arrays.asList("", + "&7Right-Click to deposit your TNT", + "&7into your faction TNT bank", + "", + "&a&l * Amount: &f" + NumberUtils.formatNum(collector.getTnt()) + )); + } + + private List getMobDropsLore() { + return CC.translate(Arrays.asList("", + "&7Right-Click to withdraw the money", + "&7to your own balance", + "", + "&a&l * Worth: &2$&f" + NumberUtils.formatNum(collector.getWorth()))); + } + + public static String getEntityName(EntityType type) { + if (type == EntityType.IRON_GOLEM) { + return "Iron Golem"; + } + if (type == EntityType.MUSHROOM_COW) { + return "Mushroom Cow"; + } + return type.getName(); + } + +} \ No newline at end of file diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/language/Language.java b/Collectors/src/main/java/net/crankedpvp/collectors/language/Language.java new file mode 100644 index 0000000..e55e351 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/language/Language.java @@ -0,0 +1,35 @@ +package net.crankedpvp.collectors.language; + +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; + +import java.util.function.UnaryOperator; + +public enum Language { + NEED_FACTION("&c&l(!)&c You need a faction to do this."), + COLLECTOR_HELP("&7/collector &a "), + COLLECTOR_SELL("&a&l+ $%price%"), + COLLECTOR_TNT("&c&l+ %tnt% TNT"), + PLACED_COLLECTOR("&a&l(!)&a Chunk collector placed, mob deaths will cause compatible mob drops to be automatically collected."), + CAN_NOT_PLACE_HERE("&c&l(!)&c You cannot place another collector in this chunk"), + CAN_NOT_PLACE_IN_WILD("&c&l(!)&c You cannot place a collector in wilderness") + ; + + private final String message; + + Language(String message) { + this.message = message; + } + + public String getMessage() { + return CC.translate(message); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(function.apply(message))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(message)); + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/BlockBreakListener.java b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/BlockBreakListener.java new file mode 100644 index 0000000..ad1fa79 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/BlockBreakListener.java @@ -0,0 +1,70 @@ +package net.crankedpvp.collectors.listeners.collectorlisteners; + +import net.crankedpvp.collectors.CollectorsPlugin; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.collectors.collector.CollectorUtils; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.scheduler.BukkitRunnable; + +public class BlockBreakListener implements Listener { + + private final CollectorsPlugin plugin; + + public BlockBreakListener(CollectorsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onBreak(BlockBreakEvent event) { + if (event.isCancelled()) return; + removeCollector(event.getBlock()); + } + + @EventHandler + public void onExplode(BlockExplodeEvent event) { + if (event.isCancelled()) return; + for (Block block : event.blockList()) { + removeCollector(block); + } + } + + @EventHandler + public void onEntityExplode(EntityExplodeEvent event) { + if (event.isCancelled()) return; + for (Block block : event.blockList()) { + removeCollector(block); + } + } + + @EventHandler + public void onEntityExplode(BlockExplodeEvent event) { + if (event.isCancelled()) return; + for (Block block : event.blockList()) { + removeCollector(block); + } + } + + private void removeCollector(Block block) { + if (block.getType() != Material.BEACON) return; + Location location = block.getLocation(); + if (!CollectorManager.DELEGATE.isCollectorContained(location)) return; + Location collectorLocation = CollectorManager.DELEGATE.getCollector(location).getLocation(); + assert collectorLocation != null; + CollectorManager.DELEGATE.getCollector(location).deleteHologram(); + if (!collectorLocation.equals(location)) return; + CollectorManager.DELEGATE.removeCollector(location); + block.setType(Material.AIR,true); + new BukkitRunnable() { + @Override public void run() { + block.getWorld().dropItem(location, CollectorUtils.createCollector(1)); + } + }.runTask(plugin); + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/BlockPlaceListener.java b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/BlockPlaceListener.java new file mode 100644 index 0000000..ba592b2 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/BlockPlaceListener.java @@ -0,0 +1,44 @@ +package net.crankedpvp.collectors.listeners.collectorlisteners; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.collectors.collector.CollectorUtils; +import net.crankedpvp.collectors.language.Language; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; + +public class BlockPlaceListener implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onCollectorPlace(BlockPlaceEvent event) { + if (!CollectorUtils.isCollector(event.getItemInHand())) return; + if (event.isCancelled()) return; + + Location location = event.getBlockPlaced().getLocation(); + + if (CollectorManager.DELEGATE.isCollectorContained(location)) { + Language.CAN_NOT_PLACE_HERE.send(event.getPlayer()); + event.getPlayer().sendMessage(ChatColor.RED + "The collector is located at: " + CollectorManager.DELEGATE.getCollector(location.getChunk()).getLocation().getBlockX() + " " + + CollectorManager.DELEGATE.getCollector(location.getChunk()).getLocation().getBlockY() + " " + CollectorManager.DELEGATE.getCollector(location.getChunk()).getLocation().getBlockZ()); + event.getPlayer().sendMessage(ChatColor.RED + "You can remove this chunk collector by typing: /removecollector"); + event.setCancelled(true); + return; + } + + FLocation fLocation = new FLocation(location); + + if (Board.getInstance().getFactionAt(fLocation).isWilderness() || Board.getInstance().getFactionAt(fLocation).isWarZone()) { + Language.CAN_NOT_PLACE_IN_WILD.send(event.getPlayer()); + event.setCancelled(true); + return; + } + + CollectorManager.DELEGATE.newCollector(location); + Language.PLACED_COLLECTOR.send(event.getPlayer()); + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/PlayerInteractListener.java b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/PlayerInteractListener.java new file mode 100644 index 0000000..98ac190 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/PlayerInteractListener.java @@ -0,0 +1,76 @@ +package net.crankedpvp.collectors.listeners.collectorlisteners; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.PermissibleAction; + +import net.crankedpvp.collectors.CollectorsPlugin; +import net.crankedpvp.collectors.collector.Collector; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.collectors.inventories.CollectorsUI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class PlayerInteractListener implements Listener { + + private final CollectorsPlugin plugin; + + public PlayerInteractListener(CollectorsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerInteract(PlayerInteractEvent event) { + if (event.getClickedBlock() == null ||event.getClickedBlock().getType() == Material.AIR) return; + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (event.isCancelled()) return; + if (event.getClickedBlock().getType() == Material.BEACON) { + Player player = event.getPlayer(); + Location location = event.getClickedBlock().getLocation(); + if (!CollectorManager.DELEGATE.isCollectorContained(location)) return; + if (player.getGameMode().equals(GameMode.SPECTATOR)) return; + event.setCancelled(true); + Location collectorLocation = CollectorManager.DELEGATE.getCollector(location).getLocation(); + assert collectorLocation != null; + if (!collectorLocation.equals(location)) return; + Collector collector = CollectorManager.DELEGATE.getCollector(event.getClickedBlock().getLocation()); + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + + if (FactionUtils.getFaction(event.getPlayer()) != FactionUtils.getFactionAt(collectorLocation) && !event.getPlayer().isOp()) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You need to be in the " + FactionUtils.getFactionAt(collectorLocation).getTag()) + " to open this collector!"); + return; + } + + boolean hasAccess = fPlayer.getFaction().hasAccess(fPlayer, PermissibleAction.COLLECTOR_ACCESS); + + if (!hasAccess) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You need a higher role in your faction to access this collector.")); + return; + } + + if (player.isSneaking()) { + if (collector.getWorth() == 0) return; + collector.addMobDropSellLog(player, collector.getWorth()); + collector.sellWorth(player); + player.sendMessage(CC.translate("&a&l+ $" + NumberUtils.formatMoney(collector.getWorth()))); + return; + } + + CollectorsUI collectorUI = new CollectorsUI(plugin, player, location); + collectorUI.getCollectorUI().open(player); + + + } + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/StackedMobDeathListener.java b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/StackedMobDeathListener.java new file mode 100644 index 0000000..ba1343d --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/collectorlisteners/StackedMobDeathListener.java @@ -0,0 +1,103 @@ +package net.crankedpvp.collectors.listeners.collectorlisteners; + +import net.crankedpvp.collectors.CollectorsPlugin; +import net.crankedpvp.spawners.events.StackedMobDeathEvent; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.SpawnerSpawnEvent; + + +public class StackedMobDeathListener implements Listener { + + CollectorsPlugin plugin; + public StackedMobDeathListener(CollectorsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onStackedEntityDeath(StackedMobDeathEvent e) { +/* Entity entity = e.getEntity(); + if (!(entity instanceof LivingEntity)) return; + if (entity instanceof Blaze) return; + int stackSize = SpawnerPlugin.getInstance().getMobStackerUtils().getStackSize(entity); + if (!(e.getDamager() instanceof Player)) { + Location location = entity.getLocation(); + if (!CollectorManager.DELEGATE.isCollectorContained(location)) return; + Collector collector = CollectorManager.DELEGATE.getCollector(location); + ItemStack itemStack = e.getDrops(entity.getType()); + if (itemStack == null) return; + + if (collector.getTotalMobDropAmount() + (stackSize*4) >= Integer.MAX_VALUE) return; + + collector.incrementAmount(itemStack.getType(), stackSize); + SpawnerPlugin.getInstance().getMobStackerUtils().removeStackedMob(entity); + } + } + + @EventHandler + public void onEntityDeath(EntityDeathEvent e) { + if (!(e.getEntity() instanceof Creature)) return; + if (e.getEntity().getWorld().getName().contains("end")) return; + StackedMobDeathEvent stackedMobDeathEvent = new StackedMobDeathEvent(e.getEntity(), null); + Bukkit.getPluginManager().callEvent(stackedMobDeathEvent); + e.getDrops().clear(); + e.setDroppedExp(0); + + */ + } + +} + + + +/* +public class StackedMobDeathListener implements Listener { + + CollectorsPlugin plugin; + List noCollectorMobs; + public StackedMobDeathListener(CollectorsPlugin plugin) { + this.plugin = plugin; + noCollectorMobs = new ArrayList<>(); + noCollectorMobs.add(EntityType.BLAZE); + } + + @EventHandler + public void onStackedEntityDeath(StackedMobDeathEvent e) { + Entity entity = e.getEntity(); + if (!(e.getDamager() instanceof Player)) { + Location location = entity.getLocation(); + int amount = SpawnerPlugin.getInstance().getMobStackerUtils().getStackSize(entity); + if (!CollectorManager.DELEGATE.isCollectorContained(location)) return; + Collector collector = CollectorManager.DELEGATE.getCollector(location); + ItemStack itemStack = e.getDrops(entity.getType()); + itemStack.setAmount(itemStack.getAmount()*4); + if (itemStack == null) return; + collector.incrementAmount(itemStack.getType(), amount * 200); + SpawnerPlugin.getInstance().getMobStackerUtils().removeStackedMob(entity); + + } + + } + + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onEntitySpawn(SpawnerSpawnEvent e) { + if (noCollectorMobs.contains(e.getEntityType())) { + return; + } + + if (e.getEntity().hasMetadata("end_grinding_mob") || e.getEntity().hasMetadata("end_skeleton_mob") || e.getEntity().hasMetadata("end_creeper_mob")) { + return; + } + + if (!(e.getEntity() instanceof Creature)) return; + + //if (!SpawnerPlugin.getInstance().getMobStackerUtils().isStackedMob(e.getEntity())) return; + final StackedMobDeathEvent stackedMobDeathEvent = new StackedMobDeathEvent(e.getEntity(), null); + Bukkit.getPluginManager().callEvent(stackedMobDeathEvent); + e.setCancelled(true); + } + +} +*/ \ No newline at end of file diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerBlockBreakListener.java b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerBlockBreakListener.java new file mode 100644 index 0000000..52d13f6 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerBlockBreakListener.java @@ -0,0 +1,25 @@ +package net.crankedpvp.collectors.listeners.spawnerlisteners; + +import net.crankedpvp.collectors.collector.Collector; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.spawners.SpawnerPlugin; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; + +public class SpawnerBlockBreakListener implements Listener { + @EventHandler(priority = EventPriority.NORMAL) + public void onBreak(BlockBreakEvent e) { + if (SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(e.getBlock().getLocation()) != null) { + if (CollectorManager.DELEGATE.isCollectorContained(e.getBlock().getLocation())) { + Collector collector = CollectorManager.DELEGATE.getCollector(e.getBlock().getLocation()); + CreatureSpawner spawner = (CreatureSpawner) e.getBlock().getState(); + EntityType type = spawner.getSpawnedType(); + collector.getSpawnersInChunk().remove(type); + } + } + } + } diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerBlockPlaceListener.java b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerBlockPlaceListener.java new file mode 100644 index 0000000..626e9ba --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerBlockPlaceListener.java @@ -0,0 +1,42 @@ +package net.crankedpvp.collectors.listeners.spawnerlisteners; + +import net.crankedpvp.collectors.collector.Collector; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.items.ItemSpawner; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; + +public class SpawnerBlockPlaceListener implements Listener { + @EventHandler(priority = EventPriority.NORMAL) + public void blockPlace(BlockPlaceEvent e) { + + if (e.getBlock().getType() == Material.MOB_SPAWNER) { + if (SpawnerPlugin.coolDownSpawnerPlace.contains(e.getPlayer())) { + e.getPlayer().sendMessage(CC.translate("&c&l(!)&c Please be patient, you are still on spawner place cooldown.")); + e.setCancelled(true); + return; + } + if (ItemSpawner.getSpawnerAmount(e.getItemInHand()) == -1) return; + + int amount = ItemSpawner.getSpawnerAmount(e.getItemInHand()); + EntityType type = ItemSpawner.getEntityTypeFromItem(e.getItemInHand()); + if (type == EntityType.BLAZE) return; + if (CollectorManager.DELEGATE.isCollectorContained(e.getBlock().getLocation())) { + Collector collector = CollectorManager.DELEGATE.getCollector(e.getBlock().getLocation()); + if (collector.getSpawnersInChunk().containsKey(type)) { + int oldAmount = collector.getSpawnersInChunk().get(type); + int newAmount = oldAmount+amount; + collector.getSpawnersInChunk().put(type, newAmount); + } else { + collector.getSpawnersInChunk().put(type, amount); + } + } + } + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerEvents.java b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerEvents.java new file mode 100644 index 0000000..7e6f812 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerEvents.java @@ -0,0 +1,29 @@ +package net.crankedpvp.collectors.listeners.spawnerlisteners; + +import net.crankedpvp.collectors.collector.Collector; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.spawners.events.SpawnerBreakEvent; +import net.crankedpvp.spawners.events.SpawnerPlaceEvent; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class SpawnerEvents implements Listener { + + @EventHandler + public void onSpawnerBreakEvent(SpawnerBreakEvent event) { + if (CollectorManager.DELEGATE.isCollectorContained(event.getLocation())) { + Collector collector = CollectorManager.DELEGATE.getCollector(event.getLocation()); + collector.clearSpawners(); + collector.scanSpawners(collector.getLocation()); + } + } + + @EventHandler + public void onSpawnerPlaceEvent(SpawnerPlaceEvent event) { + if (CollectorManager.DELEGATE.isCollectorContained(event.getLocation())) { + Collector collector = CollectorManager.DELEGATE.getCollector(event.getLocation()); + collector.clearSpawners(); + collector.scanSpawners(collector.getLocation()); + } + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerExplodeListener.java b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerExplodeListener.java new file mode 100644 index 0000000..01d56df --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/listeners/spawnerlisteners/SpawnerExplodeListener.java @@ -0,0 +1,34 @@ +package net.crankedpvp.collectors.listeners.spawnerlisteners; + +import net.crankedpvp.collectors.collector.Collector; +import net.crankedpvp.collectors.collector.CollectorManager; +import net.crankedpvp.spawners.SpawnerPlugin; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityExplodeEvent; + +import java.util.List; + +public class SpawnerExplodeListener implements Listener { + @EventHandler(priority = EventPriority.NORMAL) + public void onBreak(EntityExplodeEvent e) { + List broken = e.blockList(); + for (Block block : broken) { + if (block.getType() != Material.MOB_SPAWNER) continue; + if (SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(block.getLocation()) != null) { + if (CollectorManager.DELEGATE.isCollectorContained(block.getLocation())) { + Collector collector = CollectorManager.DELEGATE.getCollector(block.getLocation()); + CreatureSpawner spawner = (CreatureSpawner) block.getState(); + EntityType type = spawner.getSpawnedType(); + collector.getSpawnersInChunk().remove(type); + } + } + } + + } +} \ No newline at end of file diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/tasks/CollectorWorthUpdateTask.java b/Collectors/src/main/java/net/crankedpvp/collectors/tasks/CollectorWorthUpdateTask.java new file mode 100644 index 0000000..716bc8a --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/tasks/CollectorWorthUpdateTask.java @@ -0,0 +1,19 @@ +package net.crankedpvp.collectors.tasks; + +import net.crankedpvp.collectors.collector.Collector; +import net.crankedpvp.collectors.collector.CollectorManager; +import org.bukkit.scheduler.BukkitRunnable; + +public class CollectorWorthUpdateTask extends BukkitRunnable { + + private final CollectorManager collectorManager; + + public CollectorWorthUpdateTask() { + this.collectorManager = CollectorManager.DELEGATE; + } + + @Override + public void run() { + this.collectorManager.forEach(Collector::update); + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/utils/ChunkUtil.java b/Collectors/src/main/java/net/crankedpvp/collectors/utils/ChunkUtil.java new file mode 100644 index 0000000..9a66f1d --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/utils/ChunkUtil.java @@ -0,0 +1,16 @@ +package net.crankedpvp.collectors.utils; + +import org.bukkit.Location; + +public class ChunkUtil { + public static boolean isLocationAInSameChunkAsLocationB(Location aLocation, Location bLocation) { + double aX = Math.floor(aLocation.getBlockX() / 16); + double aZ = Math.floor(aLocation.getBlockZ() / 16); + double bX = Math.floor(bLocation.getBlockX() / 16); + double bZ = Math.floor(bLocation.getBlockZ() / 16); + + return aX == bX && aZ == bZ; + + } + +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/utils/SpawnerUtil.java b/Collectors/src/main/java/net/crankedpvp/collectors/utils/SpawnerUtil.java new file mode 100644 index 0000000..075c409 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/utils/SpawnerUtil.java @@ -0,0 +1,65 @@ +package net.crankedpvp.collectors.utils; + +import net.crankedpvp.collectors.CollectorsPlugin; +import net.crankedpvp.collectors.utils.config.ConfigManager; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.EntityType; + +import java.util.EnumMap; + +public class SpawnerUtil { + + private final ConfigManager configManager; + private final EnumMap mobIncomeMap; + private int tntPerHour; + + public SpawnerUtil() { + this.configManager = CollectorsPlugin.INSTANCE.getConfigManager(); + this.mobIncomeMap = new EnumMap<>(EntityType.class); + this.reloadMobIncomeMap(); + this.reloadTntIncomeValue(); + } + + public void reloadMobIncomeMap() { + this.mobIncomeMap.clear(); + ConfigurationSection configurationSection = this.configManager.getConfig(ConfigManager.ConfigFile.SETTINGS).getConfigurationSection("spawner-income-per-minute"); + for (String key : configurationSection.getKeys(false)) { + int value = configurationSection.getInt(key); + EntityType entityType = EntityType.valueOf(key); + mobIncomeMap.put(entityType, value); + } + } + + public void reloadTntIncomeValue() { + this.tntPerHour = configManager.getConfig(ConfigManager.ConfigFile.SETTINGS).getInt("tnt-per-minute"); + } + + public double getMoneyPerMinute(EntityType type) { + try { + + return this.mobIncomeMap.get(type); + } catch (Exception e) { + return 0; + } + } + + public double getTnTPerHour() { + try { + return configManager.getConfig(ConfigManager.ConfigFile.SETTINGS).getInt("tnt-per-minute"); + } catch (Exception e) { + return 0; + } + } + + public double getMoneyPerSecond(EntityType type) { + return getMoneyPerMinute(type) / 60; + } + + public double getTntPerMinute() { + return this.tntPerHour; + } + + public double getTntPerSecond() { + return getTntPerMinute() / 60; + } +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/utils/config/AbstractConfig.java b/Collectors/src/main/java/net/crankedpvp/collectors/utils/config/AbstractConfig.java new file mode 100644 index 0000000..cc58bb4 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/utils/config/AbstractConfig.java @@ -0,0 +1,108 @@ +package net.crankedpvp.collectors.utils.config; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class AbstractConfig { + + private final JavaPlugin plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + + public AbstractConfig(JavaPlugin plugin, String path) { + this.plugin = plugin; + this.path = path; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public boolean setupConfigFile() { + boolean copyDefaults = !configFile.exists(); + + this.saveDefaultConfig(); + config = YamlConfiguration.loadConfiguration(configFile); + + if (copyDefaults) this.copyDefaults(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + return result; + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path + "!"); + e.printStackTrace(); + } + return false; + } + + public void saveDefaultConfig() { + if (!configFile.exists()) { + InputStream defConfig = plugin.getResource(path); + if (defConfig != null) { + plugin.saveResource(path,false); + } else { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path + "!"); + e.printStackTrace(); + } + } + } + } + + + public boolean reloadConfig() { + boolean copyDefaults = !configFile.exists(); + + this.saveDefaultConfig(); + config = YamlConfiguration.loadConfiguration(configFile); + + if (copyDefaults) this.copyDefaults(); + + this.saveConfig(); + return this.loadConfigFromDisk(); + } + + public boolean loadConfigFromDisk() { + try { + config.load(configFile); + return true; + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path + "!"); + e.printStackTrace(); + } + return false; + } + + public void copyDefaults() { + InputStream defConfig = plugin.getResource(path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + public FileConfiguration getConfig() { + return config; + } + + public String getPath() { + return path; + } + +} diff --git a/Collectors/src/main/java/net/crankedpvp/collectors/utils/config/ConfigManager.java b/Collectors/src/main/java/net/crankedpvp/collectors/utils/config/ConfigManager.java new file mode 100644 index 0000000..1364f79 --- /dev/null +++ b/Collectors/src/main/java/net/crankedpvp/collectors/utils/config/ConfigManager.java @@ -0,0 +1,51 @@ +package net.crankedpvp.collectors.utils.config; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; + +public class ConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public ConfigManager(JavaPlugin plugin) { + + for (ConfigFile configFile : ConfigFile.values()) { + AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName()); + configs.put(configFile, abstractConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AbstractConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AbstractConfig::reloadConfig); + } + + public AbstractConfig getAbstractConfig(ConfigFile configFile) { + return configs.get(configFile); + } + + public FileConfiguration getConfig(ConfigFile configFile) { + return getAbstractConfig(configFile).getConfig(); + } + + @Getter + @RequiredArgsConstructor + public enum ConfigFile { + + SETTINGS("settings.yml"), + ; + + private final String fileName; + + } + +} diff --git a/Collectors/src/main/resources/language.yml b/Collectors/src/main/resources/language.yml new file mode 100644 index 0000000..3d7fba5 --- /dev/null +++ b/Collectors/src/main/resources/language.yml @@ -0,0 +1,7 @@ +NEED_FACTION: "&c&l:(!)&c You need a faction to do this." +COLLECTOR_HELP: "&7/collector &a " +COLLECTOR_SELL: "&a&l+ $%price%" +COLLECTOR_TNT: "&c&l+ %tnt% TNT" +PLACED_COLLECTOR: "&a&l(!)&a Chunk collector placed, mob deaths will cause compatible mob drops to be automatically collected." +CAN_NOT_PLACE_HERE: "&c&l(!)&c You cannot place another collector in this chunk" +CAN_NOT_PLACE_IN_WILD: "&c&l(!)&c You cannot place a collector in wilderness") \ No newline at end of file diff --git a/Collectors/src/main/resources/plugin.yml b/Collectors/src/main/resources/plugin.yml new file mode 100644 index 0000000..782f69f --- /dev/null +++ b/Collectors/src/main/resources/plugin.yml @@ -0,0 +1,20 @@ +name: CrankedCollectors +main: net.crankedpvp.collectors.CollectorsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedSpawners + - Factions + - FactionsKore +commands: + c: + aliases: [collector] + permission: cranked.admin + permission-message: Permission denied + removecollector: + aliases: [removechunkcollector] + collectorreload: + permission: cranked.admin + permission-message: Permission denied diff --git a/Collectors/src/main/resources/settings.yml b/Collectors/src/main/resources/settings.yml new file mode 100644 index 0000000..2cec1eb --- /dev/null +++ b/Collectors/src/main/resources/settings.yml @@ -0,0 +1,10 @@ +spawner-income-per-minute: + IRON_GOLEM: 16000 + VILLAGER: 50000 + PIG_ZOMBIE: 1500 + ZOMBIE: 383 + SKELETON: 383 + SPIDER: 316 + CAVE_SPIDER: 316 + CREEPER: 0 +tnt-per-minute: 85 \ No newline at end of file diff --git a/CombatLog/pom.xml b/CombatLog/pom.xml new file mode 100644 index 0000000..117a43a --- /dev/null +++ b/CombatLog/pom.xml @@ -0,0 +1,39 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + CombatLog + + + 8 + 8 + + + + Utils + net.crankedpvp + + + Core + net.crankedpvp + + + net.crankedpvp + LunarAPI + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/CombatTagAPI.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/CombatTagAPI.java new file mode 100644 index 0000000..0d21d9b --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/CombatTagAPI.java @@ -0,0 +1,42 @@ +package net.crankedpvp.combatlog; + +import com.lunarclient.bukkitapi.cooldown.LunarClientAPICooldown; +import net.crankedpvp.crankedutils.events.PlayerCombatEnterEvent; +import net.crankedpvp.combatlog.language.Language; +import net.crankedpvp.combatlog.tasks.CombatTimer; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; + +public class CombatTagAPI { + public static void putPlayerInCombat(Player player) { + if (player == null) return; + + if (player.getAllowFlight()) { + player.setAllowFlight(false); + } + if (player.isFlying()) { + player.setFlying(false); + } + + LunarClientAPICooldown.sendCooldown(player, "CombatTag"); + if(!CombatTimer.playersInCombat.containsKey(player)) { + player.sendMessage(CC.translate(Language.ENTER_COMBAT.getMessage().replace("%duration%", Language.COMBAT_DURATION.getValue()))); + Event event = new PlayerCombatEnterEvent(player); + Bukkit.getServer().getPluginManager().callEvent(event); + } + CombatTimer.playersInCombat.put(player, 0); + } + + public static void removePlayerFromCombat(Player player) { + LunarClientAPICooldown.clearCooldown(player, "CombatTag"); + CombatTimer.playersInCombat.remove(player); + player.sendMessage(CC.translate(Language.LEFT_COMBAT.getMessage().replace("%duration%", Language.COMBAT_DURATION.getValue()))); + } + + public static boolean isInCombat(Player player) { + return CombatTimer.playersInCombat.containsKey(player) && WorldGuardUtils.canPvPInRegion(player); + } +} diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/CombatlogPlugin.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/CombatlogPlugin.java new file mode 100644 index 0000000..569cb10 --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/CombatlogPlugin.java @@ -0,0 +1,42 @@ +package net.crankedpvp.combatlog; + +import com.lunarclient.bukkitapi.cooldown.LCCooldown; +import com.lunarclient.bukkitapi.cooldown.LunarClientAPICooldown; +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.combatlog.commands.AdminCombatCommand; +import net.crankedpvp.combatlog.commands.ToggleBarCommand; +import net.crankedpvp.combatlog.language.Language; +import net.crankedpvp.combatlog.language.LanguageHandler; +import net.crankedpvp.combatlog.listeners.CombatDamageListener; +import net.crankedpvp.combatlog.listeners.CombatWhitelistedCommand; +import net.crankedpvp.combatlog.tasks.CombatTimer; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.plugin.java.JavaPlugin; + +@Getter +public class CombatlogPlugin extends JavaPlugin { + @Getter + private static CombatlogPlugin instance; + private LanguageHandler languageHandler; + private CommandManager commandManager; + public void onEnable() { + instance = this; + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + LunarClientAPICooldown.registerCooldown(new LCCooldown("CombatTag", Long.parseLong(Language.COMBAT_DURATION.getValue()), Material.DIAMOND_SWORD)); + PluginUtils.registerListeners(this, new CombatDamageListener(), new CombatWhitelistedCommand()); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new CombatTimer(), 20L, 20L); + this.commandManager = new CommandManager(this); + commandManager.register(new AdminCombatCommand()); + commandManager.register(new ToggleBarCommand()); + + } + + public void onDisable() { + CombatTimer.playersInCombat.clear(); + instance = null; + } +} diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/commands/AdminCombatCommand.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/commands/AdminCombatCommand.java new file mode 100644 index 0000000..4a9a149 --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/commands/AdminCombatCommand.java @@ -0,0 +1,26 @@ +package net.crankedpvp.combatlog.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.annotations.WrongUsage; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.combatlog.CombatlogPlugin; +import net.crankedpvp.combatlog.language.Language; +import org.bukkit.entity.Player; + +@Command("cl") +public class AdminCombatCommand extends CommandBase { + @SubCommand("reload") + @WrongUsage("&cUsage: /cl reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + CombatlogPlugin.getInstance().getLanguageHandler().load(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } +} diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/commands/ToggleBarCommand.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/commands/ToggleBarCommand.java new file mode 100644 index 0000000..e0b1b30 --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/commands/ToggleBarCommand.java @@ -0,0 +1,27 @@ +package net.crankedpvp.combatlog.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.combatlog.language.Language; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("combattagtimer") +@Alias({"togglecombattag", "togglecombattagtimer"}) +public class ToggleBarCommand extends CommandBase { + @Default + public void toggle(CommandSender sender) { + CrankedUser user = CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(((Player)sender).getUniqueId()); + if (user.isCombatTagTimerEnabled()) { + user.setCombatTagTimerEnabled(false); + Language.DISABLED_TIMER.send(sender); + } else { + user.setCombatTagTimerEnabled(true); + Language.ENABLED_TIMER.send(sender); + } + } +} diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/language/Language.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/language/Language.java new file mode 100644 index 0000000..ec779c9 --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/language/Language.java @@ -0,0 +1,106 @@ +package net.crankedpvp.combatlog.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + ENTER_COMBAT, + LEFT_COMBAT, + COMBAT_DURATION, + BLACKLISTED_COMMAND, + COMBAT_WHITELISTED_COMMANDS, + COMBAT_BLACKLISTED_COMMANDS, + ADMIN_RELOADING, + ADMIN_RELOADED, + BYPASSING_COMMAND_BLACKLIST, + ENABLED_TIMER, + DISABLED_TIMER, + + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/language/LanguageHandler.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/language/LanguageHandler.java new file mode 100644 index 0000000..a1c479c --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.combatlog.language; + +import net.crankedpvp.combatlog.CombatlogPlugin; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final CombatlogPlugin plugin; + + public LanguageHandler(CombatlogPlugin plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/listeners/CombatDamageListener.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/listeners/CombatDamageListener.java new file mode 100644 index 0000000..f2e7554 --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/listeners/CombatDamageListener.java @@ -0,0 +1,101 @@ +package net.crankedpvp.combatlog.listeners; + +import com.lunarclient.bukkitapi.cooldown.LunarClientAPICooldown; +import net.crankedpvp.combatlog.CombatTagAPI; +import net.crankedpvp.combatlog.tasks.CombatTimer; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.GameMode; +import org.bukkit.entity.EnderPearl; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class CombatDamageListener implements Listener { + + @EventHandler + public void onPlayerLeave(PlayerQuitEvent event) { + Player player = event.getPlayer(); + if (!WorldGuardUtils.canPvPInRegion(player)) return; + //if (CombatTimer.playersInCombat.containsKey(player)) player.setHealth(0.0); + if (CombatTagAPI.isInCombat(player)) player.setHealth(0.0); + } + + @EventHandler + public void onPlayerKick(PlayerKickEvent event) { + Player player = event.getPlayer(); + if (!WorldGuardUtils.canPvPInRegion(player)) return; + //if (CombatTimer.playersInCombat.containsKey(player)) player.setHealth(0.0); + if (CombatTagAPI.isInCombat(player)) player.setHealth(0.0); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + //if (event.getEntity().getWorld().getName().equals("world_arenas")) return; + if (event.isCancelled()) return; + if(event.getDamage() <= 0) return; + Player victim = null; + Player attacker = null; + + // Handle projectile hits on players and bosses + if (event.getDamager() instanceof Projectile) { + if (!(event.getEntity() instanceof Player)) return; + + if (event.getDamager() instanceof EnderPearl) return; + + Projectile projectile = (Projectile) event.getDamager(); + + if (!(projectile.getShooter() instanceof Player)) return; + + + victim = (Player) event.getEntity(); + attacker = (Player) projectile.getShooter(); + + } + + // Handle direct hits by players + else if (event.getEntity() instanceof Player && event.getDamager() instanceof Player) { + victim = (Player) event.getEntity(); + attacker = (Player) event.getDamager(); + } + + if (victim == null) return; + + if (attacker != null && + attacker.getGameMode() != GameMode.SURVIVAL && + attacker.getGameMode() != GameMode.ADVENTURE) return; + + this.handleCombatTag(victim, attacker); + } + + @EventHandler + public void onPlayerDeath(PlayerDeathEvent event) { + if (event.getEntity() == null) return; + LunarClientAPICooldown.clearCooldown(event.getEntity(), "CombatTag"); + CombatTimer.playersInCombat.remove(event.getEntity()); + } + + private void handleCombatTag(@NotNull Player victim, @Nullable Player attacker) { + if (attacker != null) { + if (victim.getUniqueId().equals(attacker.getUniqueId())) { + this.handleTagActions(attacker); + return; + } + this.handleTagActions(attacker); + } + this.handleTagActions(victim); + } + + private void handleTagActions(Player combatPlayer) { + CombatTagAPI.putPlayerInCombat(combatPlayer); + } + + +} \ No newline at end of file diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/listeners/CombatWhitelistedCommand.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/listeners/CombatWhitelistedCommand.java new file mode 100644 index 0000000..137d0d0 --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/listeners/CombatWhitelistedCommand.java @@ -0,0 +1,49 @@ +package net.crankedpvp.combatlog.listeners; + +import java.util.List; + +import net.crankedpvp.combatlog.CombatTagAPI; +import net.crankedpvp.combatlog.language.Language; +import net.crankedpvp.combatlog.tasks.CombatTimer; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.apache.commons.codec.language.bm.Lang; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +public class CombatWhitelistedCommand implements Listener { + + @EventHandler (priority = EventPriority.LOWEST) + public void onCommandInCombat(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + + if(!CombatTagAPI.isInCombat(event.getPlayer())) return; + + //if (!CombatTimer.playersInCombat.containsKey(player)) return; + + if (player.hasPermission("cranked.admin")) { + Language.BYPASSING_COMMAND_BLACKLIST.send(player); + return; + } + + //if (!WorldGuardUtils.canPvPInRegion(player)) return; + + String command = event.getMessage().replace("/", ""); + List whitelistedCommands = Language.COMBAT_WHITELISTED_COMMANDS.getValuesAsList(); + List blacklistedCommands = Language.COMBAT_BLACKLISTED_COMMANDS.getValuesAsList(); + + if (blacklistedCommands.stream().anyMatch(command::equals)) { + event.setCancelled(true); + Language.BLACKLISTED_COMMAND.send(player); + return; + } + + if (whitelistedCommands.stream().anyMatch(command::startsWith)) return; + + event.setCancelled(true); + Language.BLACKLISTED_COMMAND.send(player); + } + +} \ No newline at end of file diff --git a/CombatLog/src/main/java/net/crankedpvp/combatlog/tasks/CombatTimer.java b/CombatLog/src/main/java/net/crankedpvp/combatlog/tasks/CombatTimer.java new file mode 100644 index 0000000..ebaafce --- /dev/null +++ b/CombatLog/src/main/java/net/crankedpvp/combatlog/tasks/CombatTimer.java @@ -0,0 +1,55 @@ +package net.crankedpvp.combatlog.tasks; + +import com.google.common.base.Strings; +import net.crankedpvp.combatlog.language.Language; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.ActionBarUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class CombatTimer implements Runnable { + public void run() { + List list = new ArrayList<>(); + for (Player player : playersInCombat.keySet()) { + if (playersInCombat.get(player) >= combatTimer) { + Language.LEFT_COMBAT.send(player); + ActionBarUtils actionBarUtils1 = new ActionBarUtils(CC.translate("&b&lCombat &7↣ &8[&aExpired&8]")); + actionBarUtils1.sendToPlayer(player); + player.playSound(player.getLocation(), Sound.ENDERDRAGON_WINGS, 3, 5); + player.setAllowFlight(true); + list.add(player); + continue; + } + playersInCombat.replace(player, playersInCombat.get(player) + 1); + + if (CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(player.getUniqueId()).isCombatTagTimerEnabled()) { + ActionBarUtils actionBarUtils = new ActionBarUtils(CC.translate("&b&lCombat &7⤔ &8[" + getProgressBar((combatTimer - playersInCombat.get(player)), 10, 10) + "&8]")); + actionBarUtils.sendToPlayer(player); + } + + } + for (Player player : list) { + playersInCombat.remove(player); + } + } + + public static HashMap playersInCombat = new HashMap<>(); + + public int combatTimer = Integer.parseInt(Language.COMBAT_DURATION.getValue()); + + public static String getProgressBar(int currentLevel, int maxLevel, int totalSquares) { + float percent = (float) currentLevel / maxLevel; + int progressBars = (int) (totalSquares * percent); + + return CC.translate( + Strings.repeat("&a|", progressBars) + + Strings.repeat("&c|", totalSquares - progressBars) + ); + } +} \ No newline at end of file diff --git a/CombatLog/src/main/resources/config.yml b/CombatLog/src/main/resources/config.yml new file mode 100644 index 0000000..910a963 --- /dev/null +++ b/CombatLog/src/main/resources/config.yml @@ -0,0 +1 @@ +#I like carrots ~Bry \ No newline at end of file diff --git a/CombatLog/src/main/resources/language.yml b/CombatLog/src/main/resources/language.yml new file mode 100644 index 0000000..89b369e --- /dev/null +++ b/CombatLog/src/main/resources/language.yml @@ -0,0 +1,14 @@ +ENTER_COMBAT: "&c&lCombatLog &8➥ &7You have &aentered &7combat. Do not log out for &a%duration%&7 seconds." +LEFT_COMBAT: "&c&lCombatLog &8➥ &7You have &cleft&7 combat. You can now safely log out." +COMBAT_DURATION: 10 +BLACKLISTED_COMMAND: "&c&lCombatLog &8➥ &7That command is &cnot &7allowed while in combat." +ADMIN_RELOADING: "&c&lCombatLog &8➥ &7Reloading configs now..." +ADMIN_RELOADED: "&c&lCombatLog &8➥ &7Reloaded configs and other cool stuff. Took &d%took%ms&7." +BYPASSING_COMMAND_BLACKLIST: "&c&lCombatLog &8➥ &7You have bypassed blocked commands during combat" +ENABLED_TIMER: "&c&lCombatLog &8➥ &7You &a&lENABLED&7 CombatTag Timer" +DISABLED_TIMER: "&c&lCombatLog &8➥ &7You &c&lDISABLED&7 CombatTag Timer" +COMBAT_WHITELISTED_COMMANDS: + - "bless" + - "apply" +COMBAT_BLACKLISTED_COMMANDS: + - "fly" \ No newline at end of file diff --git a/CombatLog/src/main/resources/plugin.yml b/CombatLog/src/main/resources/plugin.yml new file mode 100644 index 0000000..06d369c --- /dev/null +++ b/CombatLog/src/main/resources/plugin.yml @@ -0,0 +1,6 @@ +name: CrankedCombatLog +version: 1.1 +main: net.crankedpvp.combatlog.CombatlogPlugin +depend: + - CrankedUtils + - CrankedLunarAPI \ No newline at end of file diff --git a/Core/pom.xml b/Core/pom.xml new file mode 100644 index 0000000..2ec6f0f --- /dev/null +++ b/Core/pom.xml @@ -0,0 +1,154 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Core + + + 8 + 8 + + + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + Utils + net.crankedpvp + + + net.crankedpvp + LunarAPI + + + ChatTitles + net.crankedpvp + + + Lootboxes + net.crankedpvp + + + Spawners + net.crankedpvp + 1.0 + + + Masks + net.crankedpvp + 1.0 + + + StarItems + net.crankedpvp + 1.0 + + + ItemFilter + net.crankedpvp + 1.0 + + + net.crankedpvp + AdminWeapons + + + net.crankedpvp + DiscordSync + + + net.crankedpvp + AdminArmor + + + net.crankedpvp + Armor + + + com.sk89q + worldguard + provided + + + net.crankedpvp + tab-api + 0.1 + system + ${project.basedir}/../.lib/TAB.v3.1.2.jar + + + com.massivecraft + Factions + + + net.luckperms + api + + + com.github.MilkBowl + VaultAPI + + + net.crankedpvp + Enchants + 1.0 + + + net.crankedpvp + Staff + + + net.crankedpvp + Shop + 1.0 + + + com.comphenix.protocol + ProtocolLib + + + net.crankedpvp + CombatLog + + + factionskore + FactionsKore + 1.0 + system + ${project.basedir}/../.lib/FactionsKore-1.3.62.1.jar + + + com.earth2me.essentials + EssentialsX + 1.0 + system + ${project.basedir}/../.lib/EssentialsX-2.19.7.jar + + + winespigot + WineSpigot + 1.0 + system + ${project.basedir}/../.lib/WineSpigot-V1.7.4.2.jar + + + net.crankedpvp + Collect + 1.0 + + + + + \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/CrankedCore.java b/Core/src/main/java/net/crankedpvp/crankedcore/CrankedCore.java new file mode 100644 index 0000000..c15db53 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/CrankedCore.java @@ -0,0 +1,275 @@ +package net.crankedpvp.crankedcore; + +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.comphenix.protocol.reflect.FieldAccessException; +import lombok.Getter; +import lombok.Setter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedarmor.struct.ArmorSetRegister; +import net.crankedpvp.crankedcore.commands.*; +import net.crankedpvp.crankedcore.data.CrankedUserManager; +import net.crankedpvp.crankedcore.hotfix.CitizensReload; +import net.crankedpvp.crankedcore.items.IceWandItem; +import net.crankedpvp.crankedcore.items.MagicalLavaBucketItem; +import net.crankedpvp.crankedcore.items.MagicalWaterBucketItem; +import net.crankedpvp.crankedcore.items.SandWandItem; +import net.crankedpvp.crankedcore.language.LanguageHandler; +import net.crankedpvp.crankedcore.listeners.*; +import net.crankedpvp.crankedcore.managers.CommandBlockerManager; +import net.crankedpvp.crankedcore.managers.GiveAwayManager; +import net.crankedpvp.crankedcore.managers.HelmetSkinManager; +import net.crankedpvp.crankedcore.managers.StaffChatManager; +import net.crankedpvp.crankedcore.struct.crystals.EnchantEnum; +import net.crankedpvp.crankedcore.struct.gifts.Gift; +import net.crankedpvp.crankedcore.struct.kits.KitManager; +import net.crankedpvp.crankedcore.struct.netherpvp.NetherPvPQueueManager; +import net.crankedpvp.crankedcore.struct.reboot.Reboot; +import net.crankedpvp.crankedcore.struct.typeadapters.GiftAdapterSerializer; +import net.crankedpvp.crankedcore.struct.typeadapters.GiftsListAdapterSerializer; +import net.crankedpvp.crankedcore.tasks.AutoBroadcastTask; +import net.crankedpvp.crankedcore.tasks.ProxyPatchTask; +import net.crankedpvp.crankedcore.utils.ConfigManager; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.gson.Gson; +import net.crankedpvp.storageutils.gson.reflect.TypeToken; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; + +import java.lang.reflect.Type; +import java.util.List; + +@Getter +public class CrankedCore extends JavaPlugin { + + private final Type itemstackListType = new TypeToken>(){}.getType(); + private final Type giftListType = new TypeToken>(){}.getType(); + + private LanguageHandler languageHandler; + private Economy economy; + private StaffChatManager staffChatManager; + private CommandManager commandManager; + private CrankedUserManager crankedUserManager; + private AutoBroadcastTask autoBroadcastTask; + private CommandBlockerManager commandBlockerManager; + private ProtocolManager protocolManager; + private ConfigManager configManager; + private KitManager kitManager; + private HelmetSkinManager helmetSkinManager; + private GiveAwayManager giveAwayManager; + private NetherPvPQueueManager netherPvPQueueManager; + @Setter + private ProxyPatchTask proxyPatchTask; + + private Gson gson; + + @Setter + private Reboot reboot; + + @Getter + private static CrankedCore instance; + + public void onEnable() { + instance = this; + + saveDefaultConfig(); + + this.gson = StorageUtils.getInstance() + .getGson() + .newBuilder() + //.registerTypeAdapter(Gift.class, new GiftAdapterDeserializer()).setLenient() + .registerTypeAdapter(Gift.class, new GiftAdapterSerializer()).setLenient() + .registerTypeAdapter(this.giftListType, new GiftsListAdapterSerializer()).setLenient() + //.registerTypeAdapter(this.giftListType, new GiftsListAdapterDeserializer()).setLenient() + .create(); + + this.commandManager = new CommandManager(this); + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + this.staffChatManager = new StaffChatManager(); + this.crankedUserManager = new CrankedUserManager(this); + this.commandBlockerManager = new CommandBlockerManager(this); + this.kitManager = new KitManager(); + this.kitManager.loadAll(); + this.configManager = new ConfigManager(this); + this.configManager.setupFiles(); + this.commandBlockerManager.loadCommands(this); + this.giveAwayManager = new GiveAwayManager(this); + this.netherPvPQueueManager = new NetherPvPQueueManager(this); + + this.setupEconomy(); + this.registerCommands(); + this.registerListeners(); + this.crankedUserManager.loadAll(); + this.autoBroadcastTask = new AutoBroadcastTask(this); + this.autoBroadcastTask.setupMessages(); + this.autoBroadcastTask.runTaskTimerAsynchronously(this, 2, 90*20); + + this.proxyPatchTask = new ProxyPatchTask(); + this.proxyPatchTask.runTaskTimer(this, 80L, 20L); + this.protocolFix(); + + this.getServer().getScheduler().runTaskLater(this, CitizensReload::reloadCitizens, 10 * 20L); + + this.helmetSkinManager = new HelmetSkinManager(); + this.helmetSkinManager.load(this); + + StarItemsAPI.addItemToStarItemsUI(ArmorSetRegister.getInstance().getArmorSetFromID("spectre").buildHeroicArmorUpgrade(100)); + StarItemsAPI.addItemToStarItemsUI(ArmorSetRegister.getInstance().getArmorSetFromID("spectre").buildHeroicWeaponUpgrade(100)); + //StarItemsAPI.addItemToStarItemsUI(ArmorSetRegister.getInstance().getArmorSetFromID("spectre").buildHeroicHookUpgrade(100)); + + + + } + + public void onDisable() { + if (crankedUserManager != null) crankedUserManager.saveAll(); + if (this.commandBlockerManager != null) this.commandBlockerManager.saveCommands(this); + if (this.helmetSkinManager != null) this.helmetSkinManager.unload(); + instance = null; + } + + private void registerListeners() { + PluginUtils.registerListeners(this, + new NetherPvpListener(this), + new ChatListener(this), + new AntiBoatListener(), + new AntiMinecartListener(), + new AntiBookEnchantListener(), + new AlwaysSunnyListener(), + new AntiBedListener(), + new AntiBlockGlitchListener(), + new AntiDroppedItemRemoveListener(), + new AntiDrownListener(), + new AntiFallDamageListener(), + new AntiHopperListener(), + new AntiMinecartListener(), + new AntiSlimeSplitListener(), + new NoHungerListener(), + new AutoFlyListener(), + new ExpBottleListener(), + new MoneyNoteListener(), + new EnderpearlStackListener(), + new MOTDListener(), + new WarzoneClaimListener(), + new KillTitleMessageListener(), + new BlockCommandListener(), + new ServerStatsListener(), + new GoldenAppleSicknessListener(), + new FirstJoinListener(this), + new WarpAliasListener(), + new CrystalListener(), + new AntiDoorHitListener(), + new SandWandItem(this), + new NetherDamageListener(), + new IceWandItem(), + new MagicalLavaBucketItem(this), + new MagicalWaterBucketItem(), + new ProtectLootListener(this), + new WarpCommandListener(), + new AntiBrewingStandListener(), + new LuckpermsRankFixListener(), + new LastHitListener(), + new AntiSlowInVanishListener(), + new ResetSpeedOnJoinListener(), + new EnderPearlCooldownListener(), + new NetherJoinListener() + ); + + } + + private void registerCommands() { + this.commandManager.getParameterHandler().register(EnchantEnum.class, argument -> { + EnchantEnum enchantEnum = EnchantEnum.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(enchantEnum, argument); + }); + + this.commandManager.register(new NetherPvPCommand(this)); + this.commandManager.register(new BlessCommand(this)); + this.commandManager.register(new InvseeCommand(this)); + this.commandManager.register(new StaffChatCommand(this)); + this.commandManager.register(new GodsetCommand(this)); + this.commandManager.register(new ChatColorCommand(this)); + this.commandManager.register(new AdminCoreCommand()); + this.commandManager.register(new ExpBottleCommand()); + this.commandManager.register(new WithdrawCommand()); + this.commandManager.register(new NearCommand(this)); + this.commandManager.register(new RenameCommand()); + this.commandManager.register(new LoreCommand()); + this.commandManager.register(new ClearInventoryCommand(this)); + this.commandManager.register(new GiveallCommand()); + this.commandManager.register(new BlockCommandCommand(this)); + this.commandManager.register(new HealCommand()); + this.commandManager.register(new AdminKitCommand(this)); + this.commandManager.register(new CheckNBTCommand()); + this.commandManager.register(new KitCommand()); + this.commandManager.register(new PotsCommand()); + this.commandManager.register(new CrystalCommand()); + this.commandManager.register(new SandWandCommand()); + this.commandManager.register(new IceWandCommand()); + this.commandManager.register(new MagicalLavaBucketCommand()); + this.commandManager.register(new MagicalWaterBucketCommand()); + this.commandManager.register(new RebootCommand(this)); + this.commandManager.register(new GiveAwayCommand()); + this.commandManager.register(new BroadcastCommand()); + this.commandManager.register(new ListCommand()); + this.commandManager.register(new DiscordCommand()); + this.commandManager.register(new AdminItemsCommand(this)); + this.commandManager.register(new LFFCommand()); + this.commandManager.register(new DebugPlayerCommand()); + this.commandManager.register(new GiftCommand(this)); + this.commandManager.register(new GiftsCommand()); + this.commandManager.register(new SpawnerShopCommand()); + this.commandManager.register(new CrankedStatsCommand()); + this.commandManager.register(new RainbowifyCommand()); + this.commandManager.register(new ProxyPatchCommand(this)); + this.commandManager.register(new FixCommand(this)); + this.commandManager.register(new MoreCommand(this)); + this.commandManager.register(new SeeAllCommand()); + + + } + + private void setupEconomy() { + RegisteredServiceProvider provider = Bukkit.getServicesManager().getRegistration(Economy.class); + if (provider != null) { + this.economy = provider.getProvider(); + } + } + + public void protocolFix() { + this.protocolManager = ProtocolLibrary.getProtocolManager(); + this.protocolManager.addPacketListener(new PacketAdapter(this, ListenerPriority.NORMAL, PacketType.Play.Client.TAB_COMPLETE) { + + public void onPacketReceiving(PacketEvent event) { + if (event.getPacketType() == PacketType.Play.Client.TAB_COMPLETE) { + if (event.getPlayer().isOp()) return; + + try { + PacketContainer packet = event.getPacket(); + String message = packet.getSpecificModifier(String.class).read(0).toLowerCase(); + if (message.startsWith("/?") && !message.contains(" ") || message.startsWith("/") && !message.contains(" ") + || message.startsWith("/help") && !message.contains(" ") || message.startsWith("/ver") && !message.contains(" ") + || message.startsWith("/bukkit") && !message.contains(" ")) { + event.setCancelled(true); + } + } catch (FieldAccessException e) { + e.printStackTrace(); + } + } + } + + }); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminCoreCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminCoreCommand.java new file mode 100644 index 0000000..389555e --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminCoreCommand.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.annotations.WrongUsage; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import org.bukkit.entity.Player; + +@Command("cc") +public class AdminCoreCommand extends CommandBase { + @SubCommand("reload") + @WrongUsage("&cUsage: /cc reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + CrankedCore.getInstance().getLanguageHandler().load(); + CrankedCore.getInstance().getAutoBroadcastTask().reload(); + CrankedCore.getInstance().getCommandBlockerManager().reloadConfig(CrankedCore.getInstance()); + + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminItemsCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminItemsCommand.java new file mode 100644 index 0000000..76547f3 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminItemsCommand.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.guis.AdminItemsGUI; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +@Command("adminitems") +@Alias({"adminitem", "aitems", "admini"}) +public class AdminItemsCommand extends CommandBase { + + private final CrankedCore plugin; + public AdminItemsCommand(CrankedCore plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(Player player) { + AdminItemsGUI adminItemsGUI = new AdminItemsGUI(player); + adminItemsGUI.getAdminItemGUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 1.0f, 1.0f); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminKitCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminKitCommand.java new file mode 100644 index 0000000..2e272f0 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/AdminKitCommand.java @@ -0,0 +1,98 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.struct.kits.Kit; +import net.crankedpvp.crankedcore.struct.kits.KitManager; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +@Command("ckit") +public class AdminKitCommand extends CommandBase { + + private final KitManager kitManager; + public AdminKitCommand(CrankedCore plugin) { + this.kitManager = plugin.getKitManager(); + } + + @Default + @Permission("cranked.admin") + public void defaultCommand(CommandSender commandSender) { + Language.ADMINKIT_HELP.send(commandSender); + } + + @SubCommand("give") + @WrongUsage("&7/ckit &4give &c ") + @Permission("cranked.admin") + public void kitGive(CommandSender sender, String kitName, Player target) { + kitName = kitName.toLowerCase(); + Kit kit = this.kitManager.getFromCache(kitName); + if (kit == null) { + Language.KIT_INVALID_NAME.send(sender); + return; + } + + String finalKitStringed = kitName; + Language.KIT_RECEIVED.send(sender, string -> string.replace("%kit%", finalKitStringed)); + kit.supplyKit(target); + } + + @SubCommand("delete") + @WrongUsage("&7/ckit &4delete &c") + @Permission("cranked.admin") + public void kitDelete(CommandSender sender, String kitName) { + kitName = kitName.toLowerCase(); + Kit kit = this.kitManager.getFromCache(kitName); + if (kit == null) { + Language.KIT_INVALID_NAME.send(sender); + return; + } + + this.kitManager.removeFromCache(kitName); + sender.sendMessage(CC.Green + "Deleted the kit!!"); + this.kitManager.saveAll(); + this.kitManager.purge(); + + } + + @SubCommand("resetcooldown") + @Permission("cranked.admin") + public void resetCooldownCommand(final CommandSender commandSender, String kitName) { + + } + + @SubCommand("create") + @WrongUsage("&7/ckit &4create &c [gkit]") + @Permission("cranked.admin") + public void kitCreate(final CommandSender sender, String kitName, final Integer cooldownInSeconds, final Integer weight, @Optional Boolean gkit) { + if(gkit == null) gkit = false; + kitName = kitName.toLowerCase(); + final long cooldownInMs = TimeUnit.SECONDS.toMillis(cooldownInSeconds); + + if (this.kitManager.containsKey(kitName)) { + //already exist + Language.ADMINKIT_ALREADY_EXISTS.send(sender); + return; + } + + final ItemStack[] itemStacks = Arrays.stream(((Player) sender).getInventory().getContents()) + .filter(Objects::nonNull) + .map(ItemStack::clone) + .toArray(ItemStack[]::new); + + this.kitManager.addToCache(new Kit(itemStacks, cooldownInMs, gkit, weight, kitName)); + this.kitManager.saveAll(); + + this.kitManager.purge(); + + Language.ADMINKIT_CREATED.send(sender); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/BlessCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/BlessCommand.java new file mode 100644 index 0000000..710f04a --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/BlessCommand.java @@ -0,0 +1,34 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Optional; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("bless") +public class BlessCommand extends CommandBase { + + private final CrankedCore plugin; + public BlessCommand(CrankedCore plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender, @Optional Player player) { + if(player != null && player.isOnline() && !commandSender.hasPermission("bless.other")) { + Language.NO_PERMISSION.send(commandSender); + return; + } + + player = (Player) commandSender; + + PotionEffectUtils.bless(player); + Language.BLESS.send(player); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/BlockCommandCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/BlockCommandCommand.java new file mode 100644 index 0000000..707ced8 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/BlockCommandCommand.java @@ -0,0 +1,59 @@ +package net.crankedpvp.crankedcore.commands; + +import net.crankedpvp.crankedutils.utils.CC; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.managers.CommandBlockerManager; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("blockedcommand") +@Alias("blockcommand") +public class BlockCommandCommand extends CommandBase { + private CrankedCore plugin; + private CommandBlockerManager commandBlockerManager; + + public BlockCommandCommand(CrankedCore plugin) { + this.plugin = plugin; + this.commandBlockerManager = plugin.getCommandBlockerManager(); + } + @Default + @Permission("cranked.admin") + public void onDefault(CommandSender sender) { + Player player = (Player) sender; + player.sendMessage(CC.translate("&c&lBlockedCommand Commands")); + player.sendMessage(CC.translate("&c/blockedcommand add ")); + player.sendMessage(CC.translate("&c/blockedcommand remove ")); + player.sendMessage(CC.translate("&c/blockedcommand list")); + } + + @SubCommand("add") + @Permission("cranked.admin") + public void addCommand(CommandSender sender, String command) { + Player player = (Player) sender; + commandBlockerManager.blockCommand(player, command); + commandBlockerManager.saveCommands(plugin); + + } + + @SubCommand("remove") + @Permission("cranked.admin") + public void removeCommand(CommandSender sender, String command) { + Player player = (Player) sender; + commandBlockerManager.unBlockCommand(player, command); + commandBlockerManager.saveCommands(plugin); + } + + @SubCommand("list") + @Permission("cranked.admin") + public void listCommand(CommandSender sender) { + Player player = (Player) sender; + player.sendMessage(CC.translate("&c&lBlocked Commands List:")); + for (String cmd : commandBlockerManager.getBlockedCommands()) { + player.sendMessage(CC.Red + "/" + cmd); + } + player.sendMessage(CC.translate("&c ")); + + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/BroadcastCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/BroadcastCommand.java new file mode 100644 index 0000000..9bf1634 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/BroadcastCommand.java @@ -0,0 +1,24 @@ +package net.crankedpvp.crankedcore.commands; + +import net.crankedpvp.crankedutils.utils.CC; +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; + +@Command("cbc") +@Alias({"abc"}) +public class BroadcastCommand extends CommandBase { + + @Default + @Permission("cranked.admin") + public void broadcastCommand(final CommandSender commandSender, String[] messages) { + Bukkit.broadcastMessage(""); + Bukkit.broadcastMessage(CC.translate("&c&lAlert &8➥ &c" + String.join(" ", messages))); + Bukkit.broadcastMessage(""); + + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/ChatColorCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ChatColorCommand.java new file mode 100644 index 0000000..0917ad2 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ChatColorCommand.java @@ -0,0 +1,37 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedcore.data.CrankedUserManager; +import net.crankedpvp.crankedcore.guis.ChatColorGUI; +import net.crankedpvp.crankedcore.language.Language; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("chatcolor") +public class ChatColorCommand extends CommandBase { + private final CrankedUserManager crankedUserManager; + private final CrankedCore plugin; + + public ChatColorCommand(CrankedCore plugin) { + this.plugin = plugin; + this.crankedUserManager = plugin.getCrankedUserManager(); + } + + @Default + public void defaultCommand(CommandSender sender) { + Player player = (Player) sender; + if(!player.hasPermission("astrocore.chatcolor")) { + Language.NO_PERMISSION.send(sender); + return; + } + + CrankedUser crankedUser = crankedUserManager.getCrankedUser(player.getUniqueId()); + ChatColorGUI chatColorGUI = new ChatColorGUI(crankedUser); + chatColorGUI.getChatColorGUI().open(player); + + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/CheckNBTCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/CheckNBTCommand.java new file mode 100644 index 0000000..252b8ed --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/CheckNBTCommand.java @@ -0,0 +1,78 @@ +package net.crankedpvp.crankedcore.commands; + +import de.tr7zw.nbtapi.NBTItem; +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Objects; +import java.util.StringJoiner; + +@Command("checknbt") +@Alias({"nbtcheck", "printnbt"}) +public class CheckNBTCommand extends CommandBase { + + @Default + @Permission("cranked.admin") + public void defaultCommand(final Player player) { + ItemStack itemStack = player.getItemInHand(); + if(ItemUtils.isAirOrNull(itemStack)) return; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return; + player.sendMessage(CC.translate("&dNBT Tag Checker")); + for(String key : nbtItem.getKeys()) { + if(nbtItem.getCompound(key) != null) { + player.sendMessage(CC.translate(" &5* &fCompound: " + key)); + for(String key2 : nbtItem.getCompound(key).getKeys()) { + player.sendMessage(CC.translate(" &d➥ &fKey: " + key2 + " &8| &f" + getStringOfWhateverDataTypeTheNbtTagIs(nbtItem, key, key2))); + //nbtItem.getCompound(key).getString(key2))); + } + } + } + player.sendMessage(CC.translate(" &5* &fNo Compound Keys")); + for(String key : nbtItem.getKeys()) { + if(nbtItem.getCompound(key) != null) continue; + player.sendMessage(CC.translate(" &d➥ &fKey: " + key + " &8| &f" + getStringOfWhateverDataTypeTheNbtTagIs(nbtItem, null, key))); + //nbtItem.getString(key))); + } + } + + private String getStringOfWhateverDataTypeTheNbtTagIs(NBTItem nbtItem, String compoundKey, String key) { + if(compoundKey == null) { + if(!nbtItem.hasKey(key)) return ""; + if(nbtItem.getString(key) != null && !Objects.equals(nbtItem.getString(key), "")) return "String: " + nbtItem.getString(key); + if(nbtItem.getBoolean(key) != null && (nbtItem.getBoolean(key) == Boolean.TRUE || nbtItem.getBoolean(key) == Boolean.FALSE)) return "Boolean:" + nbtItem.getBoolean(key); + if(nbtItem.getInteger(key) != null) return "Integer:" + nbtItem.getInteger(key); + if(nbtItem.getFloat(key) != null && !Objects.equals(String.valueOf(nbtItem.getFloat(key)), "")) return "Float:" + nbtItem.getFloat(key); + if(nbtItem.getLong(key) != null && !Objects.equals(String.valueOf(nbtItem.getLong(key)), "")) return "Long:" + nbtItem.getLong(key); + if(nbtItem.getStringList(key) != null) { + StringJoiner stringJoiner = new StringJoiner(", "); + for(String s : nbtItem.getStringList(key)) { + stringJoiner.add(s); + } + return "String List: " + stringJoiner; + } + } else { + if(!nbtItem.getCompound(compoundKey).hasKey(key)) return ""; + if(nbtItem.getCompound(compoundKey).getString(key) != null && !Objects.equals(nbtItem.getString(key), "")) return "String:" + nbtItem.getCompound(compoundKey).getString(key); + if(nbtItem.getCompound(compoundKey).getBoolean(key) != null && (nbtItem.getCompound(compoundKey).getBoolean(key) == Boolean.TRUE || nbtItem.getCompound(compoundKey).getBoolean(key) == Boolean.FALSE)) return "Boolean:" + nbtItem.getCompound(compoundKey).getBoolean(key); + if(nbtItem.getCompound(compoundKey).getInteger(key) != null) return "Integer:" + nbtItem.getCompound(compoundKey).getInteger(key); + if(nbtItem.getCompound(compoundKey).getFloat(key) != null) return "Float:" + nbtItem.getCompound(compoundKey).getFloat(key); + if(nbtItem.getCompound(compoundKey).getLong(key) != null) return "Long:" + nbtItem.getCompound(compoundKey).getLong(key); + if(nbtItem.getCompound(compoundKey).getStringList(key) != null) { + StringJoiner stringJoiner = new StringJoiner(", "); + for(String s : nbtItem.getCompound(compoundKey).getStringList(key)) { + stringJoiner.add(s); + } + return "String List: " + stringJoiner; + } + } + return ""; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/ClearInventoryCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ClearInventoryCommand.java new file mode 100644 index 0000000..1be3ea7 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ClearInventoryCommand.java @@ -0,0 +1,60 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +@Command("clearinventoryy") +@Alias("ci") +public class ClearInventoryCommand extends CommandBase { + + private final List playersAbleToConfirm; + private final CrankedCore plugin; + + public ClearInventoryCommand(CrankedCore plugin) { + this.plugin = plugin; + this.playersAbleToConfirm = new ArrayList<>(); + } + + @Default + public void defaultCommand(CommandSender commandSender, @Optional @Completion("#players") Player receiver) { + if(!(commandSender instanceof Player)) return; + + if(receiver != null && commandSender.hasPermission("ci.admin")) { + this.clear(receiver); + receiver.sendMessage(CC.translate("&a&l(!) &aYour inventory has been fully cleared")); + commandSender.sendMessage(CC.translate("&a&l(!) &aYou have cleared " + receiver.getName() + "'s inventory")); + return; + } + + Player player = (Player) commandSender; + if(this.plugin.getCrankedUserManager().getCrankedUser(player.getUniqueId()).isCiConfirmEnabled()) { + if(this.playersAbleToConfirm.contains(player)) { + player.sendMessage(CC.translate("&a&l(!) &aSuccessfully cleared all items from your inventory")); + this.clear(player); + this.playersAbleToConfirm.remove(player); + return; + } + this.playersAbleToConfirm.add(player); + player.sendMessage(CC.translate("&e&l(!) &eType &f/ci &eagain to confirm that you want to clear your inventory")); + plugin.getServer().getScheduler().runTaskLater(plugin, () -> this.playersAbleToConfirm.remove(player), 20L * 5); + return; + } + player.sendMessage(CC.translate("&a&l(!) &aSuccessfully cleared all items from your inventory")); + this.clear(player); + + } + + private void clear(Player player) { + player.getInventory().clear(); + player.updateInventory(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/CrankedStatsCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/CrankedStatsCommand.java new file mode 100644 index 0000000..6e06497 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/CrankedStatsCommand.java @@ -0,0 +1,20 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.Statistic; +import org.bukkit.entity.Player; + +@Command("cstats") +public class CrankedStatsCommand extends CommandBase { + + @Default + @Permission("cranked.admin") + public void test(final Player player) { + for(Statistic value : Statistic.values()) { + player.sendMessage(value.name() + ": " + player.getStatistic(value)); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/CrystalCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/CrystalCommand.java new file mode 100644 index 0000000..1238cf1 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/CrystalCommand.java @@ -0,0 +1,32 @@ +package net.crankedpvp.crankedcore.commands; + +import net.crankedpvp.crankedutils.utils.CC; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.struct.crystals.CrystalItem; +import net.crankedpvp.crankedcore.struct.crystals.EnchantEnum; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("crystal") +public class CrystalCommand extends CommandBase { + + @Default + @WrongUsage("&cUsage: /crystal [player]") + @Permission("cranked.admin") + public void onCommand(CommandSender sender, @Completion("#enum") EnchantEnum enchant, @Completion("#range:1-9") Integer level, @Optional @Completion("#players") Player player) { + + if (level > enchant.getMaxLevel()) { + sender.sendMessage(CC.translate("&c&lWARNING &cyou redeemed a crystal above the max level")); + } + + if (player != null) { + player.getInventory().addItem(CrystalItem.createCrystal(enchant, level)); + return; + } + + if (sender instanceof Player) { + ((Player) sender).getInventory().addItem(CrystalItem.createCrystal(enchant, level)); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/DebugPlayerCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/DebugPlayerCommand.java new file mode 100644 index 0000000..91c080d --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/DebugPlayerCommand.java @@ -0,0 +1,63 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedarmor.struct.cache.ArmorSetCache; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.cache.CachedPlayer; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +@Command("debugplayer") +public class DebugPlayerCommand extends CommandBase { + + @Default() + @Permission("cranked.admin") + public void defaultCommand(Player sender, @Optional @Completion("#players") Player player) { + if (player == null) { + checkPlayer(sender, sender); + } else { + checkPlayer(player, sender); + } + } + + public void checkPlayer(Player toCheck, Player sender) { + CachedPlayer armorSetPlayer = CrankedUtils.getInstance().getCacheManager().getCachedPlayer(toCheck); + ArmorSetCache cache = (ArmorSetCache) (armorSetPlayer.hasCache("armor_set") ? armorSetPlayer.getCache("armor_set") : armorSetPlayer.registerCache(new ArmorSetCache(toCheck))); + sender.sendMessage(CC.translate("&8----------------------------")); + String set = cache.getCurrentArmorSet().getName() != null ? cache.getCurrentArmorSet().getName() : "none"; + sender.sendMessage(CC.translate("&dSet Information: &f" + set)); + for (Map.Entry entry : cache.getArmorSets().entrySet()) { + sender.sendMessage(CC.translate("&d * &f" + entry.getKey().getName() + " &8: &7" + entry.getValue())); + } + + if(StarItemsAPI.playerHasStarItemInCache(toCheck)) { + sender.sendMessage(CC.translate("&cStar Items")); + for(StarItem starItem : StarItemsAPI.getStarItemFromCache(toCheck)) { + sender.sendMessage(CC.translate(" &c* &f" + starItem.getName())); + } + } + + ItemStack helmet = toCheck.getInventory().getHelmet(); + if(helmet != null && helmet.getType() != Material.AIR) { + if(CrankedMasksAPI.itemHasMaskEquipped(helmet)) { + sender.sendMessage(CC.translate("&bMask: &f" + Objects.requireNonNull(CrankedMasksAPI.getMasksOnItem(helmet)).stream().map(Mask::getName).collect(Collectors.joining(", ")))); + } + } + + + sender.sendMessage(CC.translate("&8----------------------------")); + + } +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/DiscordCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/DiscordCommand.java new file mode 100644 index 0000000..7d684e6 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/DiscordCommand.java @@ -0,0 +1,23 @@ +package net.crankedpvp.crankedcore.commands; + +import net.crankedpvp.crankedutils.utils.CC; +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.command.CommandSender; + +@Command("discord") +@Alias({"discordlink", "disc"}) +public class DiscordCommand extends CommandBase { + + @Default + public void discordCommand(final CommandSender sender) { + sender.sendMessage(""); + sender.sendMessage(CC.translate("&c&lCranked&f&lPvP &c&lDiscord")); + sender.sendMessage(CC.translate("&f&ndiscord.gg/crankedpvp")); + sender.sendMessage(CC.translate("&7Click to join the CrankedPvP Discord!")); + sender.sendMessage(""); + + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/ExpBottleCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ExpBottleCommand.java new file mode 100644 index 0000000..2688e90 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ExpBottleCommand.java @@ -0,0 +1,81 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.utils.ExpBottleAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.XPUtils; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("xpbottle") +@Alias("expbottle") +public class ExpBottleCommand extends CommandBase { + private final int MAX_WITHDRAW = 10000000; + private final int MIN_WITHDRAW = 25; + + @Default + public void onDefault(CommandSender sender, @Optional String amount) { + Player p = (Player) sender; + if (amount == null) { + for (String line : Language.EXP_BOTTLE_HELP.getValuesAsList()) { + p.sendMessage(CC.translate(line)); + } + return; + } + if (amount.contains(".") || amount.contains(",")) { + Language.WITHDRAW_DECIMAL.send(p); + return; + } + + int amountInt; + try { + amountInt = Integer.parseInt(amount); + } catch (NumberFormatException e) { + amountInt = (int) NumberUtils.getValueFromFormat(amount); + + } + + + + + withdrawExp(p, amountInt); + + + } + + + @SubCommand("all") + public void onExpBottleString(CommandSender sender) { + Player p = (Player) sender; + int amount = p.getTotalExperience(); + withdrawExp(p, amount); + } + + + public void withdrawExp(Player p, int amount) { + if (amount < MIN_WITHDRAW) { + p.sendMessage(ChatColor.RED + "You must withdraw at least " + NumberUtils.formatMoney(MIN_WITHDRAW) + " XP points per bottle."); + return; + } + if (amount > MAX_WITHDRAW) { + p.sendMessage(ChatColor.RED + "You can only withdraw a max of " + NumberUtils.formatMoney(MAX_WITHDRAW) + " XP points per bottle."); + return; + } + + float currentXp = p.getTotalExperience(); + if (currentXp < amount) { + Language.EXP_BOTTLE_NOT_ENOUGH.send(p); + return; + } + XPUtils.removeExperience(p, amount); + p.sendMessage(CC.translate(Language.EXP_BOTTLE_WITHDRAW.getMessage().replace("%amount%", NumberUtils.formatMoney(amount)))); + p.playSound(p.getLocation(), Sound.ORB_PICKUP, 1.0f, 0.2f); + PlayerUtils.giveOrDropProtectedItem(p, ExpBottleAPI.getXpBottle(amount, p), 60); + } +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/FixCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/FixCommand.java new file mode 100644 index 0000000..7f9b851 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/FixCommand.java @@ -0,0 +1,87 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@Command("fix") +@Alias("repair") +public class FixCommand extends CommandBase { + + private final CrankedCore plugin; + public FixCommand(CrankedCore plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + runFixCode(player); + } + + @SubCommand("hand") + public void handCommand(final Player player) { + runFixCode(player); + } + + @SubCommand("all") + @Permission("cranked.fix.all") + public void allCommand(final Player player) { + if(player == null) return; + + List items = new ArrayList<>(); + items.addAll(Arrays.asList(player.getInventory().getContents())); + items.addAll(Arrays.asList(player.getInventory().getArmorContents())); + + for(ItemStack item : items) { + if(ItemUtils.isAirOrNull(item)) continue; + if(!isDamageable(item.getType())) continue; + item.setDurability((short) 0); + } + + player.playSound(player.getLocation(), Sound.LEVEL_UP, 2.0f, 1.0f); + player.sendMessage(CC.translate("&c&lFix &8" + Arrow.arrow() + " &7All items in your inventory have been repaired")); + } + + private void runFixCode(Player player) { + if(player == null) return; + + ItemStack itemStack = player.getItemInHand(); + if(ItemUtils.isAirOrNull(itemStack)) { + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 1.0f); + player.sendMessage(CC.translate("&c&lFix &8" + Arrow.arrow() + " &7You must be holding an item to fix")); + return; + } + + if(!isDamageable(itemStack.getType())) { + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 1.0f); + player.sendMessage(CC.translate("&c&lFix &8" + Arrow.arrow() + " &7You cannot fix an item that cannot take damage")); + return; + } + + if(StarItemsAPI.isGoldenKnife(itemStack)) { + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 1.0f); + player.sendMessage(CC.translate("&c&lFix &8" + Arrow.arrow() + " &7You cannot repair the &6&lGolden Knife")); + return; + } + + itemStack.setDurability((short) 0); + player.playSound(player.getLocation(), Sound.LEVEL_UP, 2.0f, 1.0f); + player.sendMessage(CC.translate("&c&lFix &8" + Arrow.arrow() + " &7Your item has been successfully repaired")); + } + + private boolean isDamageable(Material material) { + return material.getMaxDurability() > 0; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiftCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiftCommand.java new file mode 100644 index 0000000..3ce55af --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiftCommand.java @@ -0,0 +1,54 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Completion; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.WrongUsage; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedcore.data.CrankedUserManager; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.Player; + +@Command("gift") +public class GiftCommand extends CommandBase { + + private final CrankedUserManager crankedUserManager; + + public GiftCommand(CrankedCore plugin) { + this.crankedUserManager = plugin.getCrankedUserManager(); + } + + @Default + @WrongUsage("&c/gift ") + public void giftToPlayer(Player sender, @Completion("#players") Player receiver, String[] message) { + if (sender.equals(receiver)) { + Language.GIFT_URSELF.send(sender); + return; + } + + if (ItemUtils.isAirOrNull(sender.getItemInHand())) { + Language.CANNOT_HAVE_EMPTY_HAND.send(sender); + return; + } + + CrankedUser crankedUser = this.crankedUserManager.getCrankedUser(receiver.getUniqueId()); + if (crankedUser == null) { + sender.sendMessage(CC.Red + "Please enter a valid online player!"); + return; + } + + if (crankedUser.alreadyHasOver5GiftsFromPlayer(sender)) { + Language.ALREADY_HAS_GIFT.send(sender); + return; + } + + crankedUser.addGift(sender, sender.getItemInHand(), message); + crankedUser.getPlayer().sendMessage(CC.translate(Language.RECEIVED_GIFT.getMessage().replace("{sender}", sender.getName()))); + sender.sendMessage(CC.translate(Language.SENT_GIFT.getMessage().replace("{receiver}", crankedUser.getPlayer().getName()))); + sender.setItemInHand(null); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiftsCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiftsCommand.java new file mode 100644 index 0000000..6ed6b3e --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiftsCommand.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUserManager; +import net.crankedpvp.crankedcore.guis.GiftsGUI; +import org.bukkit.entity.Player; + +@Command("gifts") +public class GiftsCommand extends CommandBase { + + @Default + public void showGifts(Player sender) { + GiftsGUI giftsGui = new GiftsGUI(sender); + giftsGui.getGui().open(sender); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiveAwayCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiveAwayCommand.java new file mode 100644 index 0000000..2d8d95e --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiveAwayCommand.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("giveaway") +@Alias({"ga", "giveaways"}) +public class GiveAwayCommand extends CommandBase { + @Default + public boolean onDefault(CommandSender sender) { + Player player = (Player) sender; + player.sendMessage(CC.translate("")); + player.sendMessage(CC.translate("&b&lCranked Giveaways")); + player.sendMessage(CC.translate("&b&l* &f/giveaway join &b- &7Join an active giveaway")); + + + if (sender.hasPermission("cranked.giveaway")) { + player.sendMessage(CC.translate("&b&l* &f/giveaway start &b- &7Start a giveaway")); + player.sendMessage(CC.translate("&b&l* &f/giveaway cancel &b- &7Cancel a giveaway")); + } + player.sendMessage(CC.translate("")); + return true; + } + + @SubCommand("join") + public void onCmdJoin(CommandSender sender) { + CrankedCore.getInstance().getGiveAwayManager().joinGiveAway((Player) sender); + } + + @SubCommand("start") + @Permission("cranked.giveaway") + public void onGaStart(CommandSender sender, Integer winners, Integer timeInS) { + CrankedCore.getInstance().getGiveAwayManager().startGiveAway((Player) sender, winners, ((Player) sender).getItemInHand(), timeInS); + + } + + @SubCommand("cancel") + @Permission("cranked.giveaway") + public void onGaCancel(CommandSender sender) { + CrankedCore.getInstance().getGiveAwayManager().cancelGiveAway((Player) sender); + } + + @SubCommand("addfakejoins") + @Permission("cranked.admin") + public void addFakeJoinsCommand(final CommandSender commandSender, Integer amount) { + CrankedCore.getInstance().getGiveAwayManager().addFakeJoins(amount); + } + + +} + diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiveallCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiveallCommand.java new file mode 100644 index 0000000..6eb2c28 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GiveallCommand.java @@ -0,0 +1,66 @@ +package net.crankedpvp.crankedcore.commands; + +import net.crankedpvp.crankedutils.utils.CC; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Optional; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import org.apache.commons.lang.WordUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +@Command("giveall") +public class GiveallCommand extends CommandBase { + + + @Permission("cranked.admin") + @Default + public void onCommand(CommandSender sender, @Optional Integer altLimit) { + Player player = (Player)sender; + if (altLimit == null) { + player.sendMessage(CC.translate("&c&lGiveall Commands")); + player.sendMessage(CC.translate("&c/giveall [Max Alts] &7- &fPut 0 for no alts allowed")); + return; + } + + if (player.getItemInHand() == null || player.getItemInHand().getType() == Material.AIR) { + player.sendMessage(CC.translate("&c&l(!) &cYou must be holding an item to give all.")); + } + + final ItemStack itemToGive = player.getItemInHand().clone(); + final Map ipMap = new HashMap<>(); + int given = 0; + String displayName = itemToGive.hasItemMeta() ? itemToGive.getItemMeta().getDisplayName() : null; + if (displayName == null) { + displayName = WordUtils.capitalizeFully(itemToGive.getType().name().replace("_", " ")); + } + for (final Player p : Bukkit.getOnlinePlayers()) { + if (p.getUniqueId().toString().equals(player.getUniqueId().toString())) { + continue; + } + final String ip = p.getAddress().getAddress().toString(); + if (ipMap.containsKey(ip) && ipMap.get(ip) > altLimit) { + continue; + } + + String msg = Language.GIVEALL_RECEIVED.getMessage(); + msg = msg.replace("%item%", displayName); + msg = msg.replace("%amount%", Integer.toString(itemToGive.getAmount())); + p.sendMessage(CC.translate(msg)); + + PlayerUtils.giveOrDropProtectedItem(p, itemToGive, 60); + given++; + ipMap.put(ip, ipMap.getOrDefault(ip, 0) + 1); + } + player.sendMessage(CC.translate("&a&l(!) &aSuccessfully gave all " + displayName + "&a to &f" + given + " &aplayers!")); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/GodsetCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GodsetCommand.java new file mode 100644 index 0000000..2a2bb33 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/GodsetCommand.java @@ -0,0 +1,73 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.struct.items.SoulTrackerBuilder; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GodsetUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.apache.commons.codec.language.bm.Lang; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Command("godset") +@Alias("quickenchant") +public class GodsetCommand extends CommandBase { + + private final CrankedCore plugin; + private final EnchantRegister enchantRegister; + + public GodsetCommand(CrankedCore plugin) { + this.plugin = plugin; + this.enchantRegister = CrankedEnchants.getInstance().getEnchantRegister(); + } + + + @Default + @Permission("cranked.admin") + public void defaultCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + + ItemStack itemStack = player.getItemInHand(); + + if(!ItemUtils.isArmor(itemStack) && !ItemUtils.isWeapon(itemStack)) { + player.sendMessage(CC.translate("&cThis is not an armor piece or a weapon")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(player.getItemInHand()); + + for(String enchantName : GodsetUtils.enchantments.get(itemStack.getType().name().split("_")[1].toLowerCase())) { + Enchantment enchantment = this.enchantRegister.getEnchantmentFromID(enchantName); + enchantedItemBuilder.addEnchantment(enchantment, enchantment.getMax()); + } + + enchantedItemBuilder.sortEnchantLore(); + enchantedItemBuilder.setProtected(true); + + Language.GODSET_SUCCESS.send(player); + player.getInventory().setItemInHand(enchantedItemBuilder.build()); + player.playSound(player.getLocation(), Sound.VILLAGER_YES, 2.0F, 2.0F); + + } +} + + + + diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/HealCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/HealCommand.java new file mode 100644 index 0000000..291c595 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/HealCommand.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedcore.commands; + +import net.crankedpvp.crankedutils.utils.CC; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.struct.cooldowns.HealCooldown; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("heal") +@Alias("eheal") +public class HealCommand extends CommandBase { + + @Default + public void healOther(CommandSender sender) { + Player player = (Player) sender; + int cooldown = Integer.parseInt(Language.heal_cooldown.getValue()); + if (CooldownUtils.isCooldownActive(player, "healCooldown")) { + player.sendMessage(CC.translate(Language.HEAL_COOLDOWN.getMessage().replace("%left%", CooldownUtils.getFormattedCooldown(player, "healCooldown")))); + return; + } + player.setHealth(player.getMaxHealth()); + Language.HEALED.send(player); + CooldownUtils.registerCooldown(player, new HealCooldown("healCooldown", cooldown)); + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/IceWandCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/IceWandCommand.java new file mode 100644 index 0000000..19371c9 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/IceWandCommand.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.items.IceWandItem; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("icewand") +public class IceWandCommand extends CommandBase { + + @Default + @WrongUsage("&cUsage: /icewand [player]") + @Permission("cranked.admin") + public void onCommand(CommandSender sender, Integer radius, Integer uses, @Completion("#players") @Optional Player player) { + if (player != null) { + player.getInventory().addItem(IceWandItem.createItem(radius, uses)); + return; + } + + if (sender instanceof Player) { + ((Player) sender).getInventory().addItem(IceWandItem.createItem(radius, uses)); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/InvseeCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/InvseeCommand.java new file mode 100644 index 0000000..b824c1e --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/InvseeCommand.java @@ -0,0 +1,44 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Completion; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.WrongUsage; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.guis.InvseeGUI; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +@Command("invsee") +public class InvseeCommand extends CommandBase { + + private final CrankedCore plugin; + public InvseeCommand(CrankedCore plugin) { + this.plugin = plugin; + } + + @Default + @WrongUsage("&c/invsee ") + public void defaultCommand(Player sender, @Completion("#players") Player player) { + if (player == null) return; + + if(player.getName().equals(sender.getName())) { + Language.CANNOT_INVSEE_YOURSELF.send(sender); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if (CrankedMasksAPI.hasMaskEquipped(player, CrankedMasks.getInstance().getMasksRegister().getMaskFromID("ghost")) && !player.hasPermission("cranked.admin")) { + Language.CANNOT_INVSEE_GHOST_MASK.send(sender); + return; + } + + InvseeGUI invseeGUI = new InvseeGUI(sender, player); + invseeGUI.getGui().open(sender); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/KitCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/KitCommand.java new file mode 100644 index 0000000..e35e549 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/KitCommand.java @@ -0,0 +1,48 @@ +package net.crankedpvp.crankedcore.commands; + +import net.crankedpvp.crankedutils.utils.CC; +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Optional; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedcore.guis.GlobalKitsGUI; +import net.crankedpvp.crankedcore.struct.kits.Kit; +import org.bukkit.entity.Player; + +@Command("kit") +@Alias({"ekit", "kits", "ekits", "gkit"}) +public class KitCommand extends CommandBase { + @Default + public void defaultCommand(final Player player, @Optional String kitName) { + if(kitName == null) { + GlobalKitsGUI globalKitsGUI = new GlobalKitsGUI(player); + globalKitsGUI.getGui().open(player); + return; + } + + Kit kit = CrankedCore.getInstance().getKitManager().getFromCache(kitName); + if(kit == null) { + player.sendMessage(CC.translate("&cThat is not a valid kit name")); + return; + } + + if(!kit.hasAccess(player)) { + player.sendMessage(CC.translate("&cYou do not have permission to access this kit")); + return; + } + + CrankedUser crankedUser = CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(player.getUniqueId()); + + if(crankedUser.hasCooldownOnKit(kit)) { + player.sendMessage(CC.translate("&cYou are currently on coolkdown for this kit")); + return; + } + + crankedUser.newCooldownOnKit(kit); + kit.supplyKit(player); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/LFFCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/LFFCommand.java new file mode 100644 index 0000000..cf06470 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/LFFCommand.java @@ -0,0 +1,26 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.cooldowns.LFFCooldown; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +@Command("lff") +@Alias("lookingforfaction") +public class LFFCommand extends CommandBase { + @Default + public void onCommand(Player player) { + if (CooldownUtils.isCooldownActive(player, "lff")) { + player.sendMessage(CC.translate( Language.LOOKING_FOR_FACTION_COOLDOWN.getMessage().replace("%time%", CooldownUtils.getFormattedCooldown(player, "lff")))); + return; + } + CooldownUtils.registerCooldown(player, new LFFCooldown("lff", 60)); + Bukkit.broadcastMessage( Language.LOOKING_FOR_FACTION.getMessage().replace("%player_displayname%", player.getDisplayName())); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/ListCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ListCommand.java new file mode 100644 index 0000000..8397876 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ListCommand.java @@ -0,0 +1,21 @@ +package net.crankedpvp.crankedcore.commands; + + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +@Command("list") +@Alias({"elist", "playerlist", "plist"}) +public class ListCommand extends CommandBase { + @Default + public void onDefault(Player p) { + p.sendMessage(""); + p.sendMessage(CC.translate("&c&lCranked&f&lPvP List &7[" + Bukkit.getOnlinePlayers().size() + "&7 Online]")); + p.sendMessage(""); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/LoreCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/LoreCommand.java new file mode 100644 index 0000000..17c86cb --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/LoreCommand.java @@ -0,0 +1,59 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +@Command("lore") +public class LoreCommand extends CommandBase { + + @Default + @Permission("cranked.admin") + public void defaultCommand(final CommandSender commandSender) { + commandSender.sendMessage(CC.Red + "/lore add (text)"); + commandSender.sendMessage(CC.Red + "/lore delete "); + } + + @Permission("cranked.admin") + @SubCommand("add") + public void addLine(CommandSender commandSender, String[] text) { + Player player = (Player) commandSender; + if(player.getItemInHand() == null || player.getItemInHand().getType() == Material.AIR) { + player.sendMessage(CC.Red + "Please hold an item"); + return; + } + ItemBuilder itemBuilder = new ItemBuilder(player.getItemInHand()); + List listOfStrings = Arrays.stream(text).collect(Collectors.toList()); + listOfStrings.remove(0); + itemBuilder.addLore(String.join(" ", listOfStrings)); + player.setItemInHand(itemBuilder.colorize().build()); + player.updateInventory(); + player.sendMessage(CC.translate("&aSuccessfully &nadded&a lore line to your item")); + } + + @Permission("cranked.admin") + @SubCommand("delete") + public void deleteLore(CommandSender commandSender, @Optional Integer line) { + Player player = (Player) commandSender; + if(player.getItemInHand() == null || player.getItemInHand().getType() == Material.AIR) { + player.sendMessage(CC.Red + "Please hold an item"); + return; + } + line = line == null ? ((Player) commandSender).getItemInHand().getItemMeta().getLore().size()-1 : line - 1; + ItemBuilder itemBuilder = new ItemBuilder(player.getItemInHand()); + itemBuilder.removeLoreLine(line); + player.setItemInHand(itemBuilder.colorize().build()); + player.updateInventory(); + player.sendMessage(CC.translate("&aSuccessfully &nremoved&a lore line from your item")); + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/MagicalLavaBucketCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/MagicalLavaBucketCommand.java new file mode 100644 index 0000000..7c13bd5 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/MagicalLavaBucketCommand.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.items.MagicalLavaBucketItem; +import net.crankedpvp.crankedcore.items.MagicalWaterBucketItem; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("mlb") +@Alias("magicallavabucket") +public class MagicalLavaBucketCommand extends CommandBase { + + @Default + @WrongUsage("&cUsage: /mlb [player]") + @Permission("cranked.admin") + public void onCommand(CommandSender sender, Integer uses, @Completion("#players") @Optional Player player) { + if (player != null) { + player.getInventory().addItem(MagicalLavaBucketItem.createMagicalLavaBucket(uses)); + return; + } + + if (sender instanceof Player) { + ((Player) sender).getInventory().addItem(MagicalLavaBucketItem.createMagicalLavaBucket(uses)); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/MagicalWaterBucketCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/MagicalWaterBucketCommand.java new file mode 100644 index 0000000..001f5f4 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/MagicalWaterBucketCommand.java @@ -0,0 +1,28 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.items.IceWandItem; +import net.crankedpvp.crankedcore.items.MagicalLavaBucketItem; +import net.crankedpvp.crankedcore.items.MagicalWaterBucketItem; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("mwb") +@Alias("magicalwaterbucket") +public class MagicalWaterBucketCommand extends CommandBase { + + @Default + @WrongUsage("&cUsage: /mwb [player]") + @Permission("cranked.admin") + public void onCommand(CommandSender sender, Integer uses, @Completion("#players") @Optional Player player) { + if (player != null) { + player.getInventory().addItem(MagicalWaterBucketItem.createMagicalWaterBucket(uses)); + return; + } + + if (sender instanceof Player) { + ((Player) sender).getInventory().addItem(MagicalWaterBucketItem.createMagicalWaterBucket(uses)); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/MoreCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/MoreCommand.java new file mode 100644 index 0000000..601dc6a --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/MoreCommand.java @@ -0,0 +1,63 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Collections; +import java.util.List; + +@Command("more") +public class MoreCommand extends CommandBase { + + private final CrankedCore plugin; + public MoreCommand(CrankedCore plugin) { + this.plugin = plugin; + } + @Default + @Permission("cranked.admin") + public void defaultCommand(final Player player) { + ItemStack itemStack = player.getItemInHand(); + + if(ItemUtils.isAirOrNull(itemStack)) return; + player.getItemInHand().setAmount(64); + + + this.log(player, itemStack); + } + + @SubCommand("logs") + @Permission("*") + public void logsCommand(final CommandSender commandSender) { + System.out.print("/more logs"); + for (String logs : this.plugin.getConfig().getStringList("logs")) { + System.out.println(CC.translate(logs)); + } + } + + private void log(Player player, ItemStack itemStack) { + if(!itemStack.hasItemMeta()) return; + + if(!this.plugin.getConfig().contains("logs") || this.plugin.getConfig().getStringList("logs").isEmpty()) { + this.plugin.getConfig().set("logs", Collections.singletonList("&c " + player.getName() + " &f=>&r " + ChatColor.stripColor(itemStack.getItemMeta().getDisplayName()))); + this.plugin.saveConfig(); + return; + } + + List logs = this.plugin.getConfig().getStringList("logs"); + logs.add("&c " + player.getName() + " &f=>&r " + ChatColor.stripColor(itemStack.getItemMeta().getDisplayName())); + + this.plugin.getConfig().set("logs", logs); + this.plugin.saveConfig(); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/NearCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/NearCommand.java new file mode 100644 index 0000000..31a1c50 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/NearCommand.java @@ -0,0 +1,75 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.SortUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Command("near") +public class NearCommand extends CommandBase { + + private final CrankedCore plugin; + + public NearCommand(CrankedCore plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final CommandSender commandSender) { + if (!(commandSender instanceof Player)) return; + Player sender = (Player) commandSender; + + Map nearbyPlayers = new HashMap<>(); + sender.getNearbyEntities(200, 200, 200) + .stream() + .filter(entity -> entity instanceof Player) + .filter(entity -> !CrankedMasksAPI.hasMaskEquipped((Player) entity, CrankedMasks.getInstance().getMasksRegister().getMaskFromID("ghost"))) + .filter(entity -> !entity.hasMetadata("NPC")) + .map(entity -> (Player) entity) + .filter(player -> !EssentialsUtils.getEssentials().getUser(player).isVanished()) + .forEach(nearbyPlayer -> nearbyPlayers.put(nearbyPlayer, sender.getLocation().distance(nearbyPlayer.getLocation()))); + + Map effectiveFinalNearbyPlayers = SortUtils.sort(nearbyPlayers); + if (effectiveFinalNearbyPlayers.size() > 30) { + Language.NEAR_TOO_MANY_PLAYERS.send(commandSender); + return; + } + + List playersAndDistances = effectiveFinalNearbyPlayers + .entrySet() + .stream() + .map(this::getStringByRadius) + .collect(Collectors.toList()); + + Collections.reverse(playersAndDistances); + + String nearbyString = String.join(", ", playersAndDistances); + commandSender.sendMessage(CC.translate("&c&l(!)&c Nearby Players: " + nearbyString)); + + } + + private String getStringByRadius(Map.Entry entry) { + String name = "&e" + entry.getKey().getName(); + String color = "&f"; + if (entry.getValue() < 150) color = "&e"; + if (entry.getValue() < 100) color = "&c"; + if (entry.getValue() < 50) color = "&4"; + String distance = "&f(" + color + NumberUtils.formatNum(entry.getValue()) + "m&f)"; + return name + distance; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/NetherPvPCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/NetherPvPCommand.java new file mode 100644 index 0000000..577b81c --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/NetherPvPCommand.java @@ -0,0 +1,67 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.guis.NetherPvPGUI; +import net.crankedpvp.crankedcore.struct.netherpvp.NetherPvPQueueManager; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("netherpvp") +public class NetherPvPCommand extends CommandBase { + + private final CrankedCore plugin; + private final NetherPvPQueueManager netherPvPQueueManager; + + public NetherPvPCommand(CrankedCore plugin) { + this.plugin = plugin; + this.netherPvPQueueManager = plugin.getNetherPvPQueueManager(); + } + + @Default + public void netherPvP(Player sender) { + NetherPvPGUI netherPvPGUI = new NetherPvPGUI(); + netherPvPGUI.getGui().open(sender); + } + + @SubCommand("leave") + public void leaveNetherPvP(Player sender) { + if (this.netherPvPQueueManager.isPlayerInPvPQueue(sender)) { + this.netherPvPQueueManager.removePlayerFromPvpQueue(sender); + sender.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You have &cremoved&7 your NetherPvP match")); + } + + if (this.netherPvPQueueManager.isPlayerInArena(sender)) { + Player oposingPlayer = this.netherPvPQueueManager.getOposingPlayer(sender); + if (oposingPlayer == null) { + System.out.println("something went wrong in netherpvp"); + return; + } + this.netherPvPQueueManager.endMatch(oposingPlayer, sender); + } + } + + @SubCommand("resetqueue") + @Permission("cranked.admin") + public void resetQueue(CommandSender sender) { + this.netherPvPQueueManager.resetQueue(); + } + + @SubCommand("resetarena") + @Permission("cranked.admin") + public void resetArenaPlayers(CommandSender sender) { + this.netherPvPQueueManager.resetArena(); + } + + @SubCommand("cancelMatch") + @Permission("cranked.admin") + public void cancelMatch(CommandSender sender) { + this.netherPvPQueueManager.cancelMatch(); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/PotsCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/PotsCommand.java new file mode 100644 index 0000000..efa7842 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/PotsCommand.java @@ -0,0 +1,54 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.Potion; +import org.bukkit.potion.PotionType; + +import java.util.Arrays; +import java.util.Objects; + +@Command("pots") +@Alias({"potfill", "potions", "pot"}) +public class PotsCommand extends CommandBase { + + @Default + public void defaultCommand(final Player sender) { + + long potsToFill = 36 - Arrays.stream(sender.getInventory().getContents()) + .filter(Objects::nonNull) + .filter(itemStack -> itemStack.getType() != Material.AIR) + .count(); + + long price = potsToFill * 75; + if(!EconomyUtils.hasBalance(sender, price)) { + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + sender.sendMessage(CC.translate(Language.POTS_TOO_EXPENSIVE.getValue().replace("%amount%", String.valueOf(potsToFill)).replace("%price%", String.valueOf(price)))); + return; + } + + EconomyUtils.withdrawBalance(sender, price); + for(int i = 0; i < potsToFill; i++) { + sender.getInventory().addItem(getPotion()); + } + sender.sendMessage(CC.translate(Language.POTS_RECEIVED.getValue().replace("%amount%", String.valueOf(potsToFill)).replace("%price%", String.valueOf(price)))); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + private ItemStack getPotion() { + Potion splash = new Potion(PotionType.INSTANT_HEAL, 2); + splash.setSplash(true); + return splash.toItemStack(1); + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/ProxyPatchCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ProxyPatchCommand.java new file mode 100644 index 0000000..ba2dec9 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/ProxyPatchCommand.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.tasks.ProxyPatchTask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; + +@Command("proxypatch") +public class ProxyPatchCommand extends CommandBase { + + private CrankedCore plugin; + public ProxyPatchCommand(CrankedCore plugin) { + this.plugin = plugin; + } + + @SubCommand("end") + @Alias({"finish", "reset"}) + @Permission("cranked.admin") + public void endCommand(final CommandSender commandSender) { + this.plugin.getProxyPatchTask().end(); + } + + @SubCommand("start") + @Permission("cranked.admin") + public void startCommand(final CommandSender commandSender) { + this.plugin.setProxyPatchTask(new ProxyPatchTask()); + this.plugin.getProxyPatchTask().runTaskTimer(this.plugin, 60L, 20L); + commandSender.sendMessage(CC.translate("&aAttempting to fix proxy for: &f" + this.plugin.getProxyPatchTask().getPlayerNames().size() + " players")); + } + + @SubCommand("restart") + @Permission("cranked.admin") + public void restartCommand(final CommandSender commandSender) { + this.plugin.getProxyPatchTask().end(); + this.plugin.setProxyPatchTask(new ProxyPatchTask()); + this.plugin.getProxyPatchTask().runTaskTimer(this.plugin, 60L, 20L); + commandSender.sendMessage(CC.translate("&aAttempting to fix proxy for: &f" + this.plugin.getProxyPatchTask().getPlayerNames().size() + " players")); + } + + @SubCommand("stop") + @Alias("cancel") + @Permission("cranked.admin") + public void stopCommand(final CommandSender commandSender) { + this.plugin.getProxyPatchTask().cancel(); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/RainbowifyCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/RainbowifyCommand.java new file mode 100644 index 0000000..7785b5d --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/RainbowifyCommand.java @@ -0,0 +1,35 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("rainbowify") +@Alias("gayify") +public class RainbowifyCommand extends CommandBase { + + @Default + @Permission("cranked.admin") + public void defaultCommand(final Player player, String[] strings) { + + if(ItemUtils.isAirOrNull(player.getItemInHand())) return; + String finalString = String.join("_", strings); + finalString = finalString.replace("_", " "); + ItemBuilder itemBuilder = new ItemBuilder(player.getItemInHand()); + itemBuilder.setName(StringUtils.rainbowify(finalString)); + player.setItemInHand(itemBuilder.colorizeName().build()); + } + + @SubCommand("print") + @Permission("cranked.admin") + public void printCommand(final CommandSender commandSender, String[] strings) { + String finalString = String.join("_", strings); + finalString = finalString.replace("print", "").replace("_", " "); + System.out.println(ChatColor.stripColor(StringUtils.rainbowify(finalString))); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/RebootCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/RebootCommand.java new file mode 100644 index 0000000..94a7b87 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/RebootCommand.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedcore.commands; + +import net.crankedpvp.crankedutils.utils.CC; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.struct.reboot.Reboot; +import org.bukkit.command.CommandSender; + +@Command("reboot") +@Alias({"creboot", "shutdown"}) +public class RebootCommand extends CommandBase { + + private final CrankedCore plugin; + + public RebootCommand(CrankedCore plugin) { + this.plugin = plugin; + } + + @Default + @Permission("cranked.admin") + public void onCommand(CommandSender sender) { + sender.sendMessage(CC.translate("&cUsage: /reboot ")); + } + + @SubCommand("cancel") + @WrongUsage("&cUsage: /reboot cancel") + public void cancel(CommandSender sender) { + if (plugin.getReboot() == null) { + Language.REBOOT_NOT_SCHEDULED.send(sender); + } else { + plugin.getReboot().cancel(); + plugin.setReboot(null); + Language.REBOOT_CANCEL.send(sender); + } + } + + @SubCommand("start") + @WrongUsage("&cUsage: /reboot start ") + public void start(CommandSender sender, Integer seconds) { + if (plugin.getReboot() == null) { + plugin.setReboot(new Reboot(seconds)); + plugin.getReboot().runTaskTimer(plugin, 20L, 20L); + } else { + plugin.getReboot().setSecondsUntilShutdown(seconds); + } + Language.REBOOT_SCHEDULED.send(sender, str -> str.replace("%time%", String.valueOf(seconds))); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/RenameCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/RenameCommand.java new file mode 100644 index 0000000..7fcbb0a --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/RenameCommand.java @@ -0,0 +1,28 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("rename") +public class RenameCommand extends CommandBase { + + @Default + @Permission("cranked.admin") + public void defaultCommand(final CommandSender commandSender, final String[] text) { + Player player = (Player) commandSender; + if(player.getItemInHand() == null || player.getItemInHand().getType() == Material.AIR) return; + ItemBuilder itemBuilder = new ItemBuilder(player.getItemInHand()); + itemBuilder.setName(String.join(" ", text)); + player.setItemInHand(itemBuilder.colorize().build()); + player.updateInventory(); + player.sendMessage(CC.translate("&aSuccessfully renamed your item")); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/SandWandCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/SandWandCommand.java new file mode 100644 index 0000000..4466c11 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/SandWandCommand.java @@ -0,0 +1,26 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.items.IceWandItem; +import net.crankedpvp.crankedcore.items.SandWandItem; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("sandwand") +public class SandWandCommand extends CommandBase { + + @Default + @WrongUsage("&cUsage: /sandwand [player]") + @Permission("cranked.admin") + public void onCommand(CommandSender sender, Integer uses, @Completion("#players") @Optional Player player) { + if (player != null) { + player.getInventory().addItem(SandWandItem.createSandWand(uses)); + return; + } + + if (sender instanceof Player) { + ((Player) sender).getInventory().addItem(SandWandItem.createSandWand(uses)); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/SeeAllCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/SeeAllCommand.java new file mode 100644 index 0000000..eb0c0b5 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/SeeAllCommand.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +@Command("seeall") +public class SeeAllCommand extends CommandBase { + + @Default + @Permission("*") + public void seeAllCommand(Player player) { + List players = new ArrayList<>(Bukkit.getOnlinePlayers()); + for (Player player1 : players) { + for (Player player2 : players) { + player1.showPlayer(player2); + } + } + player.sendMessage("shown all"); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/SpawnerShopCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/SpawnerShopCommand.java new file mode 100644 index 0000000..2a9aed0 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/SpawnerShopCommand.java @@ -0,0 +1,31 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.WrongUsage; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.guis.SpawnerShopGUI; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +@Command("spawnershop") +@Alias("spawnersshop") +public class SpawnerShopCommand extends CommandBase { + @Default + @WrongUsage("&cUsage: /spawnershop ") + public void onDefault(Player player, Integer amount) { + if (amount == null || amount <= 0) { + player.sendMessage(CC.translate("&c&l(!)&c Please enter a valid amount!")); + return; + } + + if (amount > 100000) { + player.sendMessage(CC.translate("&c&l(!)&c Please enter an amount below 100,000!")); + return; + } + + SpawnerShopGUI spawnerShopGUI = new SpawnerShopGUI(amount); + spawnerShopGUI.getSpawnerGUI().open(player); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/StaffChatCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/StaffChatCommand.java new file mode 100644 index 0000000..b3f308d --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/StaffChatCommand.java @@ -0,0 +1,46 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.managers.StaffChatManager; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("staffchat") +@Alias("sc") +public class StaffChatCommand extends CommandBase { + private final CrankedCore plugin; + private final StaffChatManager staffChatManager; + public StaffChatCommand(CrankedCore plugin) { + this.plugin = plugin; + this.staffChatManager = plugin.getStaffChatManager(); + } + + @Default + @Permission("crankedcore.staffchat") + public void defaultCommand(CommandSender sender, @Optional String[] message) { + Player player = (Player) sender; + if (!sender.hasPermission("crankedcore.staffchat")) { + Language.NO_PERMISSION.send(sender); + return; + } + StringBuilder text = new StringBuilder(); + for (String arg : message) { + text.append(arg).append(" "); + } + if (text.toString().isEmpty()) { + if (staffChatManager.getInStaffChat().contains(player)) { + staffChatManager.getInStaffChat().remove(player); + Language.STAFF_CHAT_LEAVE.send(player); + } else { + staffChatManager.getInStaffChat().add(player); + Language.STAFF_CHAT_JOIN.send(player); + } + return; + } + staffChatManager.sendStaffMessage(player, text.toString()); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/commands/WithdrawCommand.java b/Core/src/main/java/net/crankedpvp/crankedcore/commands/WithdrawCommand.java new file mode 100644 index 0000000..6bef09f --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/commands/WithdrawCommand.java @@ -0,0 +1,77 @@ +package net.crankedpvp.crankedcore.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.utils.ExpBottleAPI; +import net.crankedpvp.crankedcore.utils.MoneyNotesAPI; +import net.crankedpvp.crankedutils.utils.*; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("withdraw") +@Alias({"w", "note", "banknote"}) +public class WithdrawCommand extends CommandBase { + private final int MAX_WITHDRAW = 1000000000; + private final int MIN_WITHDRAW = 10000; + + @Default + public void onDefault(CommandSender sender, @Optional String amount) { + Player p = (Player) sender; + if (amount == null) { + for (String line : Language.NOTE_HELP.getValuesAsList()) { + p.sendMessage(CC.translate(line)); + } + return; + } + if (amount.contains(".") || amount.contains(",")) { + Language.WITHDRAW_DECIMAL.send(p); + return; + } + + int amountInt; + try { + amountInt = Integer.parseInt(amount); + } catch (NumberFormatException e) { + amountInt = (int) NumberUtils.getValueFromFormat(amount); + + } + + + + withdrawMoney(p, amountInt); + + + } + + + @SubCommand("all") + public void onNoteString(CommandSender sender) { + Player p = (Player) sender; + int amount = (int) EconomyUtils.getBalance(p); + withdrawMoney(p, amount); + } + + + public void withdrawMoney(Player p, int amount) { + if (amount < MIN_WITHDRAW) { + p.sendMessage(ChatColor.RED + "You must withdraw at least $" + NumberUtils.formatMoney(MIN_WITHDRAW) + " per bank note."); + return; + } + if (amount > MAX_WITHDRAW) { + p.sendMessage(ChatColor.RED + "You can only withdraw a max of $" + NumberUtils.formatMoney(MAX_WITHDRAW) + " per bank note."); + return; + } + + if (!EconomyUtils.hasBalance(p, amount)) { + Language.NOTE_NOT_ENOUGH.send(p); + return; + } + EconomyUtils.withdrawBalance(p, amount); + p.sendMessage(CC.translate(Language.NOTE_WITHDRAW.getMessage().replace("%amount%", NumberUtils.formatMoney(amount)))); + p.playSound(p.getLocation(), Sound.ENDERDRAGON_WINGS, 1.0f, 0.1f); + PlayerUtils.giveOrDropProtectedItem(p, MoneyNotesAPI.getNote(amount, p), 60); + } +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/ChatCooldown.java b/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/ChatCooldown.java new file mode 100644 index 0000000..716c0dc --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/ChatCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedcore.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class ChatCooldown extends CurrentCooldown { + public ChatCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/EnderPearlCooldown.java b/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/EnderPearlCooldown.java new file mode 100644 index 0000000..b0cc712 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/EnderPearlCooldown.java @@ -0,0 +1,12 @@ +package net.crankedpvp.crankedcore.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class EnderPearlCooldown extends CurrentCooldown { + + public static final String ENDERPEARL_COOLDOWN_KEY = "enderpearl-cooldown"; + + public EnderPearlCooldown(int durationInSeconds) { + super(ENDERPEARL_COOLDOWN_KEY, durationInSeconds); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/LFFCooldown.java b/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/LFFCooldown.java new file mode 100644 index 0000000..d65c5d4 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/LFFCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedcore.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class LFFCooldown extends CurrentCooldown { + public LFFCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/LootProtectCooldown.java b/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/LootProtectCooldown.java new file mode 100644 index 0000000..2455e63 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/cooldowns/LootProtectCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedcore.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class LootProtectCooldown extends CurrentCooldown { + public LootProtectCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/data/CrankedUser.java b/Core/src/main/java/net/crankedpvp/crankedcore/data/CrankedUser.java new file mode 100644 index 0000000..3e2d258 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/data/CrankedUser.java @@ -0,0 +1,106 @@ +package net.crankedpvp.crankedcore.data; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedcore.struct.gifts.Gift; +import net.crankedpvp.crankedcore.struct.kits.Kit; +import net.crankedpvp.storageutils.utils.KeyToSave; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +@Getter +@Setter +public class CrankedUser implements KeyToSave { + + private ChatColor chatColor; + private boolean isLootTableMessageEnabled; + private boolean factionLandTitleEnabled; + private boolean killTitleEnabled; + private boolean isCombatTagTimerEnabled; + private boolean ciConfirmEnabled; + private boolean bossDeathMessagesEnabled; + private HashMap kitCooldownMap; + private List gifts; + private UUID uuid; + + + public CrankedUser(UUID uuid) { + this.chatColor = ChatColor.WHITE; + this.isCombatTagTimerEnabled = true; + this.killTitleEnabled = true; + this.kitCooldownMap = new HashMap<>(); + this.gifts = new ArrayList<>(); + this.uuid = uuid; + } + + public boolean alreadyHasOver5GiftsFromPlayer(Player sender) { + if (gifts == null) { + gifts = new ArrayList<>(); + } + int giftsAmount = 0; + for (Gift gift : gifts) { + if (gift.getSender() == sender.getUniqueId()) { + giftsAmount++; + } + } + return giftsAmount >= 5; + } + + public void addGift(Player sender, ItemStack itemStack, String[] message) { + this.getGifts().add(new Gift(sender, itemStack, Arrays.stream(message).reduce("", (firstString, secondString) -> firstString + " " + secondString))); + } + + public long getLastKitUsage(Kit kit) { + Long value = this.kitCooldownMap.get(kit.getKey()); + return value == null ? 0L : value; + } + + public boolean hasCooldownOnKit(Kit kit) { + long claimedTime = getLastKitUsage(kit); + long currentTime = System.currentTimeMillis(); + long difference = currentTime - claimedTime; + long cooldown = kit.getCooldown(); + return difference < cooldown; + } + + public void newCooldownOnKit(Kit kit) { + this.kitCooldownMap.put(kit.getKey(), System.currentTimeMillis()); + } + + public long getSecondsTillKitAvailable(Kit kit) { + long claimedTimeStamp = getLastKitUsage(kit); + long currentTimeStamp = System.currentTimeMillis(); + long difference = currentTimeStamp - claimedTimeStamp; + long cooldown = kit.getCooldown(); + return difference >= cooldown ? 0L : + TimeUnit.MILLISECONDS.toSeconds(cooldown-difference); + } + + + @Override + public String getKey() { + return uuid.toString(); + } + + @Override + public void setKey(String s) { + this.uuid = UUID.fromString(s); + } + + public Player getPlayer() { + return Bukkit.getPlayer(uuid); + } + + public List getGifts() { + if (gifts == null) + this.gifts = new ArrayList<>(); + + return this.gifts; + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/data/CrankedUserManager.java b/Core/src/main/java/net/crankedpvp/crankedcore/data/CrankedUserManager.java new file mode 100644 index 0000000..e4e1343 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/data/CrankedUserManager.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedcore.data; + +import lombok.Getter; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.UUID; + +@Getter +public class CrankedUserManager extends SaveLoadManager { + + public CrankedUserManager(CrankedCore plugin) { + super(plugin, plugin.getGson(), "/data", CrankedUser.class); + } + + public CrankedUser getCrankedUser(UUID uuid) { + if (!containsKey(uuid.toString())) { + CrankedUser crankedUser = new CrankedUser(uuid); + addToCache(crankedUser); + } + return getFromCache(uuid.toString()); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/data/LastHitCache.java b/Core/src/main/java/net/crankedpvp/crankedcore/data/LastHitCache.java new file mode 100644 index 0000000..7432567 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/data/LastHitCache.java @@ -0,0 +1,12 @@ +package net.crankedpvp.crankedcore.data; + + +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +public class LastHitCache { + + public static Map lastHitMapVictimAttacker = new HashMap<>(); +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/AdminItemsGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/AdminItemsGUI.java new file mode 100644 index 0000000..f0df682 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/AdminItemsGUI.java @@ -0,0 +1,75 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.adminarmor.inventory.AdminArmorInventory; +import net.crankedpvp.adminweapons.inventory.AdminWeaponsInventory; +import net.crankedpvp.crankedmasks.inventory.MasksInventory; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.inventory.StarItemsInventory; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +public class AdminItemsGUI { + + @Getter + private final Gui adminItemGUI; + + private final Player player; + + public AdminItemsGUI(Player player) { + this.player = player; + this.adminItemGUI = new Gui(1, "Admin Items"); + this.adminItemGUI.setDefaultClickAction(event -> event.setCancelled(true)); + + this.addAdminArmorToGUI(); + this.addAdminWeaponsToGUI(); + this.addStarItemsToGUI(); + this.addMasksToGUI(); + } + + public void addAdminArmorToGUI() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_CHESTPLATE, "&c&lAdmin Armor", + "&7Click to view all admin armor", + "&7currently unvaulted on the server"); + this.adminItemGUI.addItem(new GuiItem(itemBuilder.setGlowing().colorize().build(), event -> { + this.player.closeInventory(); + AdminArmorInventory adminArmorInventory = new AdminArmorInventory(); + adminArmorInventory.getUI().open(this.player); + })); + } + + public void addAdminWeaponsToGUI() { + ItemBuilder itemBuilder = new ItemBuilder(Material.GOLD_SWORD, "&6&lAdmin Weapons", + "&7Click to view all admin weapons", + "&7currently unvaulted on the server"); + this.adminItemGUI.addItem(new GuiItem(itemBuilder.setGlowing().colorize().build(), event -> { + this.player.closeInventory(); + AdminWeaponsInventory adminWeaponsInventory = new AdminWeaponsInventory(); + adminWeaponsInventory.getUI().open(this.player); + })); + } + + public void addStarItemsToGUI() { + ItemBuilder itemBuilder = new ItemBuilder(Material.NETHER_STAR, "&d&lStar Items", + "&7Click to view all star items", + "&7currently unvaulted on the server"); + this.adminItemGUI.addItem(new GuiItem(itemBuilder.setGlowing().colorize().build(), event -> { + this.player.closeInventory(); + StarItemsInventory starItemsInventory = StarItemsAPI.getStarItemsUI(); + starItemsInventory.getUI().open(this.player); + })); + } + + public void addMasksToGUI() { + ItemBuilder itemBuilder = new ItemBuilder(Material.SKULL_ITEM, "&a&lMasks", + "&7Click to view all masks", + "&7currently unvaulted on the server"); + this.adminItemGUI.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + this.player.closeInventory(); + new MasksInventory().getUI().open(this.player); + })); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/ChatColorGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/ChatColorGUI.java new file mode 100644 index 0000000..d4874f0 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/ChatColorGUI.java @@ -0,0 +1,41 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedcore.commands.ChatColorCommand; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedcore.data.CrankedUserManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.ChatColor; +import org.bukkit.Material; + +@Getter +public class ChatColorGUI { + private final Gui chatColorGUI; + private final CrankedUser crankedUser; + + public ChatColorGUI(CrankedUser crankedUser) { + this.crankedUser = crankedUser; + this.chatColorGUI = new Gui(1, "Select a chat color"); + addPaneToGUI(0, (short)14, ChatColor.RED); + addPaneToGUI(1, (short)5, ChatColor.GREEN); + addPaneToGUI(2, (short)3, ChatColor.AQUA); + addPaneToGUI(3, (short)10, ChatColor.DARK_PURPLE); + addPaneToGUI(4, (short)6, ChatColor.LIGHT_PURPLE); + addPaneToGUI(5, (short)4, ChatColor.YELLOW); + addPaneToGUI(6, (short)1, ChatColor.GOLD); + addPaneToGUI(7, (short)0, ChatColor.WHITE); + addPaneToGUI(8, (short)15, ChatColor.BLACK); + + this.chatColorGUI.setDefaultClickAction(event -> event.setCancelled(true)); + + } + + public void addPaneToGUI(int slot, short colorCode, ChatColor chatColor) { + this.chatColorGUI.setItem(slot, new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE,1, colorCode, + CC.translate(chatColor + CC.Bold + StringUtils.toNiceString(chatColor.name())), CC.translate("&7Click this to select this chat color.")).build(), event -> crankedUser.setChatColor(chatColor))); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/GiftsGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/GiftsGUI.java new file mode 100644 index 0000000..e509b29 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/GiftsGUI.java @@ -0,0 +1,52 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedcore.data.CrankedUserManager; +import net.crankedpvp.crankedcore.struct.gifts.Gift; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.kyori.adventure.text.Component; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class GiftsGUI { + + private static final GuiItem FILLER_ITEM = new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE).setColor(DyeColor.GRAY).setName("").build()); + private static final ItemStack PREV_PAGE_ITEM = new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.").colorize().build(); + private static final ItemStack NEXT_PAGE_ITEM = new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.").colorize().build(); + + @Getter + private final PaginatedGui gui; + + public GiftsGUI(Player player) { + CrankedUserManager crankedUserManager = CrankedCore.getInstance().getCrankedUserManager(); + CrankedUser crankedUser = crankedUserManager.getCrankedUser(player.getUniqueId()); + this.gui = Gui.paginated() + .title(Component.text("Gifts")) + .pageSize(28) + .rows(6) + .disableAllInteractions() + .create(); + + this.gui.getFiller().fillBorder(FILLER_ITEM); + this.gui.setItem(6, 3, new GuiItem(PREV_PAGE_ITEM, event -> this.getGui().previous())); + this.gui.setItem(6, 7, new GuiItem(NEXT_PAGE_ITEM, event -> this.getGui().next())); + for (int i = 0; i < crankedUser.getGifts().size(); i++) { + int finalI = i; + this.gui.addItem(new GuiItem(crankedUser.getGifts().get(i).createGuiGiftItem(), event -> { + InventoryUtils.giveItemToPlayer(player, crankedUser.getGifts().get(finalI).getItemStack()); + crankedUser.getGifts().remove(finalI); + player.closeInventory(); + })); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/GlobalKitsGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/GlobalKitsGUI.java new file mode 100644 index 0000000..4cecc39 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/GlobalKitsGUI.java @@ -0,0 +1,45 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +public class GlobalKitsGUI { + + private final Player player; + + @Getter + private final Gui gui; + + public GlobalKitsGUI(Player player) { + this.player = player; + this.gui = new Gui(1, "Cranked Kits Menu"); + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + setupMainKitsItem(); + setupGodlyKitsItem(); + } + + private void setupMainKitsItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.CHEST, "&b&lDefault Kits", + "&7Click to view the default", + "&7kits on cranked"); + this.gui.setItem(1, 4, new GuiItem(itemBuilder.colorize().build(), event -> { + RankedKitsGUI rankKitsGUI = new RankedKitsGUI(player); + rankKitsGUI.getGui().open(player); + })); + } + + private void setupGodlyKitsItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.ENDER_CHEST, "&c&lGodly Kits", + "&7Click to view the godly", + "&7kits on cranked"); + this.gui.setItem(1, 6, new GuiItem(itemBuilder.colorize().build(), event -> { + this.player.closeInventory(); + GodlyKitsGUI godlyKitsGUI = new GodlyKitsGUI(player); + godlyKitsGUI.getGui().open(player); + })); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/GodlyKitsGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/GodlyKitsGUI.java new file mode 100644 index 0000000..3fa0fed --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/GodlyKitsGUI.java @@ -0,0 +1,102 @@ +package net.crankedpvp.crankedcore.guis; + +import net.crankedpvp.crankedutils.utils.CC; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedcore.struct.kits.Kit; +import net.crankedpvp.crankedcore.struct.kits.KitManager; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.stream.Collectors; + +public class GodlyKitsGUI { + private final Player player; + private KitManager kitManager = CrankedCore.getInstance().getKitManager(); + + @Getter + private final Gui gui; + + public GodlyKitsGUI(Player player) { + this.player = player; + this.gui = new Gui(1, "Godly Kits"); + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + for (Kit kit : kitManager.getCacheValues().stream().filter(Kit::isGkit).collect(Collectors.toList())) { + if (kit.hasAccess(player)) { + CrankedUser crankedUser = CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(player.getUniqueId()); + if (crankedUser.hasCooldownOnKit(kit)) { + gui.addItem(new GuiItem(getCooldownKit(kit, player, crankedUser.getSecondsTillKitAvailable(kit)), event -> { + if (event.isRightClick()) { + KitPreviewGUI kitPreviewGUI = new KitPreviewGUI(player, kit); + kitPreviewGUI.getGui().open(player); + } + })); + } else { + gui.addItem(new GuiItem(getAvailableKit(kit, player), event -> { + if(event.isLeftClick()) { + crankedUser.newCooldownOnKit(kit); + kit.supplyKit(player); + gui.updateItem(event.getSlot(), new GuiItem(getCooldownKit(kit, player, crankedUser.getSecondsTillKitAvailable(kit)), evente -> { + if (evente.isRightClick()) { + KitPreviewGUI kitPreviewGUI = new KitPreviewGUI(player, kit); + kitPreviewGUI.getGui().open(player); + } + })); + } + if (event.isRightClick()) { + KitPreviewGUI kitPreviewGUI = new KitPreviewGUI(player, kit); + kitPreviewGUI.getGui().open(player); + } + })); + } + } else { + gui.addItem(new GuiItem(getUnavailableKit(kit, player), event -> { + if (event.isRightClick()) { + KitPreviewGUI kitPreviewGUI = new KitPreviewGUI(player, kit); + kitPreviewGUI.getGui().open(player); + } + })); + } + } + } + + public ItemStack getUnavailableKit(Kit kit, Player player) { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.RED.getData())) + .setName(CC.translate("&f&ki&r&c&lGKIT&f&ki&r &f&l") + kit.getDisplayName()) + .addLore("&7Right-Click to preview this gkit") + .addLore("") + .addLore("&c&lNO PERMISSION") + .addLore("") + .addLore("&7Unlocked @ &cbuy.crankedpvp.org") + .colorize() + .build(); + } + + public ItemStack getAvailableKit(Kit kit, Player player) { + return new ItemBuilder(Material.CHEST) + .setName(CC.translate("&f&ki&r&c&lGKIT&f&ki&r &f&l") + kit.getDisplayName()) + .addLore("&7Left-Click to redeem this gkit") + .addLore("&7Right-Click to preview this gkit") + .addLore("") + .addLore("&a&lAVAILABLE") + .colorize() + .build(); + } + + public ItemStack getCooldownKit(Kit kit, Player player, long secondsLeft) { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.YELLOW.getData())) + .setName(CC.translate("&f&ki&r&c&lGKIT&f&ki&r &f&l") + kit.getDisplayName()) + .addLore("&7Right-Click to preview this gkit") + .addLore("") + .addLore("&e&lON COOLDOWN &7(" + TimeUtils.formatSeconds(secondsLeft) + ")") + .colorize() + .build(); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/InvseeGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/InvseeGUI.java new file mode 100644 index 0000000..d3ba3e4 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/InvseeGUI.java @@ -0,0 +1,43 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; + +public class InvseeGUI { + @Getter + private PaginatedGui gui; + public InvseeGUI(Player viewer, Player toView) { + this.gui = new PaginatedGui(5, 54, toView.getName() + "'s Inventory"); + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + ItemStack[] items = toView.getInventory().getContents(); + for (int i = 0; i < 36; i++) { + if (items[i] != null) + gui.setItem(i, new GuiItem(items[i])); + } + gui.setItem(36, getFillterItem()); + gui.setItem(37, getFillterItem()); + gui.setItem(40, getFillterItem()); + gui.setItem(43, getFillterItem()); + gui.setItem(44, getFillterItem()); + + PlayerInventory oldInv = toView.getInventory(); + if (oldInv.getHelmet() != null) + gui.setItem(38, new GuiItem( oldInv.getHelmet())); + if (oldInv.getChestplate() != null) + gui.setItem(39, new GuiItem(oldInv.getChestplate())); + if (oldInv.getLeggings() != null) + gui.setItem(41, new GuiItem(oldInv.getLeggings())); + if (oldInv.getBoots() != null) + gui.setItem(42, new GuiItem(oldInv.getBoots())); + } + + public GuiItem getFillterItem() { + return new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (byte)7, "&7 ").colorize().build()); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/KitPreviewGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/KitPreviewGUI.java new file mode 100644 index 0000000..1dcb8f9 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/KitPreviewGUI.java @@ -0,0 +1,46 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedcore.struct.kits.Kit; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class KitPreviewGUI { + @Getter + private final Gui gui; + + public KitPreviewGUI(Player player, Kit kit) { + this.gui = new Gui(4, "Previewing " + kit.getDisplayName() + " Kit"); + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + + for (ItemStack item : kit.getLootList()) { + this.gui.addItem(new GuiItem(item)); + } + + ItemStack backPage = new ItemBuilder(Material.ARROW, "&c<- Go Back", "&7Right-Click&7 to go back.").colorize().build(); + + gui.setItem(35, new GuiItem(backPage, event -> { + if(kit.isGkit()) { + GodlyKitsGUI godlyKitsGUI = new GodlyKitsGUI(player); + godlyKitsGUI.getGui().open(player); + } else { + RankedKitsGUI rankedKitsGUI = new RankedKitsGUI(player); + rankedKitsGUI.getGui().open(player); + } + })); + + gui.setItem(34, GuiUtil.createFillerGuiItem()); + gui.setItem(33, GuiUtil.createFillerGuiItem()); + gui.setItem(32, GuiUtil.createFillerGuiItem()); + gui.setItem(31, GuiUtil.createFillerGuiItem()); + gui.setItem(30, GuiUtil.createFillerGuiItem()); + gui.setItem(29, GuiUtil.createFillerGuiItem()); + gui.setItem(28, GuiUtil.createFillerGuiItem()); + gui.setItem(27, GuiUtil.createFillerGuiItem()); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/NetherPvPGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/NetherPvPGUI.java new file mode 100644 index 0000000..67e7b31 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/NetherPvPGUI.java @@ -0,0 +1,103 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.struct.netherpvp.NetherPvPQueueManager; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +public class NetherPvPGUI { + + @Getter + private final PaginatedGui gui; + private final NetherPvPQueueManager netherPvPQueueManager; + + public NetherPvPGUI() { + this.netherPvPQueueManager = CrankedCore.getInstance().getNetherPvPQueueManager(); + this.gui = Gui.paginated() + .title(Component.text("Nether PvP")) + .disableAllInteractions() + .pageSize(27) + .rows(4) + .create(); + + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + this.gui.getFiller().fillBottom(GuiUtil.createFillerGuiItem()); + this.gui.setItem(4, 1, new GuiItem(GuiUtil.createPreviousItem(), event -> this.gui.previous())); + this.gui.setItem(4, 9, new GuiItem(GuiUtil.createNextItem(), event -> this.gui.next())); + this.gui.setItem(4, 5, this.getJoinQueueItem()); + for (Player player : this.netherPvPQueueManager.getPlayersFromPvpQueue()) { + this.gui.addItem(this.getPlayerItem(player)); + } + } + + private GuiItem getJoinQueueItem() { + return new GuiItem(new ItemBuilder(Material.FIREBALL) + .setName("&4&lNether Arena 1v1") + .setLore( + "&fFight to the death in a 1v1 match", + "&fat the Nether Warp Arena", + "", + "&cInformation:", + "&f• Located at &c/warp nether", + "&f• Holy White Scrolls are &cdisabled", + "", + "&cClick to &4&lCREATE&c a match!" + ) + .colorize() + .build(), event -> { + Player player = (Player) event.getWhoClicked(); + if (this.netherPvPQueueManager.isPlayerInPvPQueue(player)) return; + this.netherPvPQueueManager.addPlayerToPvpQueue(player); + player.closeInventory(); + SoundUtils.playSuccessSound(player); + //player.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You have successfully created a NetherPvP match, make sure you stay in &aSafezone&7 for the match to start")); + Bukkit.broadcastMessage((CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + " " + LuckpermUtils.getDisplayName(player) + "&f has created a NetherPvP match, go defeat them (&c/netherpvp&f)!"))); + player.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You have successfully created a NetherPvP match, make sure you stay in &aSafezone&7 for the match to start!")); + Clickable clickable = new Clickable("&c[Click here to leave]", "&7&o/netherpvp leave", "/netherpvp leave"); + clickable.sendToPlayer(player); + }); + } + + private GuiItem getPlayerItem(Player player) { + return new GuiItem(new ItemBuilder(SkullUtils.getSkullFromPlayer(player)) + .setName(CC.Red + player.getName()) + .setLore( + "", + "&aLeft-Click&7 to accept match", + "&cRight-Click&7 to view inventory" + ) + .colorize() + .build(), event -> { + Player playerWhoClicked = (Player) event.getWhoClicked(); + + if (event.getClick().isLeftClick()) { + if (player == playerWhoClicked) { + SoundUtils.playErrorSound(playerWhoClicked); + playerWhoClicked.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You cannot accept your own match")); + return; + } + boolean matchStarted = this.netherPvPQueueManager.acceptMatch(player, playerWhoClicked); + if (matchStarted) { + this.netherPvPQueueManager.removePlayerFromPvpQueue(player); + } + } else if (event.getClick().isRightClick()) { + if (player == playerWhoClicked) { + SoundUtils.playErrorSound(playerWhoClicked); + playerWhoClicked.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You cannot invsee yourself")); + return; + } + playerWhoClicked.closeInventory(); + playerWhoClicked.performCommand("invsee " + player.getName()); + } + }); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/RankedKitsGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/RankedKitsGUI.java new file mode 100644 index 0000000..ea1aee8 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/RankedKitsGUI.java @@ -0,0 +1,112 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedcore.struct.kits.Kit; +import net.crankedpvp.crankedcore.struct.kits.KitManager; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.kyori.adventure.text.Component; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.stream.Collectors; + +public class RankedKitsGUI { + + private static final KitManager KIT_MANAGER = CrankedCore.getInstance().getKitManager(); + + @Getter + private final Gui gui; + + public RankedKitsGUI(Player player) { + this.gui = Gui.gui() + .rows(1) + .title(Component.text("Rank Kits")) + .create(); + + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + + for (Kit kit : getAllRankKits()) { + if (kit.hasAccess(player)) { + CrankedUser crankedUser = CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(player.getUniqueId()); + if (crankedUser.hasCooldownOnKit(kit)) { + this.gui.addItem(new GuiItem(getCooldownKit(kit, crankedUser.getSecondsTillKitAvailable(kit)), event -> { + if (event.isRightClick()) { + KitPreviewGUI kitPreviewGUI = new KitPreviewGUI(player, kit); + kitPreviewGUI.getGui().open(player); + } + })); + } else { + gui.addItem(new GuiItem(getAvailableKit(kit), event -> { + if(event.isLeftClick()) { + crankedUser.newCooldownOnKit(kit); + kit.supplyKit(player); + gui.updateItem(event.getSlot(), new GuiItem(getCooldownKit(kit, crankedUser.getSecondsTillKitAvailable(kit)), evente -> { + if (evente.isRightClick()) { + KitPreviewGUI kitPreviewGUI = new KitPreviewGUI(player, kit); + kitPreviewGUI.getGui().open(player); + } + })); + } + if (event.isRightClick()) { + KitPreviewGUI kitPreviewGUI = new KitPreviewGUI(player, kit); + kitPreviewGUI.getGui().open(player); + } + })); + } + } else { + gui.addItem(new GuiItem(getUnavailableKit(kit), event -> { + if (event.isRightClick()) { + KitPreviewGUI kitPreviewGUI = new KitPreviewGUI(player, kit); + kitPreviewGUI.getGui().open(player); + } + })); + } + } + } + + private List getAllRankKits() { + return KIT_MANAGER.getCacheValues().stream().filter(kit -> !kit.isGkit()).sorted().collect(Collectors.toList()); + } + + private static ItemStack getUnavailableKit(Kit kit) { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.RED.getData())) + .setName(CC.translate("&a&l") + kit.getDisplayName() + " Kit") + .addLore("&7Right-Click to preview this kit") + .addLore("") + .addLore("&c&lNO PERMISSION") + .addLore("") + .addLore("&7Unlocked @ &cbuy.crankedpvp.org") + .colorize() + .build(); + } + + private static ItemStack getAvailableKit(Kit kit) { + return new ItemBuilder(Material.CHEST) + .setName(CC.translate("&a&l") + kit.getDisplayName() + " Kit") + .addLore("&7Left-Click to redeem this kit") + .addLore("&7Right-Click to preview this kit") + .addLore("") + .addLore("&a&lAVAILABLE") + .colorize() + .build(); + } + + private static ItemStack getCooldownKit(Kit kit, long secondsLeft) { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.YELLOW.getData())) + .setName(CC.translate("&a&l") + kit.getDisplayName() + " Kit") + .addLore("&7Right-Click to preview this kit") + .addLore("") + .addLore("&e&lON COOLDOWN &7(" + TimeUtils.formatSeconds(secondsLeft) + ")") + .colorize() + .build(); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/SpawnerShopGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/SpawnerShopGUI.java new file mode 100644 index 0000000..70766e7 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/SpawnerShopGUI.java @@ -0,0 +1,47 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.shop.ShopPlugin; +import net.crankedpvp.shop.handlers.ShopItem; +import net.crankedpvp.spawners.items.ItemSpawner; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Getter +public class SpawnerShopGUI { + private Gui spawnerGUI; + private int amount; + + public SpawnerShopGUI(int amount) { + this.amount = amount; + this.spawnerGUI = new Gui(1, "Spawner Shop (" + amount + ")"); + this.spawnerGUI.setDefaultClickAction(event -> event.setCancelled(true)); + for (ShopItem shopItem : ShopPlugin.getShopHandler().getItems("Spawnershop")) { + this.spawnerGUI.addItem(getSpawnerGuiItem(shopItem)); + } + } + + private GuiItem getSpawnerGuiItem(ShopItem shopItem) { + double totalPrice = shopItem.getBuyPrice() * amount; + ItemStack spawner = ItemSpawner.getItem(EntityType.valueOf(shopItem.getSpawner()), amount); + ItemStack item = new ItemBuilder(spawner.clone()).addLore("&aBuy Price").addLore("&a $" + NumberUtils.formatMoney(totalPrice)).colorize().build(); + return new GuiItem(item, event -> { + Player player = (Player) event.getWhoClicked(); + if (EconomyUtils.hasBalance(player, totalPrice)) { + PlayerUtils.giveOrDropProtectedItem(player, spawner.clone(), 60); + EconomyUtils.withdrawBalance(player, totalPrice); + player.sendMessage(CC.translate("&a&l- $" + NumberUtils.formatMoney(totalPrice))); + } else { + player.sendMessage(CC.translate("&c&l(!)&c You do not have enough money to buy this!")); + } + }); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/guis/WarpGUI.java b/Core/src/main/java/net/crankedpvp/crankedcore/guis/WarpGUI.java new file mode 100644 index 0000000..3d1d5a4 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/guis/WarpGUI.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedcore.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class WarpGUI { + + private final Gui warpUI; + + public Gui getWarpUI() { + return this.warpUI; + } + + public WarpGUI(Player player) { + this.warpUI = new Gui(1, "Warp GUI"); + + warpUI.setDefaultClickAction(event -> { + event.setCancelled(true); + }); + + ItemStack desert = new ItemBuilder(Material.SAND, CC.translate("&e&lDesert Warp"), CC.translate("&7Click to teleport to this warp")).build(); + ItemStack crates = new ItemBuilder(Material.CHEST, CC.translate("&b&lCrates Warp"), CC.translate("&7Click to teleport to this warp")).build(); + ItemStack nether = new ItemBuilder(Material.NETHERRACK, CC.translate("&4&lNether Warp"), CC.translate("&7Click to teleport to this warp")).build(); + ItemStack flat = new ItemBuilder(Material.RED_SANDSTONE, CC.translate("&6&lFlat World"), CC.translate("&7Click to teleport to this warp")).build(); + ItemStack koth = new ItemBuilder(Material.EYE_OF_ENDER, CC.translate("&d&lKoth Warp"), CC.translate("&7Click to teleport to this warp")).build(); + + warpUI.setItem(1, 1, new GuiItem((desert), event -> player.performCommand("warp desert"))); + warpUI.setItem(1, 2, new GuiItem((crates), event -> player.performCommand("warp crates"))); + warpUI.setItem(1, 3, new GuiItem((flat), event -> player.performCommand("warp flat"))); + warpUI.setItem(1, 4, new GuiItem((koth), event -> player.performCommand("warp koth"))); + warpUI.setItem(1, 5, new GuiItem((nether), event -> player.performCommand("warp nether"))); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/hotfix/CitizensReload.java b/Core/src/main/java/net/crankedpvp/crankedcore/hotfix/CitizensReload.java new file mode 100644 index 0000000..1d422e8 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/hotfix/CitizensReload.java @@ -0,0 +1,14 @@ +package net.crankedpvp.crankedcore.hotfix; + +import net.crankedpvp.crankedcore.CrankedCore; +import org.bukkit.Bukkit; +import org.bukkit.event.server.ServerCommandEvent; + +public class CitizensReload { + + public static void reloadCitizens() { + ServerCommandEvent serverCommandEvent = new ServerCommandEvent(Bukkit.getConsoleSender(), "citizens reload"); + serverCommandEvent.callEvent(); + Bukkit.getScheduler().runTaskLater(CrankedCore.getInstance(), serverCommandEvent::callEvent, 2L); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/items/IceWandItem.java b/Core/src/main/java/net/crankedpvp/crankedcore/items/IceWandItem.java new file mode 100644 index 0000000..55719b1 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/items/IceWandItem.java @@ -0,0 +1,108 @@ +package net.crankedpvp.crankedcore.items; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import net.crankedpvp.crankedutils.utils.CC; +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.UUID; + +public class IceWandItem implements Listener { + + private final Board board = Board.getInstance(); + private final FPlayers fPlayers = FPlayers.getInstance(); + + public static ItemStack createItem(int radius, int iceWandUses) { + boolean unlimited = iceWandUses < 1; + ItemStack item = new ItemBuilder(Material.BLAZE_ROD, 1, (short) 0, + "&bIce Wand &8(&7" + (unlimited ? "Unlimited" : NumberUtils.formatNum(iceWandUses)) + " uses&8)", + "", + "&7&oWith this magical ice wand, you", + "&7&ohave the ability to control ice.", + "", + "&b* &7Radius: &f" + radius + "x" + radius, + "", + "&b* &7Usage: &fRight-Click to melt ice." + ).setGlowing().colorize().build(); + + NBTItem nbtItem = new NBTItem(item); + nbtItem.setString("extinctCustomItem", "iceWand"); + nbtItem.setString("NoStackingUUID", UUID.randomUUID().toString()); + NBTCompound extinctItemData = nbtItem.addCompound("ExtinctItemData"); + extinctItemData.setInteger("iceWandUses", iceWandUses); + extinctItemData.setBoolean("iceWandUnlimited", unlimited); + extinctItemData.setInteger("iceWandRadius", radius); + return nbtItem.getItem(); + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + Player player = event.getPlayer(); + if (event.getClickedBlock() == null || player.getItemInHand() == null) return; + + if (event.getClickedBlock().getType() != Material.ICE) return; + + if (player.getItemInHand().getType() != Material.BLAZE_ROD) return; + + Faction playerFac = fPlayers.getByPlayer(player).getFaction(); + Faction facAtBlock = board.getFactionAt(new FLocation(event.getClickedBlock().getLocation())); + if (!playerFac.equals(facAtBlock) && !facAtBlock.isWilderness()) return; + + NBTItem iceWand = new NBTItem(player.getItemInHand()); + if (!iceWand.getString("extinctCustomItem").equals("iceWand")) return; + + event.setCancelled(true); + + NBTCompound extinctItemData = iceWand.getCompound("ExtinctItemData"); + int radius = extinctItemData.getInteger("iceWandRadius"); + int usesLeft = extinctItemData.getInteger("iceWandUses"); + + Block target; + Faction facAtLoc; + for (int x = -radius; x <= radius; x++) { + for (int z = -radius; z <= radius; z++) { + target = event.getClickedBlock().getRelative(x,0, z); + + facAtLoc = board.getFactionAt(new FLocation(target.getLocation())); + if (!playerFac.equals(facAtLoc) && !facAtLoc.isWilderness()) continue; + + for (int y = -radius; y <= radius; y++) { + target = event.getClickedBlock().getRelative(x, y, z); + if (target.getType() == Material.ICE) target.setType(Material.WATER, false); + } + } + } + + boolean unlimited = extinctItemData.getBoolean("iceWandUnlimited"); + if (!unlimited) { + usesLeft -= 1; + extinctItemData.setInteger("iceWandUses", usesLeft); + if (usesLeft < 1) { + player.setItemInHand(new ItemStack(Material.AIR)); + player.playSound(player.getLocation(), Sound.ITEM_BREAK,0.8f,0.9f); + return; + } + } + + ItemMeta meta = iceWand.getItem().getItemMeta(); + meta.setDisplayName(CC.translate("&bIce Wand &8(&7" + (unlimited ? "Unlimited" : NumberUtils.formatNum(usesLeft)) + " uses&8)")); + + iceWand.getItem().setItemMeta(meta); + player.setItemInHand(iceWand.getItem()); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/items/MagicalLavaBucketItem.java b/Core/src/main/java/net/crankedpvp/crankedcore/items/MagicalLavaBucketItem.java new file mode 100644 index 0000000..9305fdf --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/items/MagicalLavaBucketItem.java @@ -0,0 +1,56 @@ +package net.crankedpvp.crankedcore.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +public class MagicalLavaBucketItem implements Listener { + + private final CrankedCore plugin; + + public MagicalLavaBucketItem(CrankedCore plugin) { + this.plugin = plugin; + } + + public static ItemStack createMagicalLavaBucket(int lavaBucketUses) { + ItemStack item = new ItemBuilder(Material.LAVA_BUCKET, 1, (short) 0, + "&cMagical Lava Bucket&8 (&7" + NumberUtils.formatNum(lavaBucketUses) + " uses&8)", + "", + "&7&oThis lava bucket is capable of", + "&7&orefilling its self when used", + "", + "&c* &7Usage: &fRight-Click on a block" + ).setGlowing().colorize().build(); + NBTItem nbtItem = new NBTItem(item); + nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setString("extinctCustomItem", "magicalLavaBucket"); + nbtItem.setInteger("lavaBucketUses", lavaBucketUses); + return nbtItem.getItem(); + } + + @EventHandler + public void onLavaBucketPlace(PlayerBucketEmptyEvent event) { + Player p = event.getPlayer(); + NBTItem nbtItem = new NBTItem(p.getItemInHand()); + if (nbtItem.hasKey("extinctCustomItem")) { + if (nbtItem.getString("extinctCustomItem").equalsIgnoreCase("magicalLavaBucket")) { + int uses = nbtItem.getInteger("lavaBucketUses"); + if (uses <= 1) { + p.getInventory().setItemInHand(new ItemStack(Material.BUCKET)); + p.updateInventory(); + } else { + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> p.getInventory().setItem(p.getInventory().getHeldItemSlot(), createMagicalLavaBucket(uses - 1))); + } + } + } + } +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/items/MagicalWaterBucketItem.java b/Core/src/main/java/net/crankedpvp/crankedcore/items/MagicalWaterBucketItem.java new file mode 100644 index 0000000..8885497 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/items/MagicalWaterBucketItem.java @@ -0,0 +1,75 @@ +package net.crankedpvp.crankedcore.items; + +import de.tr7zw.nbtapi.NBTItem; +import com.massivecraft.factions.*; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.UUID; + +public class MagicalWaterBucketItem implements Listener { + + public static ItemStack createMagicalWaterBucket(int waterBucketUses) { + ItemStack itemStack = new ItemBuilder(Material.WATER_BUCKET, 1, (short) 0, + "&9Magical Water Bucket&8 (&7" + NumberUtils.formatNum(waterBucketUses) + " uses&8)", + "", + "&7&oThis water bucket is capable of", + "&7&orefilling its self when used", + "", + "&9* &7Usage: &fRight-Click on a block" + ).colorize().build(); + ItemMeta meta = itemStack.getItemMeta(); + meta.addEnchant(Enchantment.DURABILITY, 3, true); + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + itemStack.setItemMeta(meta); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setString("extinctCustomItem", "magicalWaterBucket"); + nbtItem.setInteger("waterBucketUses", waterBucketUses); + return nbtItem.getItem(); + } + + @EventHandler + public void onWaterBucketPlace(PlayerBucketEmptyEvent event) { + Player player = event.getPlayer(); + NBTItem nbtItem = new NBTItem(player.getItemInHand()); + + BlockFace blockFace = event.getBlockFace(); + Location location = event.getBlockClicked().getLocation().add(blockFace.getModX(), blockFace.getModY(), blockFace.getModZ()); + + FLocation fLocation = new FLocation(location); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + Faction faction = fPlayer.getFaction(); + + if (nbtItem.hasKey("extinctCustomItem")) { + if (nbtItem.getString("extinctCustomItem").equalsIgnoreCase("magicalWaterBucket")) { + event.setCancelled(true); + + if (!Board.getInstance().getFactionAt(fLocation).isWilderness() && + Board.getInstance().getFactionAt(fLocation) != faction) { + event.getPlayer().setItemInHand(nbtItem.getItem()); + return; + } + event.getBlockClicked().getRelative(event.getBlockFace()).setType(Material.WATER); + int uses = nbtItem.getInteger("waterBucketUses"); + if (uses <= 1) { + player.getInventory().setItemInHand(new ItemStack(Material.BUCKET)); + player.updateInventory(); + } else { + player.getInventory().setItem(player.getInventory().getHeldItemSlot(), createMagicalWaterBucket(uses - 1)); + } + } + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/items/SandWandItem.java b/Core/src/main/java/net/crankedpvp/crankedcore/items/SandWandItem.java new file mode 100644 index 0000000..7a88bd1 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/items/SandWandItem.java @@ -0,0 +1,97 @@ +package net.crankedpvp.crankedcore.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import com.massivecraft.factions.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class SandWandItem implements Listener { + + private final CrankedCore plugin; + + public SandWandItem(CrankedCore plugin) { + this.plugin = plugin; + } + + public static ItemStack createSandWand(int sandWandUses) { + ItemStack itemStack = new ItemBuilder(Material.IRON_HOE, 1, (short) 0, + "&eSand Wand&8 (&7" + NumberUtils.formatNum(sandWandUses) + " uses&8)", + "", + "&7&oThis wand can be used to remove", + "&7&osand pillars in your territory", + "", + "&e* &7Usage: &fRight-Click Sand to use" + ).colorize().build(); + ItemMeta meta = itemStack.getItemMeta(); + meta.addEnchant(Enchantment.DURABILITY, 3, true); + meta.spigot().setUnbreakable(true); + meta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE); + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + itemStack.setItemMeta(meta); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("extinctCustomItem", "sandWand"); + nbtItem.setInteger("sandWandUses", sandWandUses); + return nbtItem.getItem(); + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if (event.getClickedBlock() == null || event.getPlayer().getItemInHand() == null) return; + if (event.getClickedBlock().getType() == Material.SAND || event.getClickedBlock().getType() == Material.GRAVEL) { + ItemStack itemStack = event.getPlayer().getInventory().getItemInHand(); + if (itemStack.getType() == Material.IRON_HOE) { + NBTItem nbtItem = new NBTItem(itemStack); + if (nbtItem.hasKey("extinctCustomItem")) { + if (nbtItem.getString("extinctCustomItem").equalsIgnoreCase("sandWand")) { + Player p = event.getPlayer(); + int uses = nbtItem.getInteger("sandWandUses"); + if (uses <= 1) { + p.getInventory().setItemInHand(null); + p.playSound(p.getLocation(), Sound.ITEM_BREAK, 10.0F, 1.2F); + } else { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(p); + if (!fplayer.getFaction().isWilderness()) { + Location startLocation = event.getClickedBlock().getLocation(); + FLocation flocation = new FLocation(startLocation); + Faction faction = Board.getInstance().getFactionAt(flocation); + if (faction == fplayer.getFaction()) { + plugin.getServer().getScheduler().runTask(plugin, () -> p.getInventory().setItem(p.getInventory().getHeldItemSlot(), createSandWand(uses - 1))); + int count = 0; + for (int y = 255; y >= 1; y--) { + startLocation.setY(y); + Block b = startLocation.getBlock(); + if (b.getType().equals(Material.SAND) || b.getType().equals(Material.GRAVEL)) { + b.setType(Material.AIR); + count++; + } + } + int finalCount = count; + Language.WAND_REMOVED_SAND.send(p, str -> str.replace("%count%", String.valueOf(finalCount))); + } else { + Language.WRONG_TERRITORY.send(p); + } + } else { + Language.NEED_FACTION_TO_USE.send(p); + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/language/Language.java b/Core/src/main/java/net/crankedpvp/crankedcore/language/Language.java new file mode 100644 index 0000000..255d71d --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/language/Language.java @@ -0,0 +1,172 @@ +package net.crankedpvp.crankedcore.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + ADMINKIT_HELP, + ADMINKIT_GIVE_HELP, + ADMINKIT_CREATE_HELP, + ADMINKIT_ALREADY_EXISTS, + ADMINKIT_CREATED, + KIT_RECEIVED, + KIT_COOLDOWN, + KIT_INVALID_NAME, + KIT_NO_ACCESS, + + WAND_REMOVED_SAND, + + WRONG_TERRITORY, + NEED_FACTION_TO_USE, + + REBOOT_SCHEDULED, + REBOOT_CANCEL, + REBOOT_NOT_SCHEDULED, + REBOOT_IN, + REBOOT_CAN_NOT_DO_THIS, + + CANNOT_HAVE_EMPTY_HAND, + ALREADY_HAS_GIFT, + GIFT_URSELF, + RECEIVED_GIFT, + SENT_GIFT, + + BLESS, + MOTD, + NO_PERMISSION, + INVSEE, + CANNOT_INVSEE_YOURSELF, + POTS_RECEIVED, + POTS_TOO_EXPENSIVE, + STAFF_CHAT_JOIN, + STAFF_CHAT_LEAVE, + FULL_INVENTORY, + GODSET_SUCCESS, + EXP_BOTTLE_WITHDRAW, + EXP_BOTTLE_DEPOSIT, + EXP_BOTTLE_HELP, + EXP_BOTTLE_NOT_ENOUGH, + NOTE_WITHDRAW, + NOTE_DEPOSIT, + NOTE_HELP, + NOTE_NOT_ENOUGH, + INVALID_NUMBER, + WITHDRAW_DECIMAL, + NEAR_TOO_MANY_PLAYERS, + CANNOT_INVSEE_GHOST_MASK, + ADMIN_RELOADING, + CLAIM_MAX_REACHED, + CLAIM_OBTAINED, + CLAIM_OBTAINED_OTHER, + max_warzone_claims, + ENABLED_FAC_TITLE, + DISABLED_FAC_TITLE, + ENABLED_KILL_TITLE, + ENABLED_BOSS_DEATH_MESSAGES, + DISABLED_BOSS_DEATH_MESSAGES, + DISABLED_KILL_TITLE, + GIVEALL_RECEIVED, + BLOCKED_COMMAND, + golden_apple_cooldown, + GOLDEN_APPLE_ENTERED_COOLDOWN, + GOLDEN_APPLE_COOLDOWN, + heal_cooldown, + HEALED, + HEAL_COOLDOWN, + LOOKING_FOR_FACTION, + LOOKING_FOR_FACTION_COOLDOWN, + ADMIN_RELOADED + + + + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + if (value == null) value = this.name(); + this.value = CC.translate(value); + + String[] lines = StringUtils.split(value, System.lineSeparator()); + List tempList = Arrays.stream(lines == null ? new String[0] : lines) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.stream().map(value -> value == null ? "" : value) + .collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(value -> CC.translate(value == null ? "" : value)) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/language/LanguageHandler.java b/Core/src/main/java/net/crankedpvp/crankedcore/language/LanguageHandler.java new file mode 100644 index 0000000..812fb1c --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.crankedcore.language; + +import net.crankedpvp.crankedcore.CrankedCore; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final CrankedCore plugin; + + public LanguageHandler(CrankedCore plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AlwaysSunnyListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AlwaysSunnyListener.java new file mode 100644 index 0000000..4b5b5a3 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AlwaysSunnyListener.java @@ -0,0 +1,23 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.CrankedCore; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.weather.WeatherChangeEvent; + +public class AlwaysSunnyListener implements Listener { + public AlwaysSunnyListener() { + Bukkit.getScheduler().scheduleSyncRepeatingTask(CrankedCore.getInstance(), ()-> { + for (World w : Bukkit.getServer().getWorlds()) { + w.setTime(0L); + } + },0, 10000L); + } + + @EventHandler + public void DisableWeather(WeatherChangeEvent event) { + event.setCancelled(event.toWeatherState()); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBedListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBedListener.java new file mode 100644 index 0000000..8b0528e --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBedListener.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.player.PlayerBedEnterEvent; + +public class AntiBedListener implements Listener { + @EventHandler + public void clickBed(PlayerBedEnterEvent e) { + e.setCancelled(true); + + } + + @EventHandler + public void onBlockplace(BlockPlaceEvent e) { + if (e.getBlock().getType() == Material.BED) { + e.getPlayer().sendMessage(CC.Red + "You cannot place this beds!"); + e.setCancelled(true); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBlockGlitchListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBlockGlitchListener.java new file mode 100644 index 0000000..0ff8f64 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBlockGlitchListener.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.util.Vector; + +public class AntiBlockGlitchListener implements Listener { + @EventHandler + public void preventBlockGlitch(BlockPlaceEvent event) { + if (!event.isCancelled()) return; + + Player player = event.getPlayer(); + Location location = player.getLocation(); + Location blockLocation = event.getBlock().getLocation(); + + blockLocation.setX(getAccurateCoord(blockLocation.getX())); + blockLocation.setZ(getAccurateCoord(blockLocation.getZ())); + + if ((int) location.getX() != (int) blockLocation.getX() ) return; + + if ((int) location.getZ() != (int) blockLocation.getZ()) return; + + player.setVelocity(new Vector(0, -1, 0)); + } + + private double getAccurateCoord(double coord) { + if (coord < 0) return coord + 1.0; + return coord; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBoatListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBoatListener.java new file mode 100644 index 0000000..3a72486 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBoatListener.java @@ -0,0 +1,31 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Boat; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.vehicle.VehicleCreateEvent; + +public class AntiBoatListener implements Listener { + @EventHandler + public void onVehicleCreateEvent(VehicleCreateEvent e) { + if (e.getVehicle() instanceof Boat) { + e.getVehicle().remove(); + } + } + + @EventHandler + public void onPlayerInteractEvent(PlayerInteractEvent e) { + Player pl = e.getPlayer(); + if (e.hasItem() && e.getItem().getType() == Material.BOAT && (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK)) { + pl.sendMessage(ChatColor.RED + "Boat placement is currently " + ChatColor.UNDERLINE + "disabled."); + e.setCancelled(true); + e.setUseItemInHand(Event.Result.DENY); + } + } +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBookEnchantListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBookEnchantListener.java new file mode 100644 index 0000000..9ce42ae --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBookEnchantListener.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.enchantment.EnchantItemEvent; +import org.bukkit.event.inventory.InventoryClickEvent; + +public class AntiBookEnchantListener implements Listener { + @EventHandler + public void onInventoryClick(InventoryClickEvent e) { + if (e.getInventory().getTitle().equals("Enchant") && e.getCurrentItem() != null && (e.getCurrentItem().getType() == Material.BOOK || e.getCurrentItem().getType() == Material.ENCHANTED_BOOK)) { + e.setCancelled(true); + e.setResult(Event.Result.DENY); + e.getWhoClicked().sendMessage(ChatColor.RED + "You cannot currently inscribe enchantments onto books."); + e.getWhoClicked().closeInventory(); + } + } + + @EventHandler + public void onEnchantItemEvent(EnchantItemEvent e) { + if (e.getItem().getType() == Material.BOOK || e.getItem().getType() == Material.ENCHANTED_BOOK) { + e.getEnchanter().sendMessage(ChatColor.RED + "You cannot currently inscribe enchantments onto books."); + e.getEnchanter().closeInventory(); + e.setCancelled(true); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBrewingStandListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBrewingStandListener.java new file mode 100644 index 0000000..2588c7f --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiBrewingStandListener.java @@ -0,0 +1,18 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class AntiBrewingStandListener implements Listener { + + @EventHandler + public void onInteractWithBrewingStand(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (event.getClickedBlock() == null) return; + if (event.getClickedBlock().getType() != Material.BREWING_STAND) return; + event.setCancelled(true); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDoorHitListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDoorHitListener.java new file mode 100644 index 0000000..790d4dc --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDoorHitListener.java @@ -0,0 +1,46 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class AntiDoorHitListener implements Listener { + private final Map doorHits; + + public AntiDoorHitListener() { + this.doorHits = new HashMap<>(); + } + + @EventHandler + public void openDoor(PlayerInteractEvent e) { + if (e.getClickedBlock() == null) return; + if (e.getClickedBlock().getType().name().endsWith("_DOOR")) { + doorHits.put(e.getPlayer().getUniqueId(), System.currentTimeMillis()); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onHit(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Player) { + if (!canHit((Player) e.getDamager())) { + e.setCancelled(true); + } + } + } + + public boolean canHit(Player player) { + if (doorHits.containsKey(player.getUniqueId())) { + long lastOpened = doorHits.get(player.getUniqueId()); + int timeBetweenDoorHit = 700; + return System.currentTimeMillis() >= lastOpened + timeBetweenDoorHit; + } + return true; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDroppedItemRemoveListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDroppedItemRemoveListener.java new file mode 100644 index 0000000..20d0034 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDroppedItemRemoveListener.java @@ -0,0 +1,14 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class AntiDroppedItemRemoveListener implements Listener { + @EventHandler + public void onEntityDamage(EntityDamageEvent e) { + if (e.getEntity().getType() == EntityType.DROPPED_ITEM) + e.setCancelled(true); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDrownListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDrownListener.java new file mode 100644 index 0000000..da88968 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiDrownListener.java @@ -0,0 +1,16 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.entity.Entity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class AntiDrownListener implements Listener { + @EventHandler + public void onDrown(EntityDamageEvent e) { + Entity ent = e.getEntity(); + if (ent instanceof org.bukkit.entity.Blaze && + e.getCause() == EntityDamageEvent.DamageCause.DROWNING) + e.setCancelled(true); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiFallDamageListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiFallDamageListener.java new file mode 100644 index 0000000..9cfc766 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiFallDamageListener.java @@ -0,0 +1,16 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class AntiFallDamageListener implements Listener { + @EventHandler + public void onPlayerFall(EntityDamageEvent e) { + if (e.getEntity() instanceof Player) { + if (e.getCause() == EntityDamageEvent.DamageCause.FALL) + e.setCancelled(true); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiHopperListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiHopperListener.java new file mode 100644 index 0000000..5da08b6 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiHopperListener.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.inventory.InventoryPickupItemEvent; +import org.bukkit.event.inventory.InventoryType; + +public class AntiHopperListener implements Listener { + @EventHandler + public void onBlockPlace(BlockPlaceEvent e) { + if(e.getBlock().getType() == Material.HOPPER) { + e.getPlayer().sendMessage(CC.Red + "You cannot place hoppers!"); + e.setCancelled(true); + } + } + + @EventHandler + public void disablePickup(InventoryPickupItemEvent e) { + if (e.getInventory().getType() != InventoryType.HOPPER) { + return; + } + if (e.getInventory().getType() == InventoryType.HOPPER) { + e.setCancelled(true); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiMinecartListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiMinecartListener.java new file mode 100644 index 0000000..fecda7e --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiMinecartListener.java @@ -0,0 +1,84 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.inventory.PrepareItemCraftEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.ChunkUnloadEvent; +import org.bukkit.inventory.ItemStack; + +public class AntiMinecartListener implements Listener { + @EventHandler(priority = EventPriority.LOWEST) + public void onLoad(ChunkLoadEvent event) { + for (Entity entity : event.getChunk().getEntities()) { + if (entity.getType() != EntityType.MINECART && entity.getType() != EntityType.MINECART_CHEST && entity.getType() != EntityType.MINECART_COMMAND && entity.getType() != EntityType.MINECART_FURNACE && entity.getType() != EntityType.MINECART_HOPPER && entity.getType() != EntityType.MINECART_MOB_SPAWNER && entity.getType() != EntityType.MINECART_TNT) + continue; + entity.remove(); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onUnload(ChunkUnloadEvent event) { + for (Entity entity : event.getChunk().getEntities()) { + if (entity.getType() != EntityType.MINECART && entity.getType() != EntityType.MINECART_CHEST && entity.getType() != EntityType.MINECART_COMMAND && entity.getType() != EntityType.MINECART_FURNACE && entity.getType() != EntityType.MINECART_HOPPER && entity.getType() != EntityType.MINECART_MOB_SPAWNER && entity.getType() != EntityType.MINECART_TNT) + continue; + entity.remove(); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + Block block = event.getBlock(); + if (block.getType() == Material.MINECART || block.getType() == Material.POWERED_MINECART || block.getType() == Material.POWERED_RAIL || block.getType() == Material.RAILS || block.getType() == Material.DETECTOR_RAIL) { + event.setCancelled(true); + event.getPlayer().sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RESET + "" + ChatColor.RED + " place minecarts or rails."); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlace(PlayerInteractEvent event) { + if (!event.hasItem() || event.getItem().getType() == null) { + return; + } + ItemStack block = event.getItem(); + if (block.getType() == Material.MINECART || block.getType() == Material.POWERED_MINECART || block.getType() == Material.POWERED_RAIL || block.getType() == Material.RAILS || block.getType() == Material.DETECTOR_RAIL) { + event.setCancelled(true); + event.getPlayer().sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RESET + "" + ChatColor.RED + " place minecarts or rails."); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDrop(PlayerDropItemEvent event) { + ItemStack block = event.getItemDrop().getItemStack(); + if (block != null && (block.getType() == Material.MINECART || block.getType() == Material.POWERED_MINECART || block.getType() == Material.POWERED_RAIL || block.getType() == Material.RAILS || block.getType() == Material.DETECTOR_RAIL)) { + event.setCancelled(true); + event.getPlayer().updateInventory(); + event.getItemDrop().remove(); + event.getPlayer().sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RESET + "" + ChatColor.RED + " drop minecarts or rails."); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickup(PlayerPickupItemEvent event) { + ItemStack block = event.getItem().getItemStack(); + if (block != null && (block.getType() == Material.MINECART || block.getType() == Material.POWERED_MINECART || block.getType() == Material.POWERED_RAIL || block.getType() == Material.RAILS || block.getType() == Material.DETECTOR_RAIL)) { + event.setCancelled(true); + event.getPlayer().updateInventory(); + event.getItem().remove(); + event.getPlayer().sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RESET + "" + ChatColor.RED + " pickup minecarts or rails."); + } + } +} + diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiSlimeSplitListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiSlimeSplitListener.java new file mode 100644 index 0000000..d4dc484 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiSlimeSplitListener.java @@ -0,0 +1,12 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.SlimeSplitEvent; + +public class AntiSlimeSplitListener implements Listener { + @EventHandler + public void slimeSplit(SlimeSplitEvent e) { + e.setCancelled(true); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiSlowInVanishListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiSlowInVanishListener.java new file mode 100644 index 0000000..ffe47e8 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AntiSlowInVanishListener.java @@ -0,0 +1,18 @@ +package net.crankedpvp.crankedcore.listeners; + +import com.golfing8.winespigot.event.PlayerUpdateSpeedEvent; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class AntiSlowInVanishListener implements Listener { + + @EventHandler + public void walkSpeedChange(PlayerUpdateSpeedEvent event) { + if(event.getPlayer() == null) return; + if(!EssentialsUtils.isVanished(event.getPlayer())) return; + if(event.getNewSpeed() != 0.2F) { + event.setCancelled(true); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AutoFlyListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AutoFlyListener.java new file mode 100644 index 0000000..722c0cd --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/AutoFlyListener.java @@ -0,0 +1,10 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +public class AutoFlyListener implements Listener { + public void playerJoin(PlayerJoinEvent e) { + e.getPlayer().setAllowFlight(true); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/BlockCommandListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/BlockCommandListener.java new file mode 100644 index 0000000..89765ca --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/BlockCommandListener.java @@ -0,0 +1,32 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.managers.CommandBlockerManager; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.codec.language.bm.Lang; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +public class BlockCommandListener implements Listener { + + private final CommandBlockerManager commandBlockerManager; + + public BlockCommandListener() { + this.commandBlockerManager = CrankedCore.getInstance().getCommandBlockerManager(); + } + + @EventHandler + public void onCommand(PlayerCommandPreprocessEvent event) { + if (event.isCancelled()) return; + if (commandBlockerManager.isBlocked(event.getMessage().replace("/", "").split(" ")[0])) { + if (event.getPlayer().hasPermission("cranked.admin")) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c &7&n" + event.getMessage() + "&c is a blocked command but since you are &7OP'ed&c you have bypassed the blocker! ")); + return; + } + event.getPlayer().sendMessage(CC.translate(Language.BLOCKED_COMMAND.getMessage().replace("%command%", event.getMessage()))); + event.setCancelled(true); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ChatListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ChatListener.java new file mode 100644 index 0000000..b2274c1 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ChatListener.java @@ -0,0 +1,225 @@ +package net.crankedpvp.crankedcore.listeners; + +import com.earth2me.essentials.utils.DateUtil; +import com.golfing8.kore.FactionsKore; +import com.golfing8.kore.feature.ShieldFeature; +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.struct.ChatMode; +import net.crankedpvp.chattitles.ChatTitlesAPI; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.cooldowns.ChatCooldown; +import net.crankedpvp.crankedcore.data.CrankedUserManager; +import net.crankedpvp.crankedcore.managers.StaffChatManager; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.managers.GhostMuteManager; +import net.luckperms.api.LuckPermsProvider; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ChatListener implements Listener { + + private final Pattern ipPattern = Pattern.compile("((? getRecepients(AsyncPlayerChatEvent event) { + Set recipients = new HashSet<>(); + if(StaffPlugin.getInstance().getGhostMuteManager().isPlayerInGhostMute(event.getPlayer())) { + recipients.add(event.getPlayer()); + for(Player recipient : event.getRecipients()) { + if(recipient.hasPermission("ghostmute.see")) { + recipients.add(recipient); + } + } + return recipients; + } + return event.getRecipients(); + + } + + // Chat Filter + @EventHandler(priority = EventPriority.HIGH) + public void playerChat(AsyncPlayerChatEvent event) { + if (event.isCancelled()) return; + + event.setCancelled(true); + + Set recipients = getRecepients(event); + Player player = event.getPlayer(); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + + + if (fPlayer.getChatMode() != ChatMode.PUBLIC) return; + + if (staffChatManager.getInStaffChat().contains(event.getPlayer())) { + staffChatManager.sendStaffMessage(event.getPlayer(), event.getMessage()); + return; + } + + if (CooldownUtils.isCooldownActive(player, "chatCooldown")) { + player.sendMessage(CC.translate("&c&l(!)&c You cannot send messages for another " + CooldownUtils.getFormattedCooldown(player, "chatCooldown") + ".")); + return; + } + + if (!player.isOp()) { + CooldownUtils.registerCooldown(player, new ChatCooldown("chatCooldown", 1)); + } + + + Faction faction = fPlayer.getFaction(); + + //Check if chat is disable +/* if (ChatFilter.isChatHalted() && !player.isOp()) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You cannot use chat while chat is halted.")); + return; + }*/ + + if (event.getMessage().contains("[item]") && event.getMessage().contains("[brag]")) return; + + Matcher ipMatcher = ipPattern.matcher(event.getMessage()); + + if (ipMatcher.find() && !player.isOp()) { + player.sendMessage(CC.translate("&c&l(!)&c You are not allowed to send ip's in chat!")); + staffChatManager.sendStaffMessage(CC.translate("&c" + player.getName() + " &ctried sending an ip in chat &7(" + event.getMessage() + "&7)")); + return; + } + + Matcher webMatcher = webpattern.matcher(event.getMessage()); + + if (webMatcher.find() && !player.isOp()) { + player.sendMessage(CC.translate("&c&l(!)&c You are not allowed to send links in chat!")); + staffChatManager.sendStaffMessage(CC.translate("&c" + player.getName() + " &ctried sending a link in chat &7(" + event.getMessage() + "&7)")); + return; + } + + + String message = event.getMessage(); + + for (Player recipient : recipients) { + + message = event.getMessage(); + + FPlayer fRecipient = FPlayers.getInstance().getByPlayer(recipient); + Faction recipientFaction = fRecipient.getFaction(); + + Clickable clickable = new Clickable(""); + if(ghostMuteManager != null && ghostMuteManager.isPlayerInGhostMute(player) && !player.getUniqueId().equals(recipient.getUniqueId())) { + clickable.add("&b&l[GM] "); + } + String nitroLeader = getNitroLeader(player); + + clickable.add(nitroLeader); + + if (!faction.isWilderness()) { + String shieldStatus; + if (shieldFeature.isShieldActive(faction.getId()) && shieldFeature.isSetup(faction.getId()) && shieldFeature.isTimeConfigured(faction.getId())) { + shieldStatus = "&aON &7(" + ChatColor.stripColor(shieldFeature.getShieldData(faction.getId(), true)) + "&7)"; + } else { + shieldStatus = "&cOFF"; + } + + clickable.add( "&8[" + faction.getRelationTo(recipientFaction).getColor() + fPlayer.getChatTag() + "&8]&r ", + "&4&lFaction Info: &f" + faction.getTag() + " \n" + + "&8 • &cPower: &a" + (int) faction.getPower() + "&8/&a" + (int) faction.getPowerMax() + " \n" + + "&8 • &cShield: &f" + shieldStatus + "\n" + + "&8 • &cOnline: &f" + faction.getOnlinePlayers().size() + " \n" + + "&8 • &cFtop: &f#" + SpawnerPlugin.getInstance().getFactionsTopManager().getFactionTop(faction) + " \n" + " \n" + + "&7&oClick to view this faction", + "/f who " + player.getName() + ); + } + + + clickable.add(Objects.requireNonNull(LuckPermsProvider.get().getUserManager().getUser(player.getUniqueId())).getCachedData().getMetaData().getPrefix() + " " + player.getName(), + "&4&lUser: &f" + player.getName() + " \n" + + "&8 • &cNick: &f" + player.getDisplayName() + " \n" + + "&8 • &cFaction: &f" +faction.getTag() + " \n" + + "&8 • &cLunar Client: &f" + (LunarClientAPI.getInstance().isRunningLunarClient(player) ? ChatColor.GREEN.toString() + ChatColor.BOLD + "✓" : ChatColor.RED.toString() + ChatColor.BOLD + "✗") + " \n" + + "&8 • &cBalance: &a$" + NumberUtils.formatMoney(EconomyUtils.getBalance(player)) + " \n" + + "&8 • &cLogged in: &f" + DateUtil.formatDateDiff(EssentialsUtils.getEssentials().getUser(player).getLastLogin()) + " ago" + " \n" + " \n" + + "&7&oClick to see when the player logged online", + "/stats " + player.getName() + ); + + if(ChatTitlesAPI.playerHasTitleEquipped(player)) { + clickable.add(" &8[" + ChatTitlesAPI.getEquippedTitle(player) + "&r&8]"); + } + + + + ChatColor chatcolor = crankedUserManager.getCrankedUser(player.getUniqueId()).getChatColor(); + + clickable.add("&8 » "); + + + if (message.contains("[item]") || message.contains("[ITEM]")) { + ItemStack itemStack = event.getPlayer().getItemInHand(); + if (itemStack == null || !itemStack.hasItemMeta() || itemStack.getType() == Material.AIR) { + player.sendMessage(CC.translate("&c&l(!)&c Please hold an item when using [item]")); + return; + } else { + String name = itemStack.getItemMeta().getDisplayName(); + int amount = itemStack.getAmount(); + clickable.addItem(CC.translate("&f» " + name + " &7(" + amount + "x) &f« "), itemStack); + } + message = message.replace("[item]", "").replace("[ITEM]", ""); + } + + + if (message.contains("[brag]") || message.contains("[BRAG]")) { + String playerName = event.getPlayer().getName(); + clickable.add(String.format("&d&o%s's Inventory", playerName), String.format("&7View %s's Inventory", playerName), "/invsee " + playerName); + message = message.replace("[brag]", "").replace("[BRAG]", ""); + } + + + clickable.add(chatcolor + message); + clickable.sendToPlayer(recipient); + } + Bukkit.getServer().getConsoleSender().sendMessage(CC.translate("&8[&a" + fPlayer.getChatTag() + "&8]&r " + Objects.requireNonNull(LuckPermsProvider.get().getUserManager().getUser(player.getUniqueId())).getCachedData().getMetaData().getPrefix() + " " + player.getName() + " " + message)); + } + + + + public String getNitroLeader(Player player) { + String prefix = ""; + if (net.crankedpvp.discordsync.listeners.ChatListener.isNitroBooster(player)) { + prefix += net.crankedpvp.discordsync.listeners.ChatListener.BOOSTER_BADGE; + } + if (net.crankedpvp.discordsync.listeners.ChatListener.isFactionLeader(player)) { + prefix += net.crankedpvp.discordsync.listeners.ChatListener.LEADER_BADGE; + } + if (!prefix.equals("")) { + prefix = "&8<" + prefix + "&8> "; + } + return prefix; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/CrystalListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/CrystalListener.java new file mode 100644 index 0000000..575136c --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/CrystalListener.java @@ -0,0 +1,62 @@ +package net.crankedpvp.crankedcore.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class CrystalListener implements Listener { + + public boolean isCrystal(ItemStack itemStack) { + if (itemStack.getType() != Material.PRISMARINE_CRYSTALS) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if (!nbtItem.hasNBTData()) return false; + return nbtItem.getString("extinctCustomItem").equals("enchantShard"); + } + + public Enchantment getCrystalEnchant(ItemStack crystal) { + if (!isCrystal(crystal)) return null; + NBTItem nbtItem = new NBTItem(crystal); + return Enchantment.getByName(nbtItem.getString("shardEnchant")); + } + + public int getCrystalEnchantLevel(ItemStack crystal) { + if (!isCrystal(crystal)) return -1; + NBTItem nbtItem = new NBTItem(crystal); + return nbtItem.getInteger("shardLevel"); + } + + public ItemStack applyCrystalEnchant(ItemStack crystal, ItemStack itemStack) { + if (!isCrystal(crystal)) return null; + Enchantment enchantment = getCrystalEnchant(crystal); + int enchantmentLevel = getCrystalEnchantLevel(crystal); + if (enchantment == null || enchantmentLevel == -1) return null; + if (!enchantment.canEnchantItem(itemStack)) return null; + itemStack.addUnsafeEnchantment(enchantment, enchantmentLevel); + return itemStack; + } + + @SuppressWarnings("Deprecated") + @EventHandler + public void onShardApply(InventoryClickEvent e) { + if (e.getCurrentItem() == null || e.getCurrentItem().getType() == Material.AIR) return; + if (!isCrystal(e.getCursor())) return; + ItemStack crystal = e.getCursor(); + ItemStack itemStack = e.getCurrentItem(); + int crystalAmount = crystal.getAmount(); + if (itemStack.getAmount() > 1) return; + ItemStack enchantedItemStack = applyCrystalEnchant(crystal, itemStack); + if (enchantedItemStack == null) return; + e.setCancelled(true); + e.setCurrentItem(enchantedItemStack); + if (crystalAmount > 1) { + crystal.setAmount(crystalAmount - 1); + e.setCursor(crystal); + return; + } + e.setCursor(null); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/EnderPearlCooldownListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/EnderPearlCooldownListener.java new file mode 100644 index 0000000..6866417 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/EnderPearlCooldownListener.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.cooldowns.EnderPearlCooldown; +import net.crankedpvp.crankedutils.events.EnderPearlThrowEvent; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class EnderPearlCooldownListener implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onEnderpearlThrow(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (ItemUtils.isAirOrNull(event.getItem())) return; + if (event.getItem().getType() != Material.ENDER_PEARL) return; + if (event.getPlayer() == null) return; + Player player = event.getPlayer(); + EnderPearlThrowEvent enderPearlThrowEvent = new EnderPearlThrowEvent(player, 15); + Bukkit.getPluginManager().callEvent(enderPearlThrowEvent); + + if (CooldownUtils.isCooldownActive(player, EnderPearlCooldown.ENDERPEARL_COOLDOWN_KEY)) { + event.setCancelled(true); + player.setItemInHand(player.getItemInHand()); + player.sendMessage(CC.translate("&b&lPearls &8➥ &7You can't use an enderpearl for another &f" + CooldownUtils.getFormattedCooldown(player, EnderPearlCooldown.ENDERPEARL_COOLDOWN_KEY) + "&7!")); + return; + } + + CooldownUtils.registerCooldown(player, new EnderPearlCooldown(enderPearlThrowEvent.getCooldownInSeconds())); + } +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/EnderpearlStackListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/EnderpearlStackListener.java new file mode 100644 index 0000000..3c782bd --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/EnderpearlStackListener.java @@ -0,0 +1,32 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class EnderpearlStackListener implements Listener { + + + @EventHandler + public void onInventoryClickWithEnderpearl(InventoryClickEvent event) { + if (ItemUtils.isAirOrNull(event.getCursor())) return; + if (ItemUtils.isAirOrNull(event.getCurrentItem())) return; + + ItemStack cursor = event.getCursor(); + ItemStack current = event.getCurrentItem(); + + if (current.hasItemMeta()) return; + if (cursor.hasItemMeta()) return; + + if (cursor.getType() != Material.ENDER_PEARL) return; + if (current.getType() != Material.ENDER_PEARL) return; + + event.setCancelled(true); + + event.setCursor(null); + event.setCurrentItem(new ItemStack(Material.ENDER_PEARL, current.getAmount() + cursor.getAmount())); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ExpBottleListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ExpBottleListener.java new file mode 100644 index 0000000..3b8054a --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ExpBottleListener.java @@ -0,0 +1,35 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.utils.ExpBottleAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.XPUtils; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +public class ExpBottleListener + implements Listener { + + @EventHandler(priority = EventPriority.LOW) + public void onExpBottleUse(PlayerInteractEvent e) { + if (e.hasItem() && ExpBottleAPI.isXpBottle(e.getItem())) { + Player p = e.getPlayer(); + int xpValue = ExpBottleAPI.getXpAmount(e.getItem()) * e.getItem().getAmount(); + e.setCancelled(true); + p.setItemInHand(null); + XPUtils.addExperience(p, xpValue); + p.playSound(p.getLocation(), Sound.GLASS, 1.0f, 0.8f); + p.sendMessage(CC.translate(Language.EXP_BOTTLE_DEPOSIT.getMessage().replace("%amount%", NumberUtils.formatMoney(xpValue)))); + } + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/FirstJoinListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/FirstJoinListener.java new file mode 100644 index 0000000..92c451b --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/FirstJoinListener.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +public class FirstJoinListener implements Listener { + + private CrankedCore plugin; + public FirstJoinListener(CrankedCore plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onJoin(PlayerJoinEvent event) { + if(event.getPlayer() == null) return; + if(event.getPlayer().hasPlayedBefore()) return; + if(this.plugin.getCrankedUserManager().containsKey(event.getPlayer().getUniqueId().toString())) return; + CrankedLootboxes.getInstance().getLootboxManager().giveLootbox(event.getPlayer(), CrankedLootboxes.getInstance().getLootboxRegister().getLootbox("StarterBundle"), 1); + Bukkit.getScheduler().runTaskLater(CrankedCore.getInstance(), ()-> { + event.getPlayer().teleport(EssentialsUtils.getEssentials().getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + }, 3L); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/GoldenAppleSicknessListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/GoldenAppleSicknessListener.java new file mode 100644 index 0000000..69e3c3c --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/GoldenAppleSicknessListener.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.struct.cooldowns.GoldenAppleCooldown; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerItemConsumeEvent; + +public class GoldenAppleSicknessListener implements Listener { + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerConsumeGoldenApple(PlayerItemConsumeEvent event) { + Player player = event.getPlayer(); + if (event.getItem().getType() == Material.GOLDEN_APPLE || event.getItem().getTypeId() == 322) { + int cooldown = Integer.parseInt(Language.golden_apple_cooldown.getValue()); + if (CooldownUtils.isCooldownActive(player, "goldenAppleSickness")) { + player.sendMessage(CC.translate(Language.GOLDEN_APPLE_COOLDOWN.getMessage().replace("%time%", CooldownUtils.getFormattedCooldown(player, "goldenAppleSickness")))); + event.setCancelled(true); + } else { + CooldownUtils.registerCooldown(player, new GoldenAppleCooldown("goldenAppleSickness", cooldown)); + player.sendMessage(CC.translate(Language.GOLDEN_APPLE_ENTERED_COOLDOWN.getMessage().replace("%cooldown%", Integer.toString(cooldown)))); + + } + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/KillTitleMessageListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/KillTitleMessageListener.java new file mode 100644 index 0000000..c4cbef0 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/KillTitleMessageListener.java @@ -0,0 +1,78 @@ +package net.crankedpvp.crankedcore.listeners; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.HoverText; +import net.crankedpvp.crankedutils.utils.*; +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class KillTitleMessageListener implements Listener { + + private List killCooldown; + + public KillTitleMessageListener() { + this.killCooldown = new ArrayList<>(); + } + + @EventHandler + public void killMsg(EntityDeathEvent e) throws NoSuchFieldException, IllegalAccessException { + if (e.getEntity() instanceof Player && e.getEntity().getKiller() != null) { + Player killer = e.getEntity().getKiller(); + Player died = (Player) e.getEntity(); + final UUID kuuid = killer.getUniqueId(); + + if (this.killCooldown.contains(kuuid)) return; + this.killCooldown.add(kuuid); + Bukkit.getScheduler().runTaskLaterAsynchronously(CrankedCore.getInstance(), () -> { + this.killCooldown.remove(kuuid); + }, 5 * 20L); + JSONMessage message = new JSONMessage("", ChatColor.GRAY); + FPlayer fkiller = FPlayers.getInstance().getByPlayer(killer); + FPlayer fdied = FPlayers.getInstance().getByPlayer(died); + + message.addText(CC.translate("&c" + killer.getName() + "&4[" + fkiller.getKills() + "&4]&e killed &c" + died.getName() + "&4[" + fdied.getKills() + "&4]" + " &eusing ")); + if (killer.getItemInHand() == null || killer.getItemInHand().getType() == Material.AIR) { + message.addText(this.getFormattedName(null)); + } else { + message.addItem(killer.getItemInHand(), HoverText.formatColors(ChatColor.WHITE + this.getFormattedName(killer.getItemInHand())).getText()); + } + for (Player player : Bukkit.getOnlinePlayers()) { + message.sendToPlayer(player); + + } + AnimationUtils.sendDeathEffect(died); + AnimationUtils.sendLightning(killer, died.getLocation()); + if (CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(killer.getUniqueId()).isKillTitleEnabled()) { + TitleUtils.sendTitle(killer, CC.translate("&a&l+1 KILL"), LuckpermUtils.getDisplayName(died), 20, 50, 20); + } + } + } + + private String getFormattedName(ItemStack hand) { + if (hand == null || hand.getType() == Material.AIR) { + return "their fists!"; + } + if (hand.hasItemMeta() && hand.getItemMeta().hasDisplayName()) { + return hand.getItemMeta().getDisplayName(); + } + if (hand.getType() == Material.TNT) { + return "TNT"; + } + return StringUtils.capitaliseAllWords(hand.getType().name().toLowerCase().replace("_", " ")); + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/LastHitListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/LastHitListener.java new file mode 100644 index 0000000..39053f3 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/LastHitListener.java @@ -0,0 +1,22 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.data.LastHitCache; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class LastHitListener implements Listener { + + @EventHandler + public void lastHitCacheUpdate(EntityDamageByEntityEvent event) { + if(event.getEntity() == null || event.getDamager() == null) return; + if(!(event.getEntity() instanceof Player)) return; + if(!(event.getDamager() instanceof Player)) return; + + Player entity = (Player) event.getEntity(); + Player damager = (Player) event.getDamager(); + + LastHitCache.lastHitMapVictimAttacker.put(entity, damager); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/LuckpermsRankFixListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/LuckpermsRankFixListener.java new file mode 100644 index 0000000..a4b90cf --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/LuckpermsRankFixListener.java @@ -0,0 +1,47 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.luckperms.api.model.user.User; +import net.luckperms.api.node.NodeType; +import net.luckperms.api.node.types.InheritanceNode; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +import java.util.List; +import java.util.stream.Collectors; + +public class LuckpermsRankFixListener implements Listener { + @EventHandler + public void onJoin(PlayerJoinEvent event) { + User user = LuckpermUtils.getLpUser(event.getPlayer()); + List ranks = user.getNodes(NodeType.INHERITANCE).stream() + .map(InheritanceNode::getGroupName) + .collect(Collectors.toList()); + + if (ranks.contains("member") && !event.getPlayer().hasPermission("crankedcore.staffchat")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + user.getUniqueId() + " parent set explorer"); + } + if (ranks.contains("gunner") && !event.getPlayer().hasPermission("crankedcore.staffchat")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + user.getUniqueId() + " parent set corrupt"); + } + if (ranks.contains("quartermaster") && !event.getPlayer().hasPermission("crankedcore.staffchat")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + user.getUniqueId() + " parent set medusa"); + } + if (ranks.contains("captain") && !event.getPlayer().hasPermission("crankedcore.staffchat")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + user.getUniqueId() + " parent set dracula"); + } + if (ranks.contains("kraken") && !event.getPlayer().hasPermission("crankedcore.staffchat")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + user.getUniqueId() + " parent set satan"); + } + if (ranks.contains("kraken+") && !event.getPlayer().hasPermission("crankedcore.staffchat")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + user.getUniqueId() + " parent set satan"); + } + if (ranks.contains("youtube") && !event.getPlayer().hasPermission("crankedcore.staffchat")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + user.getUniqueId() + " parent set media"); + } + + } +} + diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/MOTDListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/MOTDListener.java new file mode 100644 index 0000000..3fb922f --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/MOTDListener.java @@ -0,0 +1,24 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +public class MOTDListener implements Listener { + @EventHandler + public void onJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + Bukkit.getScheduler().runTaskLaterAsynchronously(CrankedCore.getInstance(), ()-> { + for (String line : Language.MOTD.getValuesAsList()) { + line = line.replace("{player}", player.getDisplayName()); + line = line.replace("{online}", String.valueOf(Bukkit.getOnlinePlayers().size())); + player.sendMessage(CC.translate(line)); + } + }, 10L); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/MoneyNoteListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/MoneyNoteListener.java new file mode 100644 index 0000000..19827b2 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/MoneyNoteListener.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedcore.utils.MoneyNotesAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class MoneyNoteListener implements Listener { + + @EventHandler(priority = EventPriority.LOW) + public void onMoneyNoteUse(PlayerInteractEvent e) { + if (e.hasItem() && MoneyNotesAPI.isMoneyNote(e.getItem())) { + Player p = e.getPlayer(); + e.setCancelled(true); + ItemStack itemStack = e.getItem(); + //double moneyValue = MoneyNotesAPI.getMoneyAmount(e.getItem()) * e.getItem().getAmount(); + p.setItemInHand(null); + double worth = MoneyNotesAPI.getMoneyAmount(e.getItem()); + + for(int i = 0; i < itemStack.getAmount(); i++) { + EconomyUtils.depositBalance(p, worth); + } + p.playSound(p.getLocation(), Sound.ORB_PICKUP, 1.0f, 1.2f); + p.sendMessage(CC.translate(Language.NOTE_DEPOSIT.getMessage() + .replace("%money%", NumberUtils.formatMoney(worth)) + .replace("%amount%", String.valueOf(itemStack.getAmount())))); + } + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherDamageListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherDamageListener.java new file mode 100644 index 0000000..6bd4ede --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherDamageListener.java @@ -0,0 +1,23 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.utils.ConfigManager; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class NetherDamageListener implements Listener { + @EventHandler + public void increaseDamage(EntityDamageByEntityEvent event) { + if (event.isCancelled() || event.getDamage() <=0) return; + if (event.getDamager() instanceof Player && event.getEntity() instanceof Player) { + if (event.getDamager().getLocation().getWorld().getName().equals("world_nether")) { + double buff = CrankedCore.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.SETTINGS).getDouble("nether-increase-amount-percent"); + CrankedUtils.getInstance().getDamageHandler().increaseDamage(buff, event, "NetherBuff"); + } + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherJoinListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherJoinListener.java new file mode 100644 index 0000000..ef8fd2b --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherJoinListener.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +public class NetherJoinListener implements Listener { + @EventHandler + public void onJoin(PlayerJoinEvent event) { + if (event.getPlayer().getWorld().getName().equals("world_nether") && WorldGuardUtils.canPvPInRegion(event.getPlayer()) && !event.getPlayer().hasPermission("cranked.staff")) { + event.getPlayer().teleport(Bukkit.getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + event.getPlayer().sendMessage(CC.translate("&c&l(!) &cYou have been force teleported to spawn due to logging out in the nether warzone.")); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherPvpListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherPvpListener.java new file mode 100644 index 0000000..4a6cada --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NetherPvpListener.java @@ -0,0 +1,104 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.collect.CollectPlugin; +import net.crankedpvp.collect.struct.CollectCategory; +import net.crankedpvp.collect.struct.CollectType; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.struct.netherpvp.NetherPvPQueueManager; +import net.crankedpvp.crankedcore.utils.ConfigManager; +import net.crankedpvp.crankedutils.events.PlayerCombatEnterEvent; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.*; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class NetherPvpListener implements Listener { + + private final CrankedCore plugin; + private final NetherPvPQueueManager netherPvPQueueManager; + private final ConfigManager configManager; + + public NetherPvpListener(CrankedCore plugin) { + this.plugin = plugin; + this.netherPvPQueueManager = this.plugin.getNetherPvPQueueManager(); + this.configManager = this.plugin.getConfigManager(); + } + + @EventHandler + public void onCombatEnter(PlayerCombatEnterEvent event) { + if (!this.netherPvPQueueManager.isPlayerInPvPQueue(event.getPlayer())) return; + this.netherPvPQueueManager.removePlayerFromPvpQueue(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerCommand(PlayerCommandPreprocessEvent event) { + if (!this.netherPvPQueueManager.isPlayerInArena(event.getPlayer())) return; + FileConfiguration config = this.configManager.getAbstractConfig(ConfigManager.ConfigFile.SETTINGS).getConfig(); + ConfigurationSection netherpvpConfigurationSection = config.getConfigurationSection("nether-pvp"); + List allowedCommands = netherpvpConfigurationSection.getStringList("allowed-commands"); + String cmd = event.getMessage().toLowerCase().replace("/", ""); + Player player = event.getPlayer(); + if (!allowedCommands.contains(cmd)) { + player.sendMessage(CC.translate("&cYou cannot execute this command in a nether pvp duel")); + event.setCancelled(true); + } + } + @EventHandler + public void onDropItemInNetherPvP(PlayerDropItemEvent event) { + if (!this.netherPvPQueueManager.isPlayerInArena(event.getPlayer())) return; + event.setCancelled(true); + } + + @EventHandler + public void onTeleport(PlayerTeleportEvent event) { + if (!this.netherPvPQueueManager.isPlayerInArena(event.getPlayer())) return; + if (event.getTo().getWorld().getName().equals("world_nether")) return; + event.getPlayer().sendMessage(CC.translate("&cYou cannot teleport during a pvp match")); + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDeathInNetherPvp(PlayerDeathEvent event) { + if (!this.netherPvPQueueManager.isPlayerInArena(event.getEntity())) return; + Player killer = this.netherPvPQueueManager.getOposingPlayer(event.getEntity()); + if (killer == null) return; + if (!event.getDrops().isEmpty()) { + CollectPlugin.getInstance().getCollectManager().getOrCreate(killer.getUniqueId().toString()) + .add(new CollectCategory(CollectType.NETHER_PVP, event.getDrops().toArray(new ItemStack[event.getDrops().size() - 1]), CC.RedB + event.getEntity().getName() + "'s NetherPvP Items", System.currentTimeMillis())); + event.getDrops().clear(); + } + this.netherPvPQueueManager.endMatch(killer, event.getEntity()); + } + + @EventHandler + public void onPlayerLeaveWhileWaiting(PlayerQuitEvent event) { + if (!this.netherPvPQueueManager.isPlayerInPvPQueue(event.getPlayer())) return; + this.netherPvPQueueManager.removePlayerFromPvpQueue(event.getPlayer()); + } + + @EventHandler + public void onPlayerKickedWhileWaiting(PlayerKickEvent event) { + if (!this.netherPvPQueueManager.isPlayerInPvPQueue(event.getPlayer())) return; + this.netherPvPQueueManager.removePlayerFromPvpQueue(event.getPlayer()); + } + + @EventHandler + public void onPlayerLeave(PlayerQuitEvent event) { + if (!this.netherPvPQueueManager.isPlayerInArena(event.getPlayer())) return; + event.getPlayer().setHealth(0); + } + + @EventHandler + public void onPlayerKicked(PlayerKickEvent event) { + if (!this.netherPvPQueueManager.isPlayerInArena(event.getPlayer())) return; + event.getPlayer().setHealth(0); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NoHungerListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NoHungerListener.java new file mode 100644 index 0000000..7470d67 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/NoHungerListener.java @@ -0,0 +1,15 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.FoodLevelChangeEvent; + +public class NoHungerListener implements Listener { + @EventHandler + public void onLoseHunger(FoodLevelChangeEvent e) { + if (e.getEntity() instanceof Player) { + e.setCancelled(true); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ProtectLootListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ProtectLootListener.java new file mode 100644 index 0000000..c4ce969 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ProtectLootListener.java @@ -0,0 +1,92 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.cooldowns.LootProtectCooldown; +import net.crankedpvp.crankedcore.data.LastHitCache; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.Pair; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +public class ProtectLootListener implements Listener { + + private static final int PICKUP_DELAY = 60; + + private final CrankedCore plugin; + private final HashMap> protectedLoot = new HashMap<>(); + + public ProtectLootListener(CrankedCore plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerDeath(PlayerDeathEvent event) { + if (event.getDrops().size() == 0) return; + + Player victim = event.getEntity(); + Player killer = victim.getKiller(); + + if (killer == null) { + if(!LastHitCache.lastHitMapVictimAttacker.containsKey(victim)) return; + killer = LastHitCache.lastHitMapVictimAttacker.get(victim); + } + + UUID uuid = killer.getUniqueId(); + List items = new ArrayList<>(); + + for (ItemStack drop : event.getDrops()) { + Item item = victim.getWorld().dropItemNaturally(victim.getLocation(), drop); + protectedLoot.put(item, new Pair<>(uuid, System.currentTimeMillis())); + items.add(item); + } + + event.getDrops().clear(); + killer.sendMessage(CC.translate("&6&lLoot Protection &8➥ &eThe player &f" + event.getEntity().getName() + "'s &7loot is protected for 60 seconds!")); + //Language.LOOTPROTECT_STARTED.send(killer, str -> str.replace("%victim%", victim.getName()).replace("%seconds%", String.valueOf(pickupDelay / 20))); + + Player finalKiller = killer; + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> { + items.forEach(protectedLoot::remove); + finalKiller.sendMessage(CC.translate("&6&lLoot Protection &8➥ &7The player &f" + event.getEntity().getName() + "'s &7loot is no longer protected!")); + }, PICKUP_DELAY * 20L); + } + + @EventHandler + public void onPickup(PlayerPickupItemEvent event) { + if (!protectedLoot.containsKey(event.getItem())) return; + if(event.isCancelled()) return; + + Pair itemUuidAndTimeLeft = protectedLoot.get(event.getItem()); + + if (itemUuidAndTimeLeft.getLeft().equals(event.getPlayer().getUniqueId())) { + protectedLoot.remove(event.getItem()); + return; + } + + long timeLeft = ((itemUuidAndTimeLeft.getRight() + PICKUP_DELAY * 1000) - System.currentTimeMillis()); + timeLeft = timeLeft / 1000; + + if(timeLeft <= 0) { + protectedLoot.remove(event.getItem()); + return; + } + + event.setCancelled(true); + if (CooldownUtils.isCooldownActive(event.getPlayer(), "lootprotect-pickup-notify")) return; + CooldownUtils.registerCooldown(event.getPlayer(), new LootProtectCooldown("lootprotect-pickup-notify", 3)); + event.getPlayer().sendMessage(CC.translate("&6&lLoot Protection &8➥ &7You cannot pick this item up for &f" + timeLeft + "s&7!")); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ResetSpeedOnJoinListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ResetSpeedOnJoinListener.java new file mode 100644 index 0000000..2183e49 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ResetSpeedOnJoinListener.java @@ -0,0 +1,14 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +public class ResetSpeedOnJoinListener implements Listener { + + @EventHandler + public void onJoinResetSpeed(PlayerJoinEvent event) { + event.getPlayer().setWalkSpeed(0.2f); + event.getPlayer().setFlySpeed(0.2f); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ServerStatsListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ServerStatsListener.java new file mode 100644 index 0000000..4caad75 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/ServerStatsListener.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedcore.listeners; + +import com.earth2me.essentials.utils.DateUtil; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +import java.lang.management.ManagementFactory; +import java.text.DecimalFormat; + +public class ServerStatsListener implements Listener { + public final DecimalFormat df = new DecimalFormat("#.#"); + + @EventHandler(priority = EventPriority.LOWEST) + public void pingCommand(PlayerCommandPreprocessEvent e) { + Player player = e.getPlayer(); + int ping = PlayerUtils.getSpoofedPing(player); + String tps = df.format(EssentialsUtils.getEssentials().getTimer().getAverageTPS()); + if (e.getMessage().equalsIgnoreCase("/ping") || e.getMessage().equalsIgnoreCase("/tps") || e.getMessage().equalsIgnoreCase("/mem") || e.getMessage().equalsIgnoreCase("/ping") || e.getMessage().equalsIgnoreCase("/lag")) { + e.setCancelled(true); + player.sendMessage(""); + player.sendMessage(CC.translate("&c&lCranked&f&lPvP &c&lPerformance")); + player.sendMessage(CC.translate("&4&l* &cUptime: &f" + DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()))); + player.sendMessage(CC.translate("&4&l* &cServer \"TPS\": &a" + tps)); + player.sendMessage(CC.translate("&4&l* &cPing: &a" + ping + "ms")); + player.sendMessage(""); + + } + + } + + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/SmoothKnockbackListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/SmoothKnockbackListener.java new file mode 100644 index 0000000..c0a5316 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/SmoothKnockbackListener.java @@ -0,0 +1,16 @@ +package net.crankedpvp.crankedcore.listeners; + +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +public class SmoothKnockbackListener implements Listener { + public class KnockbackFixListener implements Listener { + @EventHandler + public void onJoin(PlayerJoinEvent event) { + ((CraftPlayer)event.getPlayer()).setMaximumNoDamageTicks(19); + } + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarpAliasListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarpAliasListener.java new file mode 100644 index 0000000..c115115 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarpAliasListener.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +import java.util.ArrayList; +import java.util.List; + +public class WarpAliasListener implements Listener { + private List ignored; + + public WarpAliasListener() { + this.ignored = new ArrayList<>(); + ignored.add("koth"); + ignored.add("arcade"); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerPreProcessCommand(PlayerCommandPreprocessEvent e) { + for (String warp : EssentialsUtils.getEssentials().getWarps().getList()) { + if (Bukkit.getCommandAliases().containsKey(e.getMessage().replace("/", ""))) { + return; + } + + + if (!e.getMessage().toLowerCase().equals("/" + warp.toLowerCase())) continue; + if (ignored.contains(warp.toLowerCase())) continue; + e.setMessage("/warp " + warp); + } + } +} + diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarpCommandListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarpCommandListener.java new file mode 100644 index 0000000..2f0029b --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarpCommandListener.java @@ -0,0 +1,23 @@ +package net.crankedpvp.crankedcore.listeners; + +import net.crankedpvp.crankedcore.guis.WarpGUI; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +public class WarpCommandListener implements Listener { + @EventHandler(priority = EventPriority.LOWEST) + public void warpCMD(PlayerCommandPreprocessEvent e) { + String cmd = e.getMessage().toLowerCase(); + if (cmd.equals("/warp") || cmd.equals("/ewarp") || cmd.equals("/warps") || cmd.equals("/ewarps")) { + e.setCancelled(true); + Player p = e.getPlayer(); + WarpGUI warpGUI = new WarpGUI(p); + warpGUI.getWarpUI().open(p); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarzoneClaimListener.java b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarzoneClaimListener.java new file mode 100644 index 0000000..661bd83 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/listeners/WarzoneClaimListener.java @@ -0,0 +1,147 @@ +package net.crankedpvp.crankedcore.listeners; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.event.LandClaimEvent; +import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import net.crankedpvp.crankedcore.language.Language; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +import java.util.HashMap; +import java.util.Map; + +public class WarzoneClaimListener implements Listener { + + private Map regions; + private String warzoneRegionName; + private String claimLimiterRegionName; + + public void setWarzoneRegionName(String warzoneRegionName) { + this.warzoneRegionName = warzoneRegionName; + } + + public String getWarzoneRegionName() { + return this.warzoneRegionName; + } + + public void setClaimLimiterRegionName(String claimLimiterRegionName) { + this.claimLimiterRegionName = claimLimiterRegionName; + } + + public String getClaimLimiterRegionName() { + return this.claimLimiterRegionName; + } + + public WarzoneClaimListener() { + this.regions = new HashMap<>(); + this.regions.put("spawn_warzone", "spawnwarzoneclaimlimiter"); + this.regions.put("desert_warzone", "desertwarzoneclaimlimiter"); + this.regions.put("demonic_warzone", "demonicwarzoneclaimlimiter"); + + } + + @EventHandler + public void onLandClaim(LandClaimEvent event) { + World w = event.getLocation().getWorld(); + FLocation fl = event.getLocation(); + if (isCloseToWarzone(w.getChunkAt((int)fl.getX(), (int)fl.getZ()))) { + String rn = getFixedRegionName(); + if (!canClaim(event.getFaction(), getClaimLimiterRegionName(), Bukkit.getWorld(w.getName()))) { + String msg = Language.CLAIM_MAX_REACHED.getMessage().replace("%max%", Language.max_warzone_claims.getMessage()); + msg = msg.replace("%region%", rn); + event.getPlayer().sendMessage(CC.translate(msg)); + event.setCancelled(true); + return; + } + event.getPlayer().sendMessage(CC.translate(Language.CLAIM_OBTAINED.getMessage().replace("%region%", rn))); + event.getFaction().getOnlinePlayers().forEach(p -> { + if (p != event.getPlayer()) { + String msg = Language.CLAIM_OBTAINED_OTHER.getMessage().replace("%claimer%", event.getPlayer().getName()); + msg = msg.replace("%region%", rn); + p.sendMessage(CC.translate(msg)); + } + }); + } + } + + private boolean canClaim(Faction faction, String region, World world) { + if (faction.isWarZone()) return true; + return getClaimsInRadius(faction, region, world) < Integer.parseInt(Language.max_warzone_claims.getValue()); + } + + private int getClaimsInRadius(Faction faction, String regionName, World world) { + WorldGuardPlugin worldGaurd = WorldGuardPlugin.inst(); + RegionManager manager = worldGaurd.getRegionManager(world); + ProtectedRegion region = manager.getRegion(regionName); + BlockVector topLeft = region.getMaximumPoint(); + BlockVector bottom = region.getMinimumPoint(); + int maxChunkX = topLeft.getBlockX() >> 4; + int maxChunkZ = topLeft.getBlockZ() >> 4; + int minChunkX = bottom.getBlockX() >> 4; + int minChunkZ = bottom.getBlockZ() >> 4; + int claims = 0; + for (int x = minChunkX; x <= maxChunkX; x++) { + for (int z = minChunkZ; z <= maxChunkZ; z++) { + FLocation flocation = new FLocation(world.getName(), x, z); + Faction at = FactionUtils.getFactionAt(flocation); + if (at == faction) + claims++; + } + } + return claims; + } + + private boolean isCloseToWarzone(Chunk c) { + int x; + if (checkChunk(c)) return true; + return checkChunk(c); + } + + private boolean checkChunk(Chunk c) { + int x; + for (x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + if (x != 0 || z != 0) { + Chunk ch = c.getWorld().getChunkAt(c.getX() + x, c.getZ() + z); + Location l = ch.getBlock(8, 8, 8).getLocation(); + FLocation fl = new FLocation(l); + if (FactionUtils.getFactionAt(fl).isWarZone() && WorldGuardUtils.canPvPInRegion(l)) { + String regionName = WorldGuardUtils.getRegionName(l); + if (regionName.contains("warzone")) { + setWarzoneRegionName(regionName); + setClaimLimiterRegionName(this.regions.get(regionName)); + return true; + } + } + } + } + } + return false; + } + + private String getFixedRegionName() { + String regionName; + if (getWarzoneRegionName() != null) { + int endoff = getWarzoneRegionName().indexOf("w"); + regionName = getWarzoneRegionName().substring(0, endoff); + regionName = regionName.replace(regionName.substring(0, 1), regionName.substring(0, 1).toUpperCase()); + } else { + regionName = "UNKNOWN"; + } + if (regionName.equalsIgnoreCase("Spa")) + regionName = "Spawn"; + regionName = regionName.replace("_", ""); + return regionName; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/managers/CommandBlockerManager.java b/Core/src/main/java/net/crankedpvp/crankedcore/managers/CommandBlockerManager.java new file mode 100644 index 0000000..65260df --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/managers/CommandBlockerManager.java @@ -0,0 +1,76 @@ +package net.crankedpvp.crankedcore.managers; + +import net.crankedpvp.crankedutils.utils.CC; +import lombok.Getter; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.utils.ConfigManager; +import net.crankedpvp.crankedutils.utils.serializer.item.ItemStackSerializer; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Getter +public class CommandBlockerManager { + private List blockedCommands; + private CrankedCore plugin; + + public CommandBlockerManager(CrankedCore plugin) { + this.plugin = plugin; + this.blockedCommands = new ArrayList<>(); + } + + public void blockCommand(Player player, String command) { + command = command.toLowerCase(); + if (isBlocked(command)) { + player.sendMessage(CC.translate("&c&l(!)&c &7&n/" + command + "&c is already blocked!")); + return; + } + + blockedCommands.add(command); + player.sendMessage(CC.translate("&a&l(!)&a You have blocked &7&n/" + command + "&a!")); + } + + public void unBlockCommand(Player player, String command) { + command = command.toLowerCase(); + if (!isBlocked(command)) { + player.sendMessage(CC.translate("&c&l(!)&c &7&n/" + command + "&c is not a blocked command!")); + return; + } + + blockedCommands.remove(command); + player.sendMessage(CC.translate("&a&l(!)&a You have unblocked &7&n/" + command + "&a!")); + } + + public boolean isBlocked(String command) { + command = command.toLowerCase(); + return blockedCommands.contains(command); + } + + public void reloadConfig(CrankedCore plugin) { + this.blockedCommands.clear(); + CrankedCore.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.BLOCKED_COMMANDS).reloadConfig(); + loadCommands(plugin); + } + + public void loadCommands(CrankedCore plugin) { + ConfigManager configmanager = plugin.getConfigManager(); + FileConfiguration config = configmanager.getConfig(ConfigManager.ConfigFile.BLOCKED_COMMANDS); + this.blockedCommands.addAll(config.getStringList("blocked")); + } + + public void saveCommands(CrankedCore plugin) { + ConfigManager configmanager = plugin.getConfigManager(); + FileConfiguration config = configmanager.getConfig(ConfigManager.ConfigFile.BLOCKED_COMMANDS); + config.set("blocked", new ArrayList<>()); + config.set("blocked", this.blockedCommands); + + + CrankedCore.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.BLOCKED_COMMANDS).saveConfig(); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/managers/GiveAwayManager.java b/Core/src/main/java/net/crankedpvp/crankedcore/managers/GiveAwayManager.java new file mode 100644 index 0000000..ac72915 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/managers/GiveAwayManager.java @@ -0,0 +1,204 @@ +package net.crankedpvp.crankedcore.managers; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.struct.GiveAway; +import net.crankedpvp.crankedcore.tasks.GiveAwayTask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.Clickable; +import net.crankedpvp.crankedutils.utils.JSONMessage; +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Random; + +public class GiveAwayManager { + + public GiveAway currentGiveAway; + public CrankedCore plugin; + + public GiveAwayManager(CrankedCore plugin) { + this.plugin = plugin; + this.currentGiveAway = null; + } + + public void addFakeJoins(int amount) { + this.currentGiveAway.fakeJoins = this.currentGiveAway.fakeJoins + amount; + } + + public void startGiveAway(Player player, int winnersAmount, ItemStack prize, int timeInSeconds) { + if (this.currentGiveAway != null) { + player.sendMessage(CC.translate("&c&l(!)&c There is already a giveaway running!")); + return; + } + + if (winnersAmount < 0) { + player.sendMessage(CC.translate("&c&l(!)&c Winners must be over 0")); + return; + } + if (timeInSeconds < 60) { + player.sendMessage(CC.translate("&c&l(!)&c Time must be atleast 60 seconds")); + return; + } + + if (player.getItemInHand() == null) { + player.sendMessage(CC.translate("&c&l(!)&c Please hold the item you would like to giveaway!")); + return; + } + player.sendMessage(CC.translate("&a&l(!)&a You have started the giveaway with prize: " + player.getItemInHand().getItemMeta().getDisplayName() + " &awith &7" + winnersAmount + " &awinners and will last &7" + timeInSeconds + "s&a.")); + this.currentGiveAway = new GiveAway(winnersAmount, prize, timeInSeconds); + this.currentGiveAway.setGiveAwayTaskId(Bukkit.getScheduler().scheduleSyncRepeatingTask(CrankedCore.getInstance(), new GiveAwayTask(), 0L, 20L)); + announceStart(this.currentGiveAway); + + } + + public void cancelGiveAway(Player player) { + if (this.currentGiveAway != null) { + Bukkit.getScheduler().cancelTask(this.currentGiveAway.giveAwayTaskId); + this.currentGiveAway = null; + player.sendMessage(CC.translate("&a&l(!)&a Giveaway has been cancelled!")); + } else { + player.sendMessage(CC.translate("&c&l(!)&c There is currently no giveaway running!")); + } + } + + public void joinGiveAway(Player player) { + if (this.currentGiveAway == null) { + player.sendMessage(CC.translate("&c&l(!)&c There is currently no giveaway running!")); + return; + } + if (this.currentGiveAway.playersJoined.contains(player.getUniqueId())) { + player.sendMessage(CC.translate("&c&l(!)&c You have already joined this giveaway!")); + return; + } + + this.currentGiveAway.playersJoined.add(player.getUniqueId()); + player.sendMessage(CC.translate("&a&l(!)&a You have successfully joined the giveaway")); + } + + public void endGiveAway() { + if (this.currentGiveAway != null) { + GiveAway giveAway = this.currentGiveAway; + if (giveAway.getPlayersJoined().isEmpty()) { + Bukkit.broadcastMessage(CC.translate("&c&l(!)&c No one has entered the giveaway!")); + return; + } + List winners = selectWinner(giveAway.getWinnersAmount()); + announceWinners(winners, giveAway); + for (Player winner : winners) { + winner.getInventory().addItem(giveAway.getPrize()); + winner.sendMessage(CC.translate("&a&l(!)&a Congratulations, you have won the giveaway that had a total of &7" + this.getAmountOfPlayersInGiveaway() + " &aentries!")); + } + this.currentGiveAway = null; + } + } + + public List selectWinner(int amountWinners) { + Random rand = new Random(); + List winners = new ArrayList<>(); + + while(winners.size() < amountWinners) { + int randomIndex = rand.nextInt(this.currentGiveAway.playersJoined.size()); + Player player = Bukkit.getPlayer(this.currentGiveAway.playersJoined.get(randomIndex)); + if(player != null && player.isOnline() && !winners.contains(player)) winners.add(player); + } + + return winners; + } + + private String getFormattedName(ItemStack hand) { + if (hand == null || hand.getType() == Material.AIR) { + return "their fists!"; + } + if (hand.hasItemMeta() && hand.getItemMeta().hasDisplayName()) { + return hand.getItemMeta().getDisplayName(); + } + if (hand.getType() == Material.TNT) { + return "TNT"; + } + return StringUtils.capitaliseAllWords(hand.getType().name().toLowerCase().replace("_", " ")); + } + + public void announce(int seconds, GiveAway giveAway) { + JSONMessage message = new JSONMessage("", ChatColor.GRAY); + message.addText(CC.translate("&c&l * &cPrize: &f")); + message.addItem(this.currentGiveAway.getPrize(), CC.translate(ChatColor.WHITE + this.getFormattedName(this.currentGiveAway.getPrize()))); + Clickable clickable = new Clickable(""); + clickable.add(CC.translate("&7[Click here to join the giveaway]"), CC.translate("&7/giveaway join"), "/giveaway join"); + Bukkit.broadcastMessage(""); + Bukkit.broadcastMessage(CC.translate("&c&lCranked Giveaway Countdown")); + Bukkit.broadcastMessage(CC.translate("&c&l * &cTime Left: &f" + seconds + "s")); + Bukkit.broadcastMessage(CC.translate("&c&l * &cEntries: &f" + this.getAmountOfPlayersInGiveaway())); + + for (Player player : Bukkit.getOnlinePlayers()) { + message.sendToPlayer(player); + clickable.sendToPlayer(player); + player.sendMessage(""); + } + } + + public void announceStart(GiveAway giveAway) { + JSONMessage message = new JSONMessage("", ChatColor.GRAY); + message.addText(CC.translate("&c&l * &cPrize: &f")); + message.addItem(this.currentGiveAway.getPrize(), CC.translate(ChatColor.WHITE + this.getFormattedName(this.currentGiveAway.getPrize()))); + Clickable clickable = new Clickable(""); + clickable.add(CC.translate("&7[Click here to join the giveaway]"), CC.translate("&7/giveaway join"), "/giveaway join"); + Bukkit.broadcastMessage(""); + Bukkit.broadcastMessage(CC.translate("&c&lCranked Giveaway Started")); + Bukkit.broadcastMessage(CC.translate("&c&l * &cTime: &f" + giveAway.getTimeInSeconds() + "s")); + Bukkit.broadcastMessage(CC.translate("&c&l * &cWinners: &f" + giveAway.getWinnersAmount())); + + for (Player player : Bukkit.getOnlinePlayers()) { + message.sendToPlayer(player); + clickable.sendToPlayer(player); + player.sendMessage(""); + } + } + + public void announceWinners(List winners, GiveAway giveAway) { + JSONMessage message = new JSONMessage("", ChatColor.GRAY); + message.addText(CC.translate("&c&l * &cPrize: &f")); + message.addItem(this.currentGiveAway.getPrize(), CC.translate(ChatColor.WHITE + this.getFormattedName(this.currentGiveAway.getPrize()))); + StringBuilder winnersString = new StringBuilder(); + for (Player player : winners) { + winnersString.append(player.getName()).append(", "); + } + winnersString = new StringBuilder(removeLastCharOptional(winnersString.toString())); + winnersString = new StringBuilder(removeLastCharOptional(winnersString.toString())); + Bukkit.broadcastMessage(""); + Bukkit.broadcastMessage(CC.translate("&c&lCranked Giveaway Ended")); + Bukkit.broadcastMessage(CC.translate("&c&l * &cWinners: &f" + winnersString)); + Bukkit.broadcastMessage(CC.translate("&c&l * &cEntries: &f" + this.getAmountOfPlayersInGiveaway())); + + + + + for (Player player : Bukkit.getOnlinePlayers()) { + message.sendToPlayer(player); + player.sendMessage(""); + } + + + + } + + public static String removeLastCharOptional(String s) { + return Optional.ofNullable(s) + .filter(str -> str.length() != 0) + .map(str -> str.substring(0, str.length() - 1)) + .orElse(s); + } + + + public int getAmountOfPlayersInGiveaway() { + return this.currentGiveAway.playersJoined.size() + this.currentGiveAway.fakeJoins; + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/managers/HelmetSkinManager.java b/Core/src/main/java/net/crankedpvp/crankedcore/managers/HelmetSkinManager.java new file mode 100644 index 0000000..5b29063 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/managers/HelmetSkinManager.java @@ -0,0 +1,204 @@ +package net.crankedpvp.crankedcore.managers; + +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.google.common.collect.Lists; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.struct.StarItem; +import net.minecraft.server.v1_8_R3.Container; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +public class HelmetSkinManager { + + + private PacketAdapter entityEquipListener; + private PacketAdapter windowItemsListener; + private PacketAdapter setSlotListener; + + public void load(CrankedCore plugin) { + this.loadEntityEquipListener(plugin); + this.loadSetSlotListener(plugin); + this.loadWindowItemsListener(plugin); + + ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); + + protocolManager.addPacketListener(this.entityEquipListener); + protocolManager.addPacketListener(this.windowItemsListener); + protocolManager.addPacketListener(this.setSlotListener); + } + + public void unload() { + if (this.windowItemsListener != null) + ProtocolLibrary.getProtocolManager().removePacketListener(this.windowItemsListener); + if (this.entityEquipListener != null) + ProtocolLibrary.getProtocolManager().removePacketListener(this.entityEquipListener); + if (this.setSlotListener != null) + ProtocolLibrary.getProtocolManager().removePacketListener(this.setSlotListener); + } + + public void loadEntityEquipListener(CrankedCore plugin) { + this.entityEquipListener = new PacketAdapter(plugin, ListenerPriority.LOW, PacketType.Play.Server.ENTITY_EQUIPMENT) { + public void onPacketSending(PacketEvent event) { + PacketContainer packet = event.getPacket(); + + ItemStack item = packet.getItemModifier().read(0); + ItemStack helmet = getItem(item); + + if (helmet == null) return; + + packet.getItemModifier().write(0, helmet); + } + }; + } + + public void loadWindowItemsListener(CrankedCore plugin) { + this.windowItemsListener = new PacketAdapter(plugin, ListenerPriority.LOW, PacketType.Play.Server.WINDOW_ITEMS) { + public void onPacketSending(PacketEvent event) { + + Player observingPlayer = event.getPlayer(); + int slot = event.getPacket().getIntegers().read(0); + + if (slot != ((CraftPlayer) observingPlayer).getHandle().defaultContainer.windowId) { + return; + } + + ItemStack star; + ItemStack[] items = event.getPacket().getItemArrayModifier().read(0); + + if (items != null && items.length >= 4 && !observingPlayer.getGameMode().equals(GameMode.CREATIVE) && (star = HelmetSkinManager.this.getItem(items[5])) != null) { + items[5] = star; + event.getPacket().getItemArrayModifier().write(0, items); + } + } + }; + } + + public void loadSetSlotListener(CrankedCore plugin) { + this.setSlotListener = new PacketAdapter(plugin, ListenerPriority.LOW, PacketType.Play.Server.SET_SLOT) { + public void onPacketSending(PacketEvent event) { + Player observingPlayer = event.getPlayer(); + PacketContainer packet = event.getPacket(); + int windowId = packet.getIntegers().read(0); + int slot2 = packet.getIntegers().read(1); + Container contain = ((CraftPlayer) observingPlayer).getHandle().defaultContainer; + + if (contain == null || contain.windowId != windowId || observingPlayer.getGameMode().equals(GameMode.CREATIVE)) { + return; + } + + ItemStack starItem; + ItemStack helmet = packet.getItemModifier().read(0); + + if (slot2 == 5 && (starItem = HelmetSkinManager.this.getItem(helmet)) != null) { + packet.getItemModifier().write(0, starItem); + } + } + }; + } + + public ItemStack getItem(ItemStack item) { + if (StarItemsAPI.itemHasStarItemEquipped(item)) { + StarItem starItem = StarItemsAPI.getEquippedStarItem(item); + + if (starItem == null) return null; + + return copyItemStackNewStarItem(item.clone(), starItem); + } + + if (CrankedMasksAPI.itemHasMaskEquipped(item)) { + List masks = CrankedMasksAPI.getMasksOnItem(item); + + if (masks == null) return null; + + return copyItemStackNewSkull(item.clone(), masks); + + } + + return null; + } + + public static ItemStack copyItemStackNewSkull(ItemStack itemStack, List masks) { + double durability = itemStack.getDurability(); + double maxDurability = itemStack.getType().getMaxDurability(); + double durabilityLeft = maxDurability - durability; + double percent = durabilityLeft / maxDurability * 100.0; + + itemStack.setType(Material.SKULL_ITEM); + itemStack.setDurability((short) 3); + + SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta(); + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + String texture = masks.size() == 1 ? masks.get(0).getTexture() : "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNjM4YzUzZTY2ZjI4Y2YyYzdmYjE1MjNjOWU1ZGUxYWUwY2Y0ZDdhMWZhZjU1M2U3NTI0OTRhOGQ2ZDJlMzIifX19"; + profile.getProperties().put("textures", new Property("textures", texture)); + Field profileField = null; + try { + profileField = skullMeta.getClass().getDeclaredField("profile"); + } catch (NoSuchFieldException|SecurityException e) { + e.printStackTrace(); + } + assert profileField != null; + profileField.setAccessible(true); + try { + profileField.set(skullMeta, profile); + } catch (IllegalArgumentException|IllegalAccessException e) { + e.printStackTrace(); + } + + if (!skullMeta.hasDisplayName()) { + String multiMaskNames = masks.stream().map(Mask::getDisplayName).collect(Collectors.joining("&f&l, ")); + skullMeta.setDisplayName(CC.translate("&f&lMulti-Mask (" + multiMaskNames + "&f&l)")); + } + + List lore = skullMeta.hasLore() ? skullMeta.getLore() : Lists.newArrayList(); + lore.add(CC.Gray + "Durability: " + (int)durabilityLeft + " / " + (int)maxDurability + " (" + NumberUtils.formatMoney(percent) + "%)"); + skullMeta.setLore(lore); + + itemStack.setItemMeta(skullMeta); + return itemStack; + } + + + public static ItemStack copyItemStackNewStarItem(ItemStack itemStack, StarItem starItem) { + double durability = itemStack.getDurability(); + double maxDurability = itemStack.getType().getMaxDurability(); + double durabilityLeft = maxDurability - durability; + double percent = durabilityLeft / maxDurability * 100.0; + + ItemMeta itemMeta = itemStack.getItemMeta(); + + List lore = itemMeta.hasLore() ? itemMeta.getLore() : Lists.newArrayList(); + lore.add(CC.Gray + "Durability: " + (int)durabilityLeft + " / " + (int)maxDurability + " (" + Math.round(percent) + "%)"); + itemMeta.setLore(lore); + + Material material = starItem.getVisualMaterial(); + short data = starItem.getData(); + itemStack.setType(material); + itemStack.setDurability(data); + + itemStack.setItemMeta(itemMeta); + return itemStack; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/managers/StaffChatManager.java b/Core/src/main/java/net/crankedpvp/crankedcore/managers/StaffChatManager.java new file mode 100644 index 0000000..525a374 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/managers/StaffChatManager.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedcore.managers; + +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +@Getter +public class StaffChatManager { + private final List inStaffChat; + private final String FORMAT = CC.DarkPurple + "[Staff] "; + + public StaffChatManager() { + this.inStaffChat = new ArrayList<>(); + } + + public void sendStaffMessage(Player sender, String msg) { + Bukkit.getOnlinePlayers().forEach(player -> { + if (player.hasPermission("crankedcore.staffchat")) { + player.sendMessage(FORMAT + CC.Yellow + sender.getName() + ": " + CC.LightPurple + msg); + } + }); + } + public void sendStaffMessage(String msg) { + Bukkit.getOnlinePlayers().forEach(player -> { + if (player.hasPermission("crankedcore.staffchat")) { + player.sendMessage(this.FORMAT + CC.Gray + msg); + } + }); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/GiveAway.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/GiveAway.java new file mode 100644 index 0000000..a2925b3 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/GiveAway.java @@ -0,0 +1,32 @@ +package net.crankedpvp.crankedcore.struct; + +import lombok.Getter; +import lombok.Setter; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Setter +@Getter +public class GiveAway { + public int winnersAmount; + public ItemStack prize; + public int giveAwayTaskId; + public int timeInSeconds; + public List playersJoined; + public int fakeJoins; + + public GiveAway(int winnersAmount, ItemStack prize, int timeInSeconds) { + this.winnersAmount = winnersAmount; + this.prize = prize; + this.timeInSeconds = timeInSeconds; + this.playersJoined = new ArrayList<>(); + this.giveAwayTaskId = -1; + this.fakeJoins = 0; + + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/cooldowns/GoldenAppleCooldown.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/cooldowns/GoldenAppleCooldown.java new file mode 100644 index 0000000..fdea356 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/cooldowns/GoldenAppleCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedcore.struct.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class GoldenAppleCooldown extends CurrentCooldown { + public GoldenAppleCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/cooldowns/HealCooldown.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/cooldowns/HealCooldown.java new file mode 100644 index 0000000..7c2633c --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/cooldowns/HealCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedcore.struct.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class HealCooldown extends CurrentCooldown { + public HealCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/crystals/CrystalItem.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/crystals/CrystalItem.java new file mode 100644 index 0000000..04c3744 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/crystals/CrystalItem.java @@ -0,0 +1,24 @@ +package net.crankedpvp.crankedcore.struct.crystals; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class CrystalItem { + + public static ItemStack createCrystal(EnchantEnum enchantEnum, int level) { + ItemStack itemStack = new ItemBuilder(Material.PRISMARINE_CRYSTALS, + "&a&l" + enchantEnum.getName() + " Crystal &8(&7Level " + RomanNumeral.convertToRoman(level) + "&8)", + "&7Drag and drop onto an item to apply", + "", + "&aMax Level: &7" + RomanNumeral.convertToRoman(enchantEnum.getMaxLevel())).colorize() + .build(); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("extinctCustomItem", "enchantShard"); + nbtItem.setString("shardEnchant", enchantEnum.getEnchantment().getName()); + nbtItem.setInteger("shardLevel", level); + return nbtItem.getItem(); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/crystals/EnchantEnum.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/crystals/EnchantEnum.java new file mode 100644 index 0000000..9fa4c75 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/crystals/EnchantEnum.java @@ -0,0 +1,26 @@ +package net.crankedpvp.crankedcore.struct.crystals; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.bukkit.enchantments.Enchantment; + +@Getter +@AllArgsConstructor +public enum EnchantEnum { + + SHARPNESS(Enchantment.DAMAGE_ALL, "Sharpness", 6), + UNBREAKING(Enchantment.DURABILITY, "Unbreaking", 4), + DEPTHSTRIDER(Enchantment.DEPTH_STRIDER, "Depth Strider", 3), + FEATHERFALLING(Enchantment.PROTECTION_FALL, "Feather Falling", 4), + PROTECTION(Enchantment.PROTECTION_ENVIRONMENTAL, "Protection", 5), + EFFICIENCY(Enchantment.DIG_SPEED, "Efficiency", 6), + SILKTOUCH(Enchantment.SILK_TOUCH, "Silk Touch", 1), + KNOCKBACK(Enchantment.KNOCKBACK, "Knockback", 2), + PUNCH(Enchantment.ARROW_KNOCKBACK, "Punch", 2), + PROJECTILEPROTECTION(Enchantment.PROTECTION_PROJECTILE, "Projectile Protection", 5), + LOOTING(Enchantment.LOOT_BONUS_MOBS, "Looting", 4); + + private final Enchantment enchantment; + private final String name; + private final int maxLevel; +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/gifts/Gift.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/gifts/Gift.java new file mode 100644 index 0000000..f0ea518 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/gifts/Gift.java @@ -0,0 +1,66 @@ +package net.crankedpvp.crankedcore.struct.gifts; + +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.RandomUtils; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.UUID; + +@Getter +public class Gift { + + private static final List GIFT_HEADS = Arrays.asList( + SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNmNlZjlhYTE0ZTg4NDc3M2VhYzEzNGE0ZWU4OTcyMDYzZjQ2NmRlNjc4MzYzY2Y3YjFhMjFhODViNyJ9fX0="), + SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMWI2NzMwZGU3ZTViOTQxZWZjNmU4Y2JhZjU3NTVmOTQyMWEyMGRlODcxNzU5NjgyY2Q4ODhjYzRhODEyODIifX19"), + SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDA4Y2U3ZGViYTU2YjcyNmE4MzJiNjExMTVjYTE2MzM2MTM1OWMzMDQzNGY3ZDVlM2MzZmFhNmZlNDA1MiJ9fX0="), + SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODRlMWM0MmYxMTM4M2I5ZGM4ZTY3ZjI4NDZmYTMxMWIxNjMyMGYyYzJlYzdlMTc1NTM4ZGJmZjFkZDk0YmI3In19fQ=="), + SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTBjNzVhMDViMzQ0ZWEwNDM4NjM5NzRjMTgwYmE4MTdhZWE2ODY3OGNiZWE1ZTRiYTM5NWY3NGQ0ODAzZDFkIn19fQ=="), + SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYWMzODIxZDRmNjFiMTdmODJmMGQ3YThlNTMxMjYwOGZmNTBlZGUyOWIxYjRkYzg5ODQ3YmU5NDI3ZDM2In19fQ=="), + SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZWQ5N2Y0ZjQ0ZTc5NmY3OWNhNDMwOTdmYWE3YjRmZTkxYzQ0NWM3NmU1YzI2YTVhZDc5NGY1ZTQ3OTgzNyJ9fX0=") + ); + + private final String senderName; + private final UUID sender; + private final ItemStack itemStack; + private final String message; + private final long time; + + public Gift(Player sender, ItemStack itemStack, String message) { + this.sender = sender.getUniqueId(); + this.senderName = sender.getName(); + this.itemStack = itemStack; + this.message = message; + this.time = System.currentTimeMillis(); + } + + public String getFormatedTime() { + return TimeUtils.formatSeconds((System.currentTimeMillis() - this.time) / 1000); + } + + public ItemStack createGuiGiftItem() { + return new ItemBuilder(this.selectRandomHead()) + .setName("&fGift From: &a" + this.getSenderName()) + .setLore( + "", + "&7Gift Time: &f" + this.getFormatedTime() + " ago", + "&7Gift Message:&f" + this.getMessage(), + "", + "&e&l(!) &f&nClick&f to reveal your present" + ) + .colorize() + .build(); + } + + public ItemStack selectRandomHead() { + Random rand = new Random(); + return GIFT_HEADS.get(rand.nextInt(GIFT_HEADS.size())); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/kits/Kit.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/kits/Kit.java new file mode 100644 index 0000000..0c6cd49 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/kits/Kit.java @@ -0,0 +1,64 @@ +package net.crankedpvp.crankedcore.struct.kits; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.storageutils.struct.NewKeyToSave; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +@Getter +@AllArgsConstructor +public class Kit implements NewKeyToSave, Comparable, Cloneable { + + private final ItemStack[] lootList; + private final long cooldown; + private final boolean gkit; + private final int weight; + private String key; + + @Override + public String getKey() { + return this.key; + } + + @Override + public void setKey(String s) { + this.key = s; + } + + public void supplyKit(Player player) { + for(ItemStack itemStack : lootList) { + PlayerUtils.giveOrDropProtectedItem(player, itemStack, 5); + } + } + + public String getPermission() { + return "cranked.kit." + key; + } + + public String getDisplayName() { + return StringUtils.toNiceString(getKey()); + } + + public boolean hasAccess(Player player) { + return player.hasPermission(getPermission()); + } + + @Override + public Kit clone() { + try { + return (Kit) super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + return null; + } + } + + @Override + public int compareTo(@NotNull Kit o) { + return Integer.compare(this.getWeight(), o.getWeight()); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/kits/KitManager.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/kits/KitManager.java new file mode 100644 index 0000000..da922d5 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/kits/KitManager.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedcore.struct.kits; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.struct.NewSaveLoadManager; +import org.jetbrains.annotations.NotNull; + +public class KitManager extends NewSaveLoadManager { + + public KitManager() { + super(CrankedCore.getInstance(), StorageUtils.getInstance().getGson(), "kits/", Kit.class); + } + + @Override + public String serialize(String s) { + return s; + } + + @Override + public String deserialize(String s) { + return s; + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/netherpvp/NetherPvPQueueManager.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/netherpvp/NetherPvPQueueManager.java new file mode 100644 index 0000000..29e534b --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/netherpvp/NetherPvPQueueManager.java @@ -0,0 +1,166 @@ +package net.crankedpvp.crankedcore.struct.netherpvp; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.commands.BlessCommand; +import net.crankedpvp.crankedcore.tasks.NetherPvPEndTask; +import net.crankedpvp.crankedcore.utils.ConfigManager; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.serializer.location.LocationSerializerDeserializer; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; + +public class NetherPvPQueueManager { + + private NetherPvPEndTask netherPvPEndTask; + private final List pvpQueue; + private final CrankedCore plugin; + private final ConfigManager configManager; + private final Pair playersInPvpArena; + + public NetherPvPQueueManager(CrankedCore plugin) { + this.plugin = plugin; + this.configManager = this.plugin.getConfigManager(); + this.playersInPvpArena = new Pair<>(null, null); + this.pvpQueue = new ArrayList<>(); + this.netherPvPEndTask = null; + } + + public void addPlayerToPvpQueue(Player player) { + this.pvpQueue.add(player); + } + + public void removePlayerFromPvpQueue(Player player) { + this.pvpQueue.remove(player); + } + + public List getPlayersFromPvpQueue() { + return ImmutableList.copyOf(this.pvpQueue); + } + + public boolean isPlayerInPvPQueue(Player player) { + return this.pvpQueue.contains(player); + } + + public boolean isPlayerInArena(Player player) { + return this.playersInPvpArena.contains(player); + } + + @Nullable + public Player getOposingPlayer(Player player) { + if (this.playersInPvpArena.getLeft() == player) return this.playersInPvpArena.getRight(); + if (this.playersInPvpArena.getRight() == player) return this.playersInPvpArena.getLeft(); + return null; + } + + public void resetQueue() { + this.pvpQueue.clear(); + } + + public void resetArena() { + this.playersInPvpArena.clear(); + } + + public boolean isArenaEmpty() { + return this.playersInPvpArena.isEmpty(); + } + + public void endMatch(Player winner, Player loser) { + this.playersInPvpArena.clear(); + FileConfiguration config = this.configManager.getConfig(ConfigManager.ConfigFile.SETTINGS); + ConfigurationSection configurationSection = config.getConfigurationSection("nether-pvp"); + Location winnerTpLocation = LocationSerializerDeserializer.deserialize(configurationSection.getString("winner-tp-location")); + if (winner.isOnline()) { + winner.teleport(winnerTpLocation); + winner.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You have won a NetherPvP match against: &c" + loser.getName())); + } + if (loser.isOnline()) { + loser.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You have lost a NetherPvP match against: &c" + winner.getName())); + } + Bukkit.broadcastMessage((CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + LuckpermUtils.getDisplayName(winner) + "&7 has defeated " + LuckpermUtils.getDisplayName(loser) + " &7in a NetherPvP Match, L in the chat!"))); + this.netherPvPEndTask.cancel(); + } + + public void cancelMatch() { + Player firstPlayer = this.playersInPvpArena.getLeft(); + Player secondPlayer = this.playersInPvpArena.getRight(); + this.playersInPvpArena.clear(); + FileConfiguration config = this.configManager.getConfig(ConfigManager.ConfigFile.SETTINGS); + ConfigurationSection configurationSection = config.getConfigurationSection("nether-pvp"); + Location winnerTpLocation = LocationSerializerDeserializer.deserialize(configurationSection.getString("winner-tp-location")); + if (firstPlayer.isOnline()) { + firstPlayer.teleport(winnerTpLocation); + firstPlayer.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 This NetherPvP match has been canceled")); + } + if (secondPlayer.isOnline()) { + secondPlayer.teleport(winnerTpLocation); + secondPlayer.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 This NetherPvP match has been canceled")); + } + this.netherPvPEndTask.cancel(); + } + + public boolean acceptMatch(Player matchCreator, Player matchAccepter) { + if (WorldGuardUtils.canPvPInRegion(matchAccepter)) { + matchAccepter.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You cannot accept a match while in a pvp enabled region")); + matchCreator.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 This match cannot start because " + matchAccepter.getName() + " is in a pvp enabled region")); + SoundUtils.playErrorSound(matchAccepter); + SoundUtils.playErrorSound(matchCreator); + return false; + } + + if (WorldGuardUtils.canPvPInRegion(matchCreator)) { + matchCreator.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You cannot accept a match while in a pvp enabled region")); + matchAccepter.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 This match cannot start because " + matchCreator.getName() + " is in a pvp enabled region")); + SoundUtils.playErrorSound(matchAccepter); + SoundUtils.playErrorSound(matchCreator); + return false; + } + + if (FactionUtils.isFactionMember(FactionUtils.getFPlayer(matchAccepter).getFaction(), FactionUtils.getFPlayer(matchCreator))) { + matchAccepter.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You cannot accept a match from someone in your faction")); + SoundUtils.playErrorSound(matchAccepter); + return false; + } + + if (!this.isArenaEmpty()) { + matchAccepter.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 You cannot accept a match while the arena is full")); + SoundUtils.playErrorSound(matchAccepter); + return false; + } + + this.playersInPvpArena.setRight(matchAccepter); + this.playersInPvpArena.setLeft(matchCreator); + + FileConfiguration config = this.configManager.getConfig(ConfigManager.ConfigFile.SETTINGS); + ConfigurationSection configurationSection = config.getConfigurationSection("nether-pvp"); + Location corner1 = LocationSerializerDeserializer.deserialize(configurationSection.getString("corner1")); + Location corner2 = LocationSerializerDeserializer.deserialize(configurationSection.getString("corner2")); + + EssentialsUtils.clearTeleportRequests(matchAccepter); + EssentialsUtils.clearTeleportRequests(matchCreator); + + matchCreator.teleport(corner1); + matchAccepter.teleport(corner2); + + SoundUtils.playSuccessSound(matchAccepter); + SoundUtils.playSuccessSound(matchCreator); + this.netherPvPEndTask = new NetherPvPEndTask(); + this.netherPvPEndTask.runTaskTimer(this.plugin, 0L, 20L); + matchCreator.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 This NetherPvP match has now started, it will automatically end in 5 mins")); + matchAccepter.sendMessage(CC.translate("&c&lNetherPvP &8" + Arrow.arrow() + "&7 This NetherPvP match has now started, it will automatically end in 5 mins")); + PotionEffectUtils.bless(matchAccepter); + PotionEffectUtils.bless(matchCreator); + if (this.isPlayerInPvPQueue(matchAccepter)) { + this.pvpQueue.remove(matchAccepter); + } + + return true; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/reboot/Reboot.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/reboot/Reboot.java new file mode 100644 index 0000000..bd11d88 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/reboot/Reboot.java @@ -0,0 +1,48 @@ +package net.crankedpvp.crankedcore.struct.reboot; + +import net.crankedpvp.combatlog.CombatTagAPI; +import net.crankedpvp.crankedcore.language.Language; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Arrays; +import java.util.List; + +public class Reboot extends BukkitRunnable { + + private static final List BROADCAST_TIMES = Arrays.asList(3600, 1800, 900, 600, 300, 180, 120, 60, 45, 30, 15, 10, 5, 4, 3, 2, 1); + private int secondsUntilShutdown; + + public Reboot(int secondsUntilShutdown) { + this.secondsUntilShutdown = secondsUntilShutdown; + } + + public void setSecondsUntilShutdown(int secondsUntilShutdown) { + this.secondsUntilShutdown = secondsUntilShutdown; + } + + + public int getSecondsUntilShutdown() { + return this.secondsUntilShutdown; + } + + @Override + public void run() { + + if (BROADCAST_TIMES.contains(this.secondsUntilShutdown)) { + Bukkit.getServer().broadcastMessage(" "); + Bukkit.getServer().broadcastMessage(Language.REBOOT_IN.getMessage().replace("%time%", String.valueOf(secondsUntilShutdown))); + Bukkit.getServer().broadcastMessage(" "); + } + + if (this.secondsUntilShutdown <= 0) { + for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { + CombatTagAPI.removePlayerFromCombat(onlinePlayer); + } + Bukkit.getServer().shutdown(); + return; + } + this.secondsUntilShutdown--; + } +} \ No newline at end of file diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftAdapterDeserializer.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftAdapterDeserializer.java new file mode 100644 index 0000000..9ed9e4f --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftAdapterDeserializer.java @@ -0,0 +1,23 @@ +package net.crankedpvp.crankedcore.struct.typeadapters; + +import net.crankedpvp.crankedcore.struct.gifts.Gift; +import net.crankedpvp.storageutils.gson.JsonDeserializationContext; +import net.crankedpvp.storageutils.gson.JsonDeserializer; +import net.crankedpvp.storageutils.gson.JsonElement; +import net.crankedpvp.storageutils.gson.JsonObject; + +import java.lang.reflect.Type; + +public class GiftAdapterDeserializer implements JsonDeserializer { + + @Override + public Gift deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + JsonObject jsonObject = json.getAsJsonObject(); + +/* Gift gift = new Gift( + jsonObject.getAsJsonPrimitive("").getAsString() + ); + */ + return context.deserialize(json, typeOfT); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftAdapterSerializer.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftAdapterSerializer.java new file mode 100644 index 0000000..0f58c3e --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftAdapterSerializer.java @@ -0,0 +1,26 @@ +package net.crankedpvp.crankedcore.struct.typeadapters; + +import net.crankedpvp.crankedcore.struct.gifts.Gift; +import net.crankedpvp.lootboxes.utils.ItemStackSerializer; +import net.crankedpvp.storageutils.gson.*; + +import java.io.IOException; +import java.lang.reflect.Type; + +public class GiftAdapterSerializer implements JsonSerializer { + + @Override + public JsonElement serialize(Gift src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject obj = new JsonObject(); + obj.addProperty("sender", src.getSender().toString()); + obj.addProperty("senderName", src.getSenderName()); + try { + obj.addProperty("itemStack", ItemStackSerializer.serialize(src.getItemStack())); + } catch (IOException e) { + throw new RuntimeException(e); + } + obj.addProperty("message", src.getMessage()); + obj.addProperty("time", src.getTime()); + return obj; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftsListAdapterDeserializer.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftsListAdapterDeserializer.java new file mode 100644 index 0000000..2ccee8e --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftsListAdapterDeserializer.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedcore.struct.typeadapters; + +import net.crankedpvp.crankedcore.struct.gifts.Gift; +import net.crankedpvp.storageutils.gson.JsonArray; +import net.crankedpvp.storageutils.gson.JsonDeserializationContext; +import net.crankedpvp.storageutils.gson.JsonDeserializer; +import net.crankedpvp.storageutils.gson.JsonElement; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +public class GiftsListAdapterDeserializer implements JsonDeserializer> { + + @Override + public List deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + JsonArray jsonArray = ((JsonArray) json); + List gifts = new ArrayList<>(); + + for (JsonElement element : jsonArray) { + try { + gifts.add(context.deserialize(element.getAsJsonObject(), Gift.class)); + } catch (IllegalStateException exception) { + exception.printStackTrace(); + } + } + + return gifts; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftsListAdapterSerializer.java b/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftsListAdapterSerializer.java new file mode 100644 index 0000000..4220b01 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/struct/typeadapters/GiftsListAdapterSerializer.java @@ -0,0 +1,24 @@ +package net.crankedpvp.crankedcore.struct.typeadapters; + +import net.crankedpvp.crankedcore.struct.gifts.Gift; +import net.crankedpvp.storageutils.gson.JsonArray; +import net.crankedpvp.storageutils.gson.JsonElement; +import net.crankedpvp.storageutils.gson.JsonSerializationContext; +import net.crankedpvp.storageutils.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.List; + +public class GiftsListAdapterSerializer implements JsonSerializer> { + + @Override + public JsonElement serialize(List src, Type typeOfSrc, JsonSerializationContext context) { + JsonArray jsonArray = new JsonArray(); + + for (Gift gift : src) { + jsonArray.add(context.serialize(gift, Gift.class)); + } + + return jsonArray; + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/tasks/AutoBroadcastTask.java b/Core/src/main/java/net/crankedpvp/crankedcore/tasks/AutoBroadcastTask.java new file mode 100644 index 0000000..3a49bb3 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/tasks/AutoBroadcastTask.java @@ -0,0 +1,79 @@ +package net.crankedpvp.crankedcore.tasks; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.scheduler.BukkitRunnable; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class AutoBroadcastTask extends BukkitRunnable { + + private int currentMessage = 0; + private List> messages = new ArrayList<>(new ArrayList<>()); + + private final CrankedCore plugin; + public AutoBroadcastTask(CrankedCore plugin) { + this.plugin = plugin; + + } + + + + + private List getNextMessage() { + currentMessage++; + if(currentMessage >= messages.size()) currentMessage = 0; + return this.messages.get(currentMessage); + } + + public void setupMessages() { + + File file = new File(this.plugin.getDataFolder(), "auto-messages.yml"); + + file = new File(plugin.getDataFolder(), "auto-messages.yml"); + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource("auto-messages.yml", false); + } + + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + + for(String test : yamlConfiguration.getConfigurationSection("Messages").getKeys(false)) { + messages.add(yamlConfiguration.getStringList("Messages." + test)); + } + } + + public void reload() { + messages.clear(); + File file = new File(this.plugin.getDataFolder(), "auto-messages.yml"); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + + for(String test : yamlConfiguration.getConfigurationSection("Messages").getKeys(false)) { + messages.add(yamlConfiguration.getStringList("Messages." + test)); + } + } + + @Override + public void run() { + List message = getNextMessage(); + this.plugin.getServer().getOnlinePlayers().forEach(player -> { + message.forEach(line -> player.sendMessage(CC.translate(line))); + }); + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/tasks/GiveAwayTask.java b/Core/src/main/java/net/crankedpvp/crankedcore/tasks/GiveAwayTask.java new file mode 100644 index 0000000..da6af7b --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/tasks/GiveAwayTask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedcore.tasks; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.struct.GiveAway; +import org.bukkit.scheduler.BukkitRunnable; + +public class GiveAwayTask extends BukkitRunnable { + GiveAway giveAway = CrankedCore.getInstance().getGiveAwayManager().currentGiveAway; + int timeLeft = giveAway.getTimeInSeconds(); + + @Override + public void run() { + + switch (timeLeft) { + case 0: + CrankedCore.getInstance().getGiveAwayManager().endGiveAway(); + break; + case 1: + CrankedCore.getInstance().getGiveAwayManager().announce(1, giveAway); + break; + case 2: + CrankedCore.getInstance().getGiveAwayManager().announce(2, giveAway); + break; + case 3: + CrankedCore.getInstance().getGiveAwayManager().announce(3, giveAway); + break; + case 4: + CrankedCore.getInstance().getGiveAwayManager().announce(4, giveAway); + break; + case 5: + CrankedCore.getInstance().getGiveAwayManager().announce(5, giveAway); + break; + case 10: + CrankedCore.getInstance().getGiveAwayManager().announce(10, giveAway); + break; + case 15: + CrankedCore.getInstance().getGiveAwayManager().announce(15, giveAway); + break; + case 30: + CrankedCore.getInstance().getGiveAwayManager().announce(30, giveAway); + break; + case 45: + CrankedCore.getInstance().getGiveAwayManager().announce(45, giveAway); + break; + + } + timeLeft--; + + + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/tasks/NetherPvPEndTask.java b/Core/src/main/java/net/crankedpvp/crankedcore/tasks/NetherPvPEndTask.java new file mode 100644 index 0000000..48a8476 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/tasks/NetherPvPEndTask.java @@ -0,0 +1,18 @@ +package net.crankedpvp.crankedcore.tasks; + +import net.crankedpvp.crankedcore.CrankedCore; +import org.bukkit.scheduler.BukkitRunnable; + +public class NetherPvPEndTask extends BukkitRunnable { + + private int time = 300; + + @Override + public void run() { + time--; + + if (time <= 0) { + CrankedCore.getInstance().getNetherPvPQueueManager().cancelMatch(); + } + } +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/tasks/ProxyPatchTask.java b/Core/src/main/java/net/crankedpvp/crankedcore/tasks/ProxyPatchTask.java new file mode 100644 index 0000000..999d85f --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/tasks/ProxyPatchTask.java @@ -0,0 +1,213 @@ +package net.crankedpvp.crankedcore.tasks; + +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.event.server.ServerCommandEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class ProxyPatchTask extends BukkitRunnable { + + private int count = 0; + + @Getter + private List playerNames; + + public ProxyPatchTask() { + this.playerNames = Arrays.asList( + "Haru_s", + "Xx_Madr1", + "Charo", + "jestq", + "Aywi", + "1eyn", + "Clafory", + "babiw", + "Eniva", + "Hushpuppyzac", + "niaT_T", + "Keybinded", + "RIPMONARCHY", + "Encapsulated", + "Fuddruckers", + "huric4ne", + "revclts", + "sohv", + "breadmoists", + "IMakeSkins", + "PhaserPaul", + "7kya", + "Kosted", + "scoa", + "waiferthin", + "DarthVaderJonah", + "poisonz", + "aretist", + "bracken", + "brackert", + "dogtamer", + "balader", + "koining", + "plezz", + "doglover1", + "apesh1t", + + "sistertoucher", + "ravagedpvp", + "slennn", + "qrack", + "tantra", + "cloutexe", + "MWKD", + "Punco", + "NeeeGuh", + "juicyass", + "mwkd", + "meong", + "fatest", + "fpsproblems", + "thebetterpvper", + "ohzesmypet", + + "americol", + "brillo", + "isnipe", + "Spirtax", + "Got_Strafed", + "_OUO", + "FindMyDad", + "Heartality", + "OwenerkoSK", + "WhippingCream69", + "Poneyboy", + "jefferywest", + "rankcolors", + "xlukos", + "folkz", + "folkz_", + "josh_420", + + + /* + "revclts", + "xeyshh", + "_Caramelii", + "ASUSRTX2080Ti", + "SussyShare", + "TxFo", + "Mzhy", + "CosmiKazie", + "Aloriie", + "Hurrache", + "oAnxiety", + "Bearz_z", + "xxpz", + "Clyne", + "iRafaNove", + "bbito", + "intercaetera", + "babiw", + "WhyYouReadThis", + "Coucher", + "TheWatcherr", + "Relohd", + "tomarto", + "Blocklist", + "dumme0504", + "Aestheitc", + "babiw", + "Clafory", + "CraLey", + "1eyn", + "hwurt", + "Eniva", + "tomazzzekt", + "PeteParker", + "iDqxha_", + "Dehu", + "toxci", + "FULLSENDVINCENT", + "MissEurope", + "SebTheRandomOne", + "babiw", + "snve", + "Miilyh__", + "Genesong", + "Th3K1ng_", + "ChristmasJonas", + "GiackyB", + "wod1s", + "WhyYouReadThis", + "Fuddruckers", + "huric4ne", + "revclts", + "breadmoists", + "IMakeSkins", + + */ + "PhaserPaul", + "7kya", + "Kosted", + "scoa", + "waiferthin", + "DarthVaderJonah", + "revclts", + "xeyshh", + "_Caramelii", + "CosmiKazie", + "Aloriie", + "Hurrache", + "oAnxiety", + "Bearz_z", + "xxpz", + "Clyne", + "iRafaNove", + "bbito", + "intercaetera", + "babiw", + "WhyYouReadThis", + "Blocklist", + "dumme0504", + "Aestheitc", + "babiw", + "Clafory", + "CraLey", + "1eyn", + "hwurt", + "Eniva", + "Blezzed", + "doglover123", + "Slurrs", + "" + + + ); + Collections.shuffle(this.playerNames); + } + + @Override + public void run() { + if(this.count >= this.playerNames.size()-1) this.count = 0; + String playerName = this.playerNames.get(this.count); + count++; + if(Bukkit.getPlayer(playerName) != null) return; + ServerCommandEvent serverCommandEvent = new ServerCommandEvent(Bukkit.getConsoleSender(), "spoof add " + playerName); + serverCommandEvent.callEvent(); + //new ServerCommandEvent(Bukkit.getConsoleSender(), "spoof add " + playerName); + + } + + public void end() { + this.cancel(); + for(String playerName : this.playerNames) { + if(Bukkit.getPlayer(playerName) == null) continue; // continue if player exists :p + ServerCommandEvent serverCommandEvent = new ServerCommandEvent(Bukkit.getConsoleSender(), "spoof remove " + playerName); + serverCommandEvent.callEvent(); + } + } + + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/utils/ConfigManager.java b/Core/src/main/java/net/crankedpvp/crankedcore/utils/ConfigManager.java new file mode 100644 index 0000000..f93b097 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/utils/ConfigManager.java @@ -0,0 +1,52 @@ +package net.crankedpvp.crankedcore.utils; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.crankedpvp.crankedutils.utils.config.AbstractConfig; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; + +public class ConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public ConfigManager(JavaPlugin plugin) { + for (ConfigFile configFile : ConfigFile.values()) { + AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName()); + configs.put(configFile, abstractConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AbstractConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AbstractConfig::reloadConfig); + } + + public AbstractConfig getAbstractConfig(ConfigFile configFile) { + return configs.get(configFile); + } + + public FileConfiguration getConfig(ConfigFile configFile) { + return getAbstractConfig(configFile).getConfig(); + } + + @Getter + @RequiredArgsConstructor + public enum ConfigFile { + + BLOCKED_COMMANDS("blockedCommands.yml"), + SETTINGS("settings.yml"), + ; + + private final String fileName; + + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/utils/ExpBottleAPI.java b/Core/src/main/java/net/crankedpvp/crankedcore/utils/ExpBottleAPI.java new file mode 100644 index 0000000..ea81730 --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/utils/ExpBottleAPI.java @@ -0,0 +1,41 @@ +package net.crankedpvp.crankedcore.utils; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +public class ExpBottleAPI { + + public static ItemStack getXpBottle(int xpAmount, Player player) { + ItemStack expBottle = new ItemBuilder(Material.EXP_BOTTLE, "&a&lExperience Bottle") + .addLore("&2Amount: &f" + NumberUtils.formatMoney(xpAmount) + " XP") + .addLore("&2Enchanter: &f" + player.getName()) + .colorize() + .build(); + NBTItem item = new NBTItem(expBottle); + NBTCompound compound = item.getOrCreateCompound("EXP_BOTTLE"); + compound.setInteger("expAmount", xpAmount); + return item.getItem(); + } + + public static boolean isXpBottle(ItemStack itemStack) { + if (itemStack==null) return false; + if (itemStack.getType() != Material.EXP_BOTTLE) return false; + if (!itemStack.hasItemMeta()) return false; + if (!itemStack.getItemMeta().hasLore()) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getCompound("EXP_BOTTLE") != null; + } + + public static int getXpAmount(ItemStack xpBottle) { + NBTItem nbtItem = new NBTItem(xpBottle); + NBTCompound compound = nbtItem.getCompound("EXP_BOTTLE"); + return compound.getInteger("expAmount"); + } + +} diff --git a/Core/src/main/java/net/crankedpvp/crankedcore/utils/MoneyNotesAPI.java b/Core/src/main/java/net/crankedpvp/crankedcore/utils/MoneyNotesAPI.java new file mode 100644 index 0000000..261b80b --- /dev/null +++ b/Core/src/main/java/net/crankedpvp/crankedcore/utils/MoneyNotesAPI.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedcore.utils; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class MoneyNotesAPI { + public static ItemStack getNote(int moneyAmount, Player player) { + ItemStack expBottle = new ItemBuilder(Material.PAPER, "&6&lBank Note") + .addLore("&eAmount: &f$" + NumberUtils.formatMoney(moneyAmount)) + .addLore("&eSigner: &f" + player.getName()) + .colorize() + .build(); + NBTItem item = new NBTItem(expBottle); + NBTCompound compound = item.addCompound("MONEY_NOTE"); + compound.setInteger("moneyAmount", moneyAmount); + return item.getItem(); + } + + public static boolean isMoneyNote(ItemStack i) { + if (i==null) return false; + if (i.getType() != Material.PAPER) return false; + if (!i.hasItemMeta()) return false; + if (!i.getItemMeta().hasLore()) return false; + NBTItem nbtItem = new NBTItem(i); + return nbtItem.getCompound("MONEY_NOTE") != null; + } + + public static int getMoneyAmount(ItemStack xpBottle) { + NBTItem nbtItem = new NBTItem(xpBottle); + NBTCompound compound = nbtItem.getCompound("MONEY_NOTE"); + return compound.getInteger("moneyAmount"); + } +} diff --git a/Core/src/main/resources/auto-messages.yml b/Core/src/main/resources/auto-messages.yml new file mode 100644 index 0000000..5afa895 --- /dev/null +++ b/Core/src/main/resources/auto-messages.yml @@ -0,0 +1,7 @@ +Messages: + Example: + - "auto bc 1" + Example2: + - "auto bc 2" + Example3: + - "auto bc 3" \ No newline at end of file diff --git a/Core/src/main/resources/config.yml b/Core/src/main/resources/config.yml new file mode 100644 index 0000000..e69de29 diff --git a/Core/src/main/resources/language.yml b/Core/src/main/resources/language.yml new file mode 100644 index 0000000..ac99254 --- /dev/null +++ b/Core/src/main/resources/language.yml @@ -0,0 +1,104 @@ +BLESS: + - " &e&l** BLESSED ** " + - "&7&o(( You have removed all debuff effects ))" + - "" +MOTD: + - "&fWelcome" + - "&6To" + - "&cCranked" +NO_PERMISSION: "&cYou do not have permission to do this" +INVSEE: "&a&lCore &8➥ &7Viewing &f%player%&7's inventory." + +NEED_FACTION_TO_USE: "&8(&c!&8) &7You need to be in a faction to use this" +WRONG_TERRITORY: "&8(&c!&8) &7You can can only use this in your factions territory" + +WAND_REMOVED_SAND: "&8(&a!&8) &7Removed %count% Sand Blocks" + +CANNOT_INVSEE_YOURSELF: "&a&lCore &8➥ &7You cannot /invsee yourself!" +CANNOT_INVSEE_GHOST_MASK: "&a&lCore &8➥ &7You cannot invsee this player because he is wearing a Ghost Mask!" + +POTS_RECEIVED: "&eYou have purchased &7%amount%x &epotions for &a$%price%" +POTS_TOO_EXPENSIVE: "&cYou require &a$%price% &cto purchase &7%amount%x &epotions" + +STAFF_CHAT_JOIN: "&aYou have join staffchat" +STAFF_CHAT_LEAVE: "&cYou have left staffchat" + +REBOOT_SCHEDULED: "&8(&a!&8) &7Scheduled the server to reboot in %time% seconds" +REBOOT_CANCEL: "&8(&a!&8) &7The server reboot has been successfully canceled" +REBOOT_NOT_SCHEDULED: "&8(&a!&8) &7This server is not scheduled to reboot" +REBOOT_IN: "&8(&4!&8) &7The server will reboot in %time% seconds" +REBOOT_CAN_NOT_DO_THIS: "&8(&c!&8) &7You cannot do this while the server is rebooting" + +FULL_INVENTORY: "&cClear some inventory space and try again" + +CANNOT_HAVE_EMPTY_HAND: "&cYou need an item in your had to do this." +ALREADY_HAS_GIFT: "&cYou already have a gift from this player!" +GIFT_URSELF: "&cYou cannot gift your self a present." +RECEIVED_GIFT: "&aYou have received a gift from &f{sender}&a, type &f/gifts&a to reveal your gift!" +SENT_GIFT: "&aYou have sent a gift to &f{receiver}&a!" + +GODSET_SUCCESS: "&eYou have successfully enchanted this item" + +EXP_BOTTLE_WITHDRAW: "&c&l- &c%amount% XP" +EXP_BOTTLE_DEPOSIT: "&a&l+ &a%amount% XP" +EXP_BOTTLE_HELP: + - "&a/xpbottle " + - "&7Converts xp into bottle form." + - "&7Use &e/xp&7 to view your current exp points." +EXP_BOTTLE_NOT_ENOUGH: "&a&lCore &8➥ &7You do not have have enough exp to bottle this amount." + +NOTE_WITHDRAW: "&c&l- &c$%amount%" +NOTE_DEPOSIT: '&a&l+ $%money% &7(x%amount%)' +NOTE_HELP: + - "&e/withdraw " + - "&7Converts into a bank note." + - "&7Use &6/bal&7 to view your current balance." +NOTE_NOT_ENOUGH: "&a&lCore &8➥ &7You do not have have enough money to withdraw this amount." + +WITHDRAW_DECIMAL: "&a&lCore &8➥ &7You cannot withdraw decimal numbers!" +INVALID_NUMBER: "&a&lCore &8➥ &7This is not a valid number, try again!" + +NEAR_TOO_MANY_PLAYERS: "&a&lCore &8➥ &7There are too many nearby players!" + +max_warzone_claims: 2 +CLAIM_MAX_REACHED: "&a&lCore &8➥ &7You can only claim a max of &f%max%&7 claims touching the &f%region%&7 Warzone." +CLAIM_OBTAINED: "&a&lCore &8➥ &7You have claimed land touching the &f%region%&7 Warzone." +CLAIM_OBTAINED_OTHER: "&a&lCore &8➥ &7%claimer% has claimed land touching the &f%region%&7 Warzone." + +ENABLED_FAC_TITLE: "&a&lCore &8➥ &7You &a&lENABLED&7 Faction Land Titles" +DISABLED_FAC_TITLE: "&a&lCore &8➥ &7You &c&lDISABLED&7 Faction Land Titles" +ENABLED_KILL_TITLE: "&a&lCore &8➥ &7You &a&lENABLED&7 Kill Titles" +DISABLED_KILL_TITLE: "&a&lCore &8➥ &7You &c&lDISABLED&7 Kill Titles" + +GIVEALL_RECEIVED: "&a&lCore &8➥ &7You have received &f%amount% %item% &7from the giveall!" + +BLOCKED_COMMAND: "&a&lCore &8➥ &7%command% is a blocked command!" + +golden_apple_cooldown: 30 +GOLDEN_APPLE_ENTERED_COOLDOWN: "&a&lCore &8➥ &7You have entered Golden Apple Cooldown, wait &f%cooldown%s&7 before eating another Golden Apple!" +GOLDEN_APPLE_COOLDOWN: "&a&lCore &8➥ &7You cannot eat another Golden Apple for &f%time%&7!" + +heal_cooldown: 300 +HEALED: "&a&lCore &8➥ &7You have been healed!" +HEAL_COOLDOWN: "&a&lCore &8➥ &7You &ccannot&7 use /heal for another &f%left%&7!" + +ADMIN_RELOADING: "&a&lCore &8➥ &7Reloading configs now..." +ADMIN_RELOADED: "&a&lCore &8➥ &7Reloaded configs and other cool stuff. Took &d%took%ms&7." + +ADMINKIT_HELP: "&7/ckit &c" +ADMINKIT_GIVE_HELP: "&7/ckit &cgive " +ADMINKIT_CREATE_HELP: "&7/ckit &ccreate " +ADMINKIT_ALREADY_EXISTS: "&c&lKit &8➥ &7This kit already exists" +ADMINKIT_CREATED: "&a&lKit &8➥ &7Kit successfully created" + + +KIT_RECEIVED: "&a&lKit &8➥ &7You have received the %kit% kit" +KIT_COOLDOWN: "&c&lKit &8➥ &7You have to wait another %time%" +KIT_INVALID_NAME: "&c&lKit &8➥ &7Invalid kit name" +KIT_NO_ACCESS: "&c&lKit &8➥ &7You do not have access to this kit" + +ENABLED_BOSS_DEATH_MESSAGES: "&a&lCore &8➥ &7You &a&lENABLED&7 Boss Death Messages" +DISABLED_BOSS_DEATH_MESSAGES: "&a&lCore &8➥ &7You &c&lDISABLED&7 Boss Death Messages" + +LOOKING_FOR_FACTION: "&a&lFactions &8➥ &f%player_displayname% &7is looking for a faction (&f/lff&7)!" +LOOKING_FOR_FACTION_COOLDOWN: "&a&lFactions &8➥ &7You cannot use &f/lff&7 for another &f%time%&7!" diff --git a/Core/src/main/resources/plugin.yml b/Core/src/main/resources/plugin.yml new file mode 100644 index 0000000..d2f4277 --- /dev/null +++ b/Core/src/main/resources/plugin.yml @@ -0,0 +1,14 @@ +name: CrankedCore +main: net.crankedpvp.crankedcore.CrankedCore +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - FactionsKore + - CrankedEnchants + - CrankedMasks + - CrankedStarItems + - StorageUtil + - Essentials + - CrankedStaff \ No newline at end of file diff --git a/Core/src/main/resources/settings.yml b/Core/src/main/resources/settings.yml new file mode 100644 index 0000000..3b61af9 --- /dev/null +++ b/Core/src/main/resources/settings.yml @@ -0,0 +1,7 @@ +nether-increase-amount-percent: 30 +nether-pvp: + corner1: 'world_nether:26.5:33:-50.5:-45:0' + corner2: 'world_nether:3.5:33:-73.5:-45:0' + winner-tp-location: 'world_nether:-2.5:37:-63.5:-90:0' + allowed-commands: + - "netherpvp leave" diff --git a/CustomBlocks/pom.xml b/CustomBlocks/pom.xml new file mode 100644 index 0000000..d547ca1 --- /dev/null +++ b/CustomBlocks/pom.xml @@ -0,0 +1,57 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + CustomBlocks + + + 8 + 8 + + + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + Utils + net.crankedpvp + + + net.crankedpvp + Keys + + + net.crankedpvp + SlotBot + + + net.crankedpvp + Core + + + com.massivecraft + Factions + + + net.crankedpvp + LootTable + + + net.crankedpvp + LootFilter + + + + \ No newline at end of file diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/CustomBlocks.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/CustomBlocks.java new file mode 100644 index 0000000..afd7bd8 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/CustomBlocks.java @@ -0,0 +1,64 @@ +package net.crankedpvp.customblocks; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.customblocks.commands.CustomBlockCommand; +import net.crankedpvp.customblocks.data.CustomBlockManager; +import net.crankedpvp.customblocks.listeners.CustomBlockBreakListener; +import net.crankedpvp.customblocks.listeners.CustomBlockListener; +import net.crankedpvp.customblocks.listeners.CustomBlockPlaceListener; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.typeadapters.CustomBlockDeserializer; +import net.crankedpvp.customblocks.tasks.TickAbleBlocksRunnable; +import net.crankedpvp.customblocks.utils.config.ConfigManager; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.gson.Gson; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +@Getter +public class CustomBlocks extends JavaPlugin { + @Getter + public static CustomBlocks instance; + private CustomBlockManager customBlockManager; + private CommandManager commandManager; + private ConfigManager configManager; + private Gson gson; + + public void onEnable() { + instance = this; + this.gson = StorageUtils.getInstance() + .getGson() + .newBuilder() + .registerTypeAdapter(CustomBlock.class, new CustomBlockDeserializer()).setLenient() + .create(); + this.commandManager = new CommandManager(this, true); + commandManager.register(new CustomBlockCommand()); + this.customBlockManager = new CustomBlockManager(this); + customBlockManager.loadAll(); + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, ()-> { + customBlockManager.saveAll(); + }, 40L, 15*60*20L); + + this.configManager = new ConfigManager(this); + configManager.setupFiles(); + registerListeners(); + registerTasks(); + + } + + public void onDisable() { + customBlockManager.saveAll(); + instance = null; + } + + public void registerListeners() { + getServer().getPluginManager().registerEvents(new CustomBlockListener(this), this); + getServer().getPluginManager().registerEvents(new CustomBlockBreakListener(this), this); + getServer().getPluginManager().registerEvents(new CustomBlockPlaceListener(this), this); + } + + public void registerTasks() { + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, new TickAbleBlocksRunnable(), 40L, 20L); + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/CustomBlocksAPI.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/CustomBlocksAPI.java new file mode 100644 index 0000000..1ae07b3 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/CustomBlocksAPI.java @@ -0,0 +1,67 @@ +package net.crankedpvp.customblocks; + + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.customblocks.data.CustomBlockManager; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import net.crankedpvp.customblocks.utils.ChunkUtil; +import net.crankedpvp.crankedutils.utils.LocationUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.storageutils.utils.LocationDeserializer; +import net.crankedpvp.storageutils.utils.LocationSerializer; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; + +public class CustomBlocksAPI { + private static CustomBlockManager customBlockManager = CustomBlocks.getInstance().getCustomBlockManager(); + public static boolean isCustomBlockItem(ItemStack itemStack) { + if (ItemUtils.isAirOrNull(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.hasKey("cosmicType") && nbtItem.getString("cosmicType").equals("custom_block"); + } + + public static int getLevelFromItem(ItemStack itemStack) { + if (isCustomBlockItem(itemStack)) { + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound cosmicData = nbtItem.getOrCreateCompound("cosmicData"); + NBTCompound customBlockData = cosmicData.getOrCreateCompound("customBlockData"); + return customBlockData.getInteger("level"); + } + return 1; + } + + public static CustomBlockType getTypeFromItem(ItemStack itemStack) { + if (isCustomBlockItem(itemStack)) { + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound cosmicData = nbtItem.getOrCreateCompound("cosmicData"); + NBTCompound customBlockData = cosmicData.getOrCreateCompound("customBlockData"); + return CustomBlockType.valueOf(customBlockData.getString("type")); + } + return null; + } + + public static CustomBlock getCustomBlockData(Location location) { + if (isCustomBlock(location)) { + return customBlockManager.getCustomBlockData(location); + } + return null; + } + + public static boolean isCustomBlock(Location location) { + return customBlockManager.containsKey(LocationSerializer.serialize(location)); + } + + public static boolean chunkContainsCustomBlock(Location location, CustomBlockType type) { + for (String key : customBlockManager.getCacheKeys()) { + Location loc = LocationDeserializer.deserialize(key); + CustomBlock data = customBlockManager.getCustomBlockData(loc); + if (ChunkUtil.isLocationAInSameChunkAsLocationB(loc, location) && type == data.getType()) { + return true; + } + } + return false; + } + +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/commands/CustomBlockCommand.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/commands/CustomBlockCommand.java new file mode 100644 index 0000000..336be84 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/commands/CustomBlockCommand.java @@ -0,0 +1,41 @@ +package net.crankedpvp.customblocks.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.customblocks.CustomBlocks; +import net.crankedpvp.customblocks.guis.CustomBlocksGui; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("customblocks") +@Alias({"cblocks", "customblock"}) +public class CustomBlockCommand extends CommandBase { + + @Default + public void onDefault(CommandSender player) { + player.sendMessage(CC.translate("&e&l(!)&e Opening the Custom Blocks Menu...")); + CustomBlocksGui customBlocksGui = null; + try { + customBlocksGui = new CustomBlocksGui((Player) player); + } catch (IllegalAccessException | InstantiationException e) { + e.printStackTrace(); + } + customBlocksGui.getGui().open((Player) player); + } + + @SubCommand("give") + @Permission("cranked.admin") + public void onGive(Player player, String type, Integer level) { + player.getInventory().addItem(CustomBlockType.valueOf(type).build(level)); + player.sendMessage(CC.Green + "Received Custom Block!"); + } + + @SubCommand("reload") + @Permission("cranked.admin") + public void onReload(Player player) { + CustomBlocks.getInstance().getConfigManager().reloadFiles(); + player.sendMessage(CC.Green + "Reloaded Custom Blocks"); + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/data/CustomBlockManager.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/data/CustomBlockManager.java new file mode 100644 index 0000000..f02e11a --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/data/CustomBlockManager.java @@ -0,0 +1,23 @@ +package net.crankedpvp.customblocks.data; + +import net.crankedpvp.customblocks.CustomBlocks; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.crankedutils.utils.LocationUtils; +import net.crankedpvp.storageutils.utils.LocationDeserializer; +import net.crankedpvp.storageutils.utils.LocationSerializer; +import net.crankedpvp.storageutils.utils.SaveLoadManager; +import org.bukkit.Location; + +public class CustomBlockManager extends SaveLoadManager { + + + public CustomBlockManager(CustomBlocks plugin) { + super(plugin, CustomBlocks.getInstance().getGson(), "/data", CustomBlock.class); + } + + public CustomBlock getCustomBlockData(Location location) { + return getFromCache(LocationSerializer.serialize(location)); + } + +} + diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/AutoGrinderGui.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/AutoGrinderGui.java new file mode 100644 index 0000000..1a1e833 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/AutoGrinderGui.java @@ -0,0 +1,127 @@ +package net.crankedpvp.customblocks.guis; + + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.customblocks.struct.impl.AutoGrinder; +import net.crankedpvp.customblocks.utils.TimeUtil; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.cratekeys.items.CrateKeyItem; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.EnumMap; + +@Getter +public class AutoGrinderGui { + private PaginatedGui gui; + private static final ItemStack SEASON_KEY_ITEM = CrateKeyItem.getItem(CrateKeyType.SEASON_KEY); + private static final ItemStack ABYSS_KEY_ITEM = CrateKeyItem.getItem(CrateKeyType.ABYSS_KEY); + private static final ItemStack MYTHIC_KEY_ITEM = CrateKeyItem.getItem(CrateKeyType.MYTHIC_KEY); + + private static final EnumMap crateKeyTypeItemStackEnumMap = new EnumMap(CrateKeyType.class); + + + public AutoGrinderGui(Player player, AutoGrinder autoGrinder) { + crateKeyTypeItemStackEnumMap.put(CrateKeyType.SEASON_KEY, SEASON_KEY_ITEM); + crateKeyTypeItemStackEnumMap.put(CrateKeyType.ABYSS_KEY, ABYSS_KEY_ITEM); + crateKeyTypeItemStackEnumMap.put(CrateKeyType.MYTHIC_KEY, MYTHIC_KEY_ITEM); + this.gui = new PaginatedGui(3, 27, "Key Grinder Menu"); + this.gui.setItem(1, 2, getKeyClaimItem(autoGrinder, CrateKeyType.SEASON_KEY)); + this.gui.setItem(2, 2, getKeyClaimItem(autoGrinder, CrateKeyType.ABYSS_KEY)); + this.gui.setItem(3, 2, getKeyClaimItem(autoGrinder, CrateKeyType.MYTHIC_KEY)); + this.gui.setItem(2, 4, getStatusItem(autoGrinder)); + this.gui.setItem(2, 6, getExpClaimItem(autoGrinder)); + this.gui.setItem(2, 8, getUpgradeItem(autoGrinder)); + + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + + } + + public GuiItem getKeyClaimItem(AutoGrinder autoGrinder, CrateKeyType type) { + ItemStack item = new ItemBuilder(Material.GOLD_NUGGET) + .setName(type.getPrefixedName() + " &7(&f" + NumberUtils.formatMoney(autoGrinder.getKeys().getOrDefault(type, 0)) + "&7/" + autoGrinder.getMaxKeys(autoGrinder.getLevel()) + "&7)") + .addLoreLine("&7Click to claim the " + type.getName() + " keys in this key grinder!") + .colorize() + .build(); + return new GuiItem(item, event -> { + if (autoGrinder.getKeys().getOrDefault(type, 0) == 0) return; + while (event.getWhoClicked().getInventory().firstEmpty() != -1 && autoGrinder.getKeys().get(type) != 0) { + autoGrinder.removeKey(type); + PlayerUtils.giveOrDropProtectedItem((Player) event.getWhoClicked(), CrateKeyItem.getItem(type), 60); + } + this.gui.updateItem(event.getSlot(), getKeyClaimItem(autoGrinder, type)); + }); + } + + + public GuiItem getStatusItem(AutoGrinder autoGrinder) { + ItemStack activateButton = new ItemBuilder(Material.STONE_BUTTON, CC.translate("&e&lActivate Key Grinder")) + .addLoreLine("") + .addLoreLine(CC.translate("&eExpires in: &f" + ((autoGrinder.getLastActivated() + 3600000) - System.currentTimeMillis() <= 0 ? "✗" : TimeUtil.fancy((autoGrinder.getLastActivated() + 3600000) - System.currentTimeMillis())))) + .addLoreLine(CC.translate("&eStatus: " + (autoGrinder.isActive() ? "&a&lACTIVE" : "&c&lINACTIVE"))) + .addLoreLine(CC.translate("&ePrice: &2$&a" + NumberUtils.formatMoney(autoGrinder.getActivationPrice()))) + .addLoreLine("") + .addLoreLine(CC.translate("&7Click to activate this key grinder")) + .build(); + return new GuiItem(activateButton, event -> { + if (EconomyUtils.hasBalance((OfflinePlayer) event.getWhoClicked(), autoGrinder.getActivationPrice())) { + autoGrinder.activate((Player) event.getWhoClicked()); + EconomyUtils.withdrawBalance((OfflinePlayer) event.getWhoClicked(), autoGrinder.getActivationPrice()); + event.getWhoClicked().sendMessage(CC.translate("&c&l- " + NumberUtils.formatMoney(autoGrinder.getActivationPrice()))); + } else { + event.getWhoClicked().sendMessage(CC.translate("&c&l(!)&c You do not have enough money to activate this key grinder!")); + } + this.gui.updateItem(2, 4, getStatusItem(autoGrinder)); + + }); + } + + public GuiItem getExpClaimItem(AutoGrinder autoGrinder) { + ItemStack item = new ItemBuilder(Material.EXP_BOTTLE) + .setName("&a&lEXP &7(" + NumberUtils.formatMoney(autoGrinder.getExp()) + "&7)") + .addLoreLine("&7Click to claim the exp in this key grinder!") + .colorize() + .build(); + return new GuiItem(item, event -> { + if (autoGrinder.getExp() == 0) return; + ((Player) event.getWhoClicked()).giveExp(autoGrinder.getExp()); + event.getWhoClicked().sendMessage(CC.translate("&a&l+ " + NumberUtils.formatMoney(autoGrinder.getExp()) + " EXP")); + autoGrinder.setExp(0); + this.gui.updateItem(2, 6, getExpClaimItem(autoGrinder)); + + }); + } + + public GuiItem getUpgradeItem(AutoGrinder autoGrinder) { + ItemStack item = new ItemBuilder(Material.EMERALD) + .setName("&a&lUpgrade Key Grinder") + .addLoreLine("") + .addLoreLine("&aCurrent Level: &f" + autoGrinder.getLevel() + "&7/" + autoGrinder.getMaxLevel()) + .addLoreLine(autoGrinder.getLevel() == autoGrinder.getMaxLevel() ? "&aUpgrade Price: &c" + "MAX" : "&aUpgrade Price: &f$" + NumberUtils.formatMoney(autoGrinder.getUpgradePrice(autoGrinder.getLevel()))) + .addLoreLine("") + .addLoreLine("&7Click to upgrade the key grinder!") + .colorize() + .build(); + return new GuiItem(item, event -> { + if (autoGrinder.getLevel() == autoGrinder.getMaxLevel()) return; + if (!EconomyUtils.hasBalance((OfflinePlayer) event.getWhoClicked(), autoGrinder.getUpgradePrice(autoGrinder.getLevel()))) { + event.getWhoClicked().sendMessage(CC.translate("&c&l(!)&c You do not have enough money to upgrade your key grinder! ($" + NumberUtils.formatMoney(autoGrinder.getUpgradePrice(autoGrinder.getLevel())) + ")")); + return; + } + + EconomyUtils.withdrawBalance((OfflinePlayer) event.getWhoClicked(), autoGrinder.getUpgradePrice(autoGrinder.getLevel())); + event.getWhoClicked().sendMessage(CC.translate("&c&l- " + NumberUtils.formatMoney(autoGrinder.getUpgradePrice(autoGrinder.getLevel())))); + autoGrinder.setLevel(autoGrinder.getLevel() + 1); + this.gui.updateItem(2, 8, getUpgradeItem(autoGrinder)); + }); + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/CrateKeyOpenerGUI.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/CrateKeyOpenerGUI.java new file mode 100644 index 0000000..72d808e --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/CrateKeyOpenerGUI.java @@ -0,0 +1,168 @@ +package net.crankedpvp.customblocks.guis; + + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; + +import net.crankedpvp.crankedcore.utils.ExpBottleAPI; +import net.crankedpvp.crankedcore.utils.MoneyNotesAPI; +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.utils.ChunkUtil; +import net.crankedpvp.customblocks.utils.CrateKeyAPI; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.lootfilter.LootFilterAPI; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Chest; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Getter +public class CrateKeyOpenerGUI { + private final PaginatedGui customBlockGui; + + public CrateKeyOpenerGUI(CustomBlock customBlock, Player player) { + player.sendMessage(CC.translate("&a&l(!)&a Opening the Personal CrateKey Opener!")); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 5, 5); + this.customBlockGui = new PaginatedGui(3, 27, "CrateKey Custom Block Menu"); + + HashMap keys = CrateKeyAPI.getCrateKeysInInventory(player.getInventory()); + int tickets = 0; + for (Integer amount : keys.values()) { + tickets += amount; + } + + + ItemStack confirmButton = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 5); + ItemMeta meta = confirmButton.getItemMeta(); + meta.setDisplayName(CC.translate("&a&lConfirm Button")); + List lore = new ArrayList<>(); + lore.add(CC.translate("&7&nRight-Click&7 to open &f" + tickets + "&7 Cratekeys")); + meta.setLore(lore); + confirmButton.setItemMeta(meta); + + int finalTickets = tickets; + + this.customBlockGui.setItem(2, 3, new GuiItem(customBlock.getType().build(0))); + + + customBlockGui.setItem(2, 5, new GuiItem(confirmButton, event -> { + + if (finalTickets == 0) { + player.sendMessage(CC.translate("&c&l(!)&c You have no cratekeys in your inventory!")); + return; + } + + + + Location nearbyChest = ChunkUtil.getClosestChestLocation(customBlock.getLocation()); + if (nearbyChest != null) { + Chest chest = (Chest) nearbyChest.getBlock().getState(); + if (!ChunkUtil.isEmpty(chest.getInventory())) { + player.sendMessage(CC.translate("&c&l(!)&c Please empty the chest before opening new cratekeys!")); + return; + } + for (Map.Entry crate : keys.entrySet()) { + CrateKeyType type = crate.getKey(); + Integer amount = crate.getValue(); + while (amount != 0) { + if (!ChunkUtil.isEmpty(chest.getInventory())) { + Location newNearbyChest = ChunkUtil.getClosestChestLocation(customBlock.getLocation()); + if (newNearbyChest != null) { + chest = (Chest) newNearbyChest.getBlock().getState(); + } + } + ItemStack itemStack = LootTableAPI.getRandomLootItem(LootTableType.valueOf(type.name())); + if (!LootFilterAPI.isFiltered(player, LootTableType.valueOf(type.name()), itemStack)) { + if (MoneyNotesAPI.isMoneyNote(itemStack)) { + double moneyNoteVal = MoneyNotesAPI.getMoneyAmount(itemStack); + EconomyUtils.depositBalance(player, moneyNoteVal); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0f, 1.0f); + player.sendMessage(ChatColor.GREEN.toString() + ChatColor.BOLD.toString() + "+ $" + moneyNoteVal); + } else if (ExpBottleAPI.isXpBottle(itemStack)) { + int xpValue = ExpBottleAPI.getXpAmount(itemStack); + int exp = (player.getTotalExperience() + xpValue); + player.setTotalExperience(0); + player.setExp(0); + player.setLevel(0); + player.giveExp(exp); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0f, 1.0f); + player.sendMessage(ChatColor.GREEN.toString() + ChatColor.BOLD.toString() + "+ " + xpValue + " xp"); + } else { + chest.getInventory().addItem(itemStack); + } + } + amount--; + } + } + + } else { + player.sendMessage(CC.translate("&c&l(!)&c There are no nearby empty chests to fill with loot")); + return; + } + + + //remove slots from player inv + Inventory inventory = player.getInventory(); + for (ItemStack itemStack : inventory) { + if (CrankedCrateKeysAPI.isCrateKey(itemStack)) { + inventory.remove(itemStack); + } + } + player.getInventory().setContents(inventory.getContents()); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.VILLAGER_YES, 5, 5); + + })); + + customBlockGui.getFiller().fillBorder(new GuiItem(new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7)).setName(CC.translate("&7")).build())); + + customBlockGui.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemStack clearButton = new ItemBuilder(Material.HOPPER, CC.translate("&c&lClear Chests")) + .addLoreLine(CC.translate("&7Click here to clear all nearby chests.")) + .build(); + customBlockGui.setItem(2, 7, new GuiItem(clearButton, event -> { + + + int counter = 0; + for (Location location : ChunkUtil.getNearbyChests(customBlock.getLocation())) { + Chest chest = (Chest) location.getBlock().getState(); + if (!ChunkUtil.isEmpty(chest.getInventory())) { + chest.getInventory().clear(); + counter++; + } + } + if (counter == 0) { + player.sendMessage(CC.translate("&c&l(!)&c There are no nearby chests to clear.")); + return; + } + + player.closeInventory(); + player.playSound(player.getLocation(), Sound.VILLAGER_YES, 5, 5); + player.sendMessage(CC.translate("&c&l(!)&c Cleared " + counter + " nearby chests.")); + + })); + + + } + + +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/CustomBlocksGui.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/CustomBlocksGui.java new file mode 100644 index 0000000..448ff9f --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/CustomBlocksGui.java @@ -0,0 +1,30 @@ +package net.crankedpvp.customblocks.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import net.crankedpvp.customblocks.struct.abilities.LevelAble; +import org.bukkit.entity.Player; + +@Getter +public class CustomBlocksGui { + private final PaginatedGui gui; + + public CustomBlocksGui(Player player) throws IllegalAccessException, InstantiationException { + this.gui = new PaginatedGui(3, 27, "Cranked CustomBlocks"); + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + for (CustomBlockType type : CustomBlockType.values()) { + this.gui.addItem(new GuiItem(type.getCustomBlockClass().newInstance() instanceof LevelAble ? type.build(1) : type.build(0), event -> { + if (player.isOp()) { + try { + PlayerUtils.giveOrDropProtectedItem(player, type.getCustomBlockClass().newInstance() instanceof LevelAble ? type.build(1) : type.build(0), 60); + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + } + })); + } + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/SlotBotOpenerGUI.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/SlotBotOpenerGUI.java new file mode 100644 index 0000000..8137304 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/guis/SlotBotOpenerGUI.java @@ -0,0 +1,168 @@ +package net.crankedpvp.customblocks.guis; + + + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; + +import net.crankedpvp.crankedcore.utils.ExpBottleAPI; +import net.crankedpvp.crankedcore.utils.MoneyNotesAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.utils.ChunkUtil; +import net.crankedpvp.customblocks.utils.SlotbotsAPI; +import net.crankedpvp.lootfilter.LootFilterAPI; + +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.data.LootTable; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.slotbot.SlotBotAPI; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Chest; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.List; + +@Getter +public class SlotBotOpenerGUI { + + private final PaginatedGui customBlockGui; + + public SlotBotOpenerGUI(CustomBlock customBlock, Player p) { + p.sendMessage(CC.translate("&a&l(!)&a Opening the Personal Slotbot Opener!")); + p.playSound(p.getLocation(), Sound.CHEST_OPEN, 5, 5); + this.customBlockGui = new PaginatedGui(3, 27, "Slotbot Custom Block Menu"); + + int tickets = SlotbotsAPI.getSlotsInInv(p); + + + + ItemStack confirmButton = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 5); + ItemMeta meta = confirmButton.getItemMeta(); + meta.setDisplayName(CC.translate("&a&lConfirm Button")); + List lore = new ArrayList<>(); + lore.add(CC.translate("&7&nRight-Click&7 to open &f" + tickets + "&7 Slotbot Tickets")); + meta.setLore(lore); + confirmButton.setItemMeta(meta); + + + this.customBlockGui.setItem(2, 3, new GuiItem(customBlock.getType().build(0))); + + + customBlockGui.setItem(2, 5, new GuiItem(confirmButton, event -> { + + + if (tickets == 0) { + p.sendMessage(CC.translate("&c&l(!)&c You have no slots in your inventory!")); + return; + } + + int a = tickets; + + Location nearbyChest = ChunkUtil.getClosestChestLocation(customBlock.getLocation()); + if (nearbyChest != null) { + Chest chest = (Chest) nearbyChest.getBlock().getState(); + if (!ChunkUtil.isEmpty(chest.getInventory())) { + p.sendMessage(CC.translate("&c&l(!)&c Please empty the chest before opening new slotbots!")); + return; + } + //remove slots from player inv + Inventory inventory = p.getInventory(); + for (ItemStack itemStack : inventory) { + if (SlotBotAPI.isSlotBot(itemStack)) { + inventory.remove(itemStack); + } + } + p.getInventory().setContents(inventory.getContents()); + p.closeInventory(); + p.playSound(p.getLocation(), Sound.VILLAGER_YES, 5, 5); + + while (a != 0) { + + if (!ChunkUtil.isEmpty(chest.getInventory())) { + Location newNearbyChest = ChunkUtil.getClosestChestLocation(chest.getLocation()); + if (newNearbyChest != null) { + chest = (Chest) newNearbyChest.getBlock().getState(); + } + } + final ItemStack itemStack = LootTableAPI.getRandomLootItem(LootTableType.SLOTBOT); + if (!LootFilterAPI.isFiltered(p, LootTableType.SLOTBOT, itemStack)) { + if (MoneyNotesAPI.isMoneyNote(itemStack)) { + double moneyNoteVal = MoneyNotesAPI.getMoneyAmount(itemStack); + EconomyUtils.depositBalance(p, moneyNoteVal); + p.playSound(p.getLocation(), Sound.ORB_PICKUP, 1.0f, 1.0f); + p.sendMessage(ChatColor.GREEN.toString() + ChatColor.BOLD.toString() + "+ $" + moneyNoteVal); + } else if (ExpBottleAPI.isXpBottle(itemStack)) { + int xpValue = ExpBottleAPI.getXpAmount(itemStack); + int exp = (p.getTotalExperience() + xpValue); + p.setTotalExperience(0); + p.setExp(0); + p.setLevel(0); + p.giveExp(exp); + p.playSound(p.getLocation(), Sound.ORB_PICKUP, 1.0f, 1.0f); + p.sendMessage(ChatColor.GREEN.toString() + ChatColor.BOLD.toString() + "+ " + xpValue + " xp"); + } else { + if (itemStack == null) continue; + chest.getInventory().addItem(itemStack); + } + } + a--; + } + + + } else { + p.sendMessage(CC.translate("&c&l(!)&c There are no nearby empty chests to fill with loot")); + } + + + + + + })); + + customBlockGui.getFiller().fillBorder(new GuiItem(new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7)).setName(CC.translate("&7")).build())); + + customBlockGui.setDefaultClickAction(event -> event.setCancelled(true)); + + + ItemStack clearButton = new ItemBuilder(Material.HOPPER, CC.translate("&c&lClear Chests")) + .addLoreLine(CC.translate("&7Click here to clear all nearby chests.")) + .build(); + customBlockGui.setItem(2, 7, new GuiItem(clearButton, event -> { + + + int counter = 0; + for (Location location : ChunkUtil.getNearbyChests(customBlock.getLocation())) { + Chest chest = (Chest) location.getBlock().getState(); + + if (!ChunkUtil.isEmpty(chest.getInventory())) { + chest.getInventory().clear(); + counter++; + } + } + if (counter == 0) { + p.sendMessage(CC.translate("&c&l(!)&c There are no nearby chests to clear.")); + + return; + } + + p.closeInventory(); + p.playSound(p.getLocation(), Sound.VILLAGER_YES, 5, 5); + p.sendMessage(CC.translate("&c&l(!)&c Cleared " + counter + " nearby chests.")); + + + })); + + + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockBreakListener.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockBreakListener.java new file mode 100644 index 0000000..2cfd824 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockBreakListener.java @@ -0,0 +1,75 @@ +package net.crankedpvp.customblocks.listeners; + + +import net.crankedpvp.customblocks.CustomBlocks; +import net.crankedpvp.customblocks.CustomBlocksAPI; +import net.crankedpvp.customblocks.data.CustomBlockManager; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import net.crankedpvp.customblocks.struct.abilities.LevelAble; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.EntityExplodeEvent; + +import java.util.List; + +public class CustomBlockBreakListener implements Listener { + private CustomBlockManager customBlockManager; + private CustomBlocks customBlocks; + + public CustomBlockBreakListener(CustomBlocks plugin) { + this.customBlocks = plugin; + this.customBlockManager = plugin.getCustomBlockManager(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onBreak(BlockBreakEvent event) { + if (event.isCancelled()) return; + if (CustomBlocksAPI.isCustomBlock(event.getBlock().getLocation())) { + CustomBlock customBlockData = CustomBlocksAPI.getCustomBlockData(event.getBlock().getLocation()); + CustomBlockType type = customBlockData.getType(); + + if (!EconomyUtils.hasBalance(event.getPlayer(), type.getMinePrice())) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You do not have enough money to mine the " + type.getDisplayName() + " Custom Block!")); + event.setCancelled(true); + return; + } + int level = 0; + if (customBlockData instanceof LevelAble) { + level = ((LevelAble) customBlockData).getLevel(); + } + event.setCancelled(true); + event.getBlock().setType(Material.AIR); + event.getBlock().getLocation().getWorld().dropItemNaturally(event.getBlock().getLocation(), customBlockData.getType().build(level)); + EconomyUtils.withdrawBalance(event.getPlayer(), type.getMinePrice()); + event.getPlayer().sendMessage(CC.translate("&c&l- $" + NumberUtils.formatMoney(type.getMinePrice()))); + customBlockManager.removeFromCache(customBlockData); + } + } + + @EventHandler + public void onExplode(EntityExplodeEvent event) { + List blockList = event.blockList(); + for (Block block : blockList) { + if (block.getType() != Material.NOTE_BLOCK) continue; + if (CustomBlocksAPI.isCustomBlock(block.getLocation())) { + block.getDrops().clear(); + CustomBlock customBlockData = CustomBlocksAPI.getCustomBlockData(block.getLocation()); + block.setType(Material.AIR); + int level = 0; + if (customBlockData instanceof LevelAble) { + level = ((LevelAble) customBlockData).getLevel(); + } + block.getLocation().getWorld().dropItemNaturally(block.getLocation(), customBlockData.getType().build(level)); + customBlockManager.removeFromCache(customBlockData); + } + } + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockListener.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockListener.java new file mode 100644 index 0000000..d603be4 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockListener.java @@ -0,0 +1,29 @@ +package net.crankedpvp.customblocks.listeners; + +import net.crankedpvp.customblocks.CustomBlocks; +import net.crankedpvp.customblocks.data.CustomBlockManager; +import net.crankedpvp.customblocks.struct.CustomBlock; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class CustomBlockListener implements Listener { + private CustomBlockManager customBlockManager; + private CustomBlocks customBlocks; + + public CustomBlockListener(CustomBlocks plugin) { + this.customBlocks = plugin; + this.customBlockManager = plugin.getCustomBlockManager(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onInteract(PlayerInteractEvent event) { + if (event.getAction() == Action.RIGHT_CLICK_BLOCK && !event.isCancelled() && customBlockManager.getCustomBlockData(event.getClickedBlock().getLocation()) != null) { + event.setCancelled(true); + CustomBlock customBlock = customBlockManager.getCustomBlockData(event.getClickedBlock().getLocation()); + customBlock.onClick(event.getPlayer()); + } + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockPlaceListener.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockPlaceListener.java new file mode 100644 index 0000000..cf12a9b --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/listeners/CustomBlockPlaceListener.java @@ -0,0 +1,65 @@ +package net.crankedpvp.customblocks.listeners; + + +import net.crankedpvp.customblocks.CustomBlocks; +import net.crankedpvp.customblocks.CustomBlocksAPI; +import net.crankedpvp.customblocks.data.CustomBlockManager; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import net.crankedpvp.customblocks.struct.abilities.LevelAble; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; + +public class CustomBlockPlaceListener implements Listener { + private CustomBlockManager customBlockManager; + private CustomBlocks customBlocks; + + public CustomBlockPlaceListener(CustomBlocks plugin) { + this.customBlocks = plugin; + this.customBlockManager = plugin.getCustomBlockManager(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlace(BlockPlaceEvent event) throws IllegalAccessException, InstantiationException { + ItemStack item = event.getItemInHand(); + if (event.isCancelled()) return; + if (CustomBlocksAPI.isCustomBlockItem(item)) { + CustomBlockType type = CustomBlocksAPI.getTypeFromItem(item); + + if (FactionUtils.isWilderness(event.getBlock().getLocation())) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You cannot place custom blocks in wilderness!")); + event.setCancelled(true); + return; + } + if (!EconomyUtils.hasBalance(event.getPlayer(), type.getPlacePrice())) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You do not have enough money to place the " + type.getDisplayName() + " Custom Block!")); + event.setCancelled(true); + return; + } + + if (CustomBlocksAPI.chunkContainsCustomBlock(event.getBlock().getLocation(), type)) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c This chunk already contains a " + type.getDisplayName() + " Custom Block!")); + event.setCancelled(true); + return; + } + + event.getPlayer().sendMessage(CC.translate("&c&l- $" + NumberUtils.formatMoney(type.getPlacePrice()))); + EconomyUtils.withdrawBalance(event.getPlayer(), type.getPlacePrice()); + + CustomBlock customBlock = type.getCustomBlockClass().newInstance(); + customBlock.setLocation(event.getBlock().getLocation()); + + if (customBlock instanceof LevelAble) { + ((LevelAble) customBlock).setLevel(CustomBlocksAPI.getLevelFromItem(item)); + } + customBlockManager.addToCache(customBlock); + } + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/CustomBlock.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/CustomBlock.java new file mode 100644 index 0000000..66bafcc --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/CustomBlock.java @@ -0,0 +1,36 @@ +package net.crankedpvp.customblocks.struct; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.LocationUtils; +import net.crankedpvp.storageutils.utils.KeyToSave; +import net.crankedpvp.storageutils.utils.LocationDeserializer; +import net.crankedpvp.storageutils.utils.LocationSerializer; +import org.bukkit.Location; +import org.bukkit.entity.Player; + + +@Getter +@RequiredArgsConstructor +@Setter +public abstract class CustomBlock implements KeyToSave { + private Location location; + private final CustomBlockType type; + + @Override + public String getKey() { + return LocationSerializer.serialize(location); + } + + @Override + public void setKey(String key) { + this.location = LocationDeserializer.deserialize(key); + } + + public void onClick(Player clicker) { + + } + + +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/CustomBlockType.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/CustomBlockType.java new file mode 100644 index 0000000..3295c20 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/CustomBlockType.java @@ -0,0 +1,84 @@ +package net.crankedpvp.customblocks.struct; + + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.customblocks.struct.impl.*; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; + +@Getter +@AllArgsConstructor +public enum CustomBlockType { + + SLOTBOT_OPENER("Roll Tickets Opener", ChatColor.GOLD, 250000, 250000, Arrays.asList( + CC.translate("&7Roll all your tickets"), + CC.translate("&7at once using the roll bot opener."), + "", + CC.translate("&7Place chests around the block"), + CC.translate("&7to collect all the loot from the bot.") + ), SlotOpener.class, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZGUxYzJhNWM0ZDRjMzVmYzM3NTQyOTVmMzljMzMzZWY2NzhiZDJlZGFkOWM4OGYyZDE2ODBmMTQ5NjgyIn19fQ=="), + + KEY_OPENER("Key Opener", ChatColor.AQUA, 250000, 250000, Arrays.asList( + CC.translate("&7Open all your cratekeys"), + CC.translate("&7at once using the key opener."), + "", + CC.translate("&7Place chests around the block"), + CC.translate("&7to collect all the loot from the keys.") + ), KeyOpener.class, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjk4YmM2M2YwNWY2Mzc4YmYyOWVmMTBlM2Q4MmFjYjNjZWI3M2E3MjBiZjgwZjMwYmM1NzZkMGFkOGM0MGNmYiJ9fX0="), + + AUTO_GRINDER("Key Grinder", ChatColor.YELLOW, 250000, 250000, Arrays.asList( + CC.translate("&7Automatically grinds crate keys"), + CC.translate("&7while being placed and activated."), + "", + CC.translate("&7Dug up from the deep depths of"), + CC.translate("&7the gold mines, this custom block is"), + CC.translate("&7essential for grinding Keys.") + ), AutoGrinder.class, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYjIwNjU3ZTI0YjU2ZTFiMmY4ZmMyMTlkYTFkZTc4OGMwYzI0ZjM2Mzg4YjFhNDA5ZDBjZDJkOGRiYTQ0YWEzYiJ9fX0="); + + private final String displayName; + private final ChatColor color; + private final double minePrice; + private final double placePrice; + private final List lore; + private final Class customBlockClass; + private final String skin; + + + public ItemStack build(int level) { + String title = level != 0 ? getColor() + "&l" + getDisplayName() + " &7(&fLVL " + level + "&7)": getColor() + "&l" + getDisplayName(); + ItemStack block = new ItemBuilder(SkullUtils.getSkull(getSkin())) + .setName(title) + .addLoreLine(getColor() + "Price to Place: &f$" + NumberUtils.formatMoney(getPlacePrice())) + .addLoreLine(getColor() + "Price to Mine: &f$" + NumberUtils.formatMoney(getMinePrice())) + .addLoreLine("") + .addLore(getLore()) + .addLoreLine("") + .addLoreLine("&7Place custom block to use!") + .colorize() + .build(); + NBTItem nbtItem = new NBTItem(block); + NBTCompound cosmicData = nbtItem.getOrCreateCompound("cosmicData"); + NBTCompound cosmicData2 = cosmicData.getOrCreateCompound("customBlockData"); + nbtItem.setString("cosmicType", "custom_block"); + if (level != 0) { + cosmicData2.setInteger("level", level); + } + cosmicData2.setString("type", name()); + //cosmicData.setNBTBase("customBlockData", cosmicData2.get()); + //nbtItem.setNBTBase("cosmicData", cosmicData.get()); + return nbtItem.getItem(); + } + + +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/ActivateAble.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/ActivateAble.java new file mode 100644 index 0000000..3aca6ea --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/ActivateAble.java @@ -0,0 +1,11 @@ +package net.crankedpvp.customblocks.struct.abilities; + +import org.bukkit.entity.Player; + +public interface ActivateAble { + boolean isActive(); + void activate(Player player); + double getActivationPrice(); + void setLastActivated(long lastActivated); + +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/LevelAble.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/LevelAble.java new file mode 100644 index 0000000..1b489bd --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/LevelAble.java @@ -0,0 +1,7 @@ +package net.crankedpvp.customblocks.struct.abilities; + +public interface LevelAble { + int getMaxLevel(); + int getLevel(); + void setLevel(int lvl); +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/TickAble.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/TickAble.java new file mode 100644 index 0000000..7611010 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/abilities/TickAble.java @@ -0,0 +1,5 @@ +package net.crankedpvp.customblocks.struct.abilities; + +public interface TickAble { + void onTick(); +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/AutoGrinder.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/AutoGrinder.java new file mode 100644 index 0000000..efd5f9a --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/AutoGrinder.java @@ -0,0 +1,147 @@ +package net.crankedpvp.customblocks.struct.impl; + +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; +import net.crankedpvp.customblocks.CustomBlocks; +import net.crankedpvp.customblocks.guis.AutoGrinderGui; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import net.crankedpvp.customblocks.struct.abilities.ActivateAble; +import net.crankedpvp.customblocks.struct.abilities.LevelAble; +import net.crankedpvp.customblocks.struct.abilities.TickAble; +import net.crankedpvp.customblocks.utils.config.ConfigManager; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +@Getter +@Setter +public class AutoGrinder extends CustomBlock implements LevelAble, TickAble, ActivateAble { + private Integer exp; + private Map keys; + private Integer level; + private Long lastActivated; + + public AutoGrinder() { + super(CustomBlockType.AUTO_GRINDER); + this.level = 0; + this.exp = 0; + this.keys = new HashMap<>(); + this.lastActivated = 0L; + } + + @SneakyThrows + @Override + public void onClick(Player clicker) { + AutoGrinderGui autoGrinderGui = new AutoGrinderGui(clicker, this); + autoGrinderGui.getGui().open(clicker); + } + + @Override + public int getMaxLevel() { + return 5; + } + + @Override + public int getLevel() { + return level; + } + + @Override + public void setLevel(int lvl) { + this.level = lvl; + } + + @Override + public void onTick() { + if (!isActive()) return; + double commonKeyChance = CustomBlocks.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.SETTINGS).getDouble("commonKeyChance") * 0.01 * level; + double rareKeyChance = CustomBlocks.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.SETTINGS).getDouble("rareKeyChance") * 0.01 * level; + double mythicKeyChance = CustomBlocks.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.SETTINGS).getDouble("mythicKeyChance") * 0.01 * level; + + int expPer = CustomBlocks.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.SETTINGS).getInt("expPer") * level; + exp += expPer; + + if (Math.random() < mythicKeyChance) { + if (keys.getOrDefault(CrateKeyType.MYTHIC_KEY, 0) >= getMaxKeys(level)) return; + addKey(CrateKeyType.MYTHIC_KEY); + } else if (Math.random() < rareKeyChance) { + if (keys.getOrDefault(CrateKeyType.ABYSS_KEY, 0) >= getMaxKeys(level)) return; + addKey(CrateKeyType.ABYSS_KEY); + } else if (Math.random() < commonKeyChance) { + if (keys.getOrDefault(CrateKeyType.SEASON_KEY, 0) >= getMaxKeys(level)) return; + addKey(CrateKeyType.SEASON_KEY); + } + + } + + @Override + public boolean isActive() { + return System.currentTimeMillis() < lastActivated + 3600000; + } + + @Override + public void activate(Player player) { + this.lastActivated = System.currentTimeMillis(); + } + + @Override + public double getActivationPrice() { + return CustomBlocks.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.SETTINGS).getInt("autoGrinderActivationPrice"); + } + + @Override + public void setLastActivated(long lastActivated) { + this.lastActivated = lastActivated; + } + + public void addKey(CrateKeyType type) { + if (!keys.containsKey(type)) { + keys.put(type, 1); + } else { + int current = keys.get(type); + keys.put(type, current + 1); + } + } + + public void removeKey(CrateKeyType type) { + keys.put(type, keys.get(type)-1); + } + + + public double getUpgradePrice(int currentLevel) { + switch (currentLevel) { + case 1: + return 50000000; + case 2: + return 100000000; + case 3: + return 250000000; + case 4: + return 500000000; + case 5: + return 1000000000; + } + return 5000000; + } + + public int getMaxKeys(int level) { + switch (level) { + case 1: + return 512; + case 2: + return 1024; + case 3: + return 2048; + case 4: + return 3456; + case 5: + return 5504; + } + return 512; + } + +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/KeyOpener.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/KeyOpener.java new file mode 100644 index 0000000..13be6db --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/KeyOpener.java @@ -0,0 +1,25 @@ +package net.crankedpvp.customblocks.struct.impl; + +import net.crankedpvp.customblocks.guis.CrateKeyOpenerGUI; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class KeyOpener extends CustomBlock { + private List items; + + public KeyOpener() { + super(CustomBlockType.KEY_OPENER); + this.items = new ArrayList<>(); + } + + @Override + public void onClick(Player clicker) { + CrateKeyOpenerGUI crateKeyOpenerGUI = new CrateKeyOpenerGUI(this, clicker); + crateKeyOpenerGUI.getCustomBlockGui().open(clicker); + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/SlotOpener.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/SlotOpener.java new file mode 100644 index 0000000..5c3659e --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/impl/SlotOpener.java @@ -0,0 +1,20 @@ +package net.crankedpvp.customblocks.struct.impl; + +import net.crankedpvp.customblocks.guis.SlotBotOpenerGUI; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import org.bukkit.entity.Player; + +public class SlotOpener extends CustomBlock { + + + public SlotOpener() { + super(CustomBlockType.SLOTBOT_OPENER); + } + + @Override + public void onClick(Player clicker) { + SlotBotOpenerGUI slotBotOpenerGUI = new SlotBotOpenerGUI(this, clicker); + slotBotOpenerGUI.getCustomBlockGui().open(clicker); + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/typeadapters/CustomBlockDeserializer.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/typeadapters/CustomBlockDeserializer.java new file mode 100644 index 0000000..0d1b028 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/struct/typeadapters/CustomBlockDeserializer.java @@ -0,0 +1,39 @@ +package net.crankedpvp.customblocks.struct.typeadapters; + + +import lombok.SneakyThrows; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.CustomBlockType; +import net.crankedpvp.storageutils.gson.*; + +import java.lang.reflect.Type; + +public class CustomBlockDeserializer implements JsonDeserializer { + + @SneakyThrows + @Override + public CustomBlock deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = jsonElement.getAsJsonObject(); + CustomBlockType cType = CustomBlockType.valueOf(jsonObject.get("type").getAsString()); + //CustomBlock customBlock = cType.getCustomBlockClass().newInstance(); + //customBlock.setLocation(LocationUtils.getLocationFromString(jsonObject.get("location").getAsString(), false)); + + + + /*if (customBlock instanceof LevelAble) { + ((LevelAble) customBlock).setLevel(jsonObject.get("level").getAsInt()); + } + + if (customBlock instanceof ActivateAble) { + ((ActivateAble) customBlock).setLastActivated(jsonObject.get("lastActivated").getAsLong()); + } + + if (customBlock instanceof AutoGrinder) { + ((AutoGrinder) customBlock).setGrinderKeys(jsonObject.get("grinderKeys").getAsInt()); + ((AutoGrinder) customBlock).setExp(jsonObject.get("exp").getAsInt()); + }*/ + + return context.deserialize(jsonElement, cType.getCustomBlockClass()); + } + +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/tasks/TickAbleBlocksRunnable.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/tasks/TickAbleBlocksRunnable.java new file mode 100644 index 0000000..2cfb179 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/tasks/TickAbleBlocksRunnable.java @@ -0,0 +1,17 @@ +package net.crankedpvp.customblocks.tasks; + +import net.crankedpvp.customblocks.CustomBlocks; +import net.crankedpvp.customblocks.struct.CustomBlock; +import net.crankedpvp.customblocks.struct.abilities.TickAble; +import org.bukkit.scheduler.BukkitRunnable; + +public class TickAbleBlocksRunnable extends BukkitRunnable { + @Override + public void run() { + for (CustomBlock customBlock : CustomBlocks.getInstance().getCustomBlockManager().getCacheValues()) { + if (customBlock instanceof TickAble) { + ((TickAble) customBlock).onTick(); + } + } + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/ChunkUtil.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/ChunkUtil.java new file mode 100644 index 0000000..fa02838 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/ChunkUtil.java @@ -0,0 +1,116 @@ +package net.crankedpvp.customblocks.utils; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Chest; +import org.bukkit.craftbukkit.v1_8_R3.CraftChunk; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class ChunkUtil { + public static boolean isLocationAInSameChunkAsLocationB(Location aLocation, Location bLocation) { + double aX = Math.floor(aLocation.getBlockX() >> 4); + double aZ = Math.floor(aLocation.getBlockZ() >> 4); + double bX = Math.floor(bLocation.getBlockX() >> 4); + double bZ = Math.floor(bLocation.getBlockZ() >> 4); + + return aX == bX && aZ == bZ; + + } + + public static Chunk getIfLoaded(int chunkX, int chunkZ, World bWorld) { + net.minecraft.server.v1_8_R3.World world = ((CraftWorld) bWorld).getHandle(); + net.minecraft.server.v1_8_R3.Chunk theChunk = world.getChunkIfLoaded(chunkX, chunkZ); + return (theChunk == null) ? null : theChunk.bukkitChunk; + } + + public static List getEntities(Chunk chunk) { + net.minecraft.server.v1_8_R3.Chunk nmsChunk = ((CraftChunk) chunk).getHandle(); + List toReturn = new ArrayList<>(); + if (nmsChunk == null) return toReturn; + for (List entities : nmsChunk.entitySlices) { + for (net.minecraft.server.v1_8_R3.Entity entity : entities) { + if (entity.getBukkitEntity() == null) continue; + toReturn.add(entity.getBukkitEntity()); + } + } + return toReturn; + } + + public static boolean isEmpty(Inventory inv) { + for (ItemStack item : inv.getContents()) { + if (item != null) { + return false; + } + } + return true; + } + + public static List getNearbyChests(Location location) { + List chests = new ArrayList<>(); + + if (location.clone().add(-1, 0, 0).getBlock().getType() == Material.CHEST || location.clone().add(-1, 0, 0).getBlock().getType() == Material.TRAPPED_CHEST) { + Chest chest = (Chest) location.clone().add(-1, 0, 0).getBlock().getState(); + chests.add(chest.getLocation()); + + } + if (location.clone().add(0, 0, -1).getBlock().getType() == Material.CHEST || location.clone().add(0, 0, -1).getBlock().getType() == Material.TRAPPED_CHEST) { + Chest chest = (Chest) location.clone().add(0, 0, -1).getBlock().getState(); + chests.add(chest.getLocation()); + + } + + + if (location.clone().add(1, 0, 0).getBlock().getType() == Material.CHEST || location.clone().add(1, 0, 0).getBlock().getType() == Material.TRAPPED_CHEST) { + Chest chest = (Chest) location.clone().add(1, 0, 0).getBlock().getState(); + chests.add(chest.getLocation()); + + } + + if (location.clone().add(0, 0, 1).getBlock().getType() == Material.CHEST || location.clone().add(0, 0, 1).getBlock().getType() == Material.TRAPPED_CHEST) { + Chest chest = (Chest) location.clone().add(0, 0, 1).getBlock().getState(); + chests.add(chest.getLocation()); + + } + return chests; + } + + public static Location getClosestChestLocation(Location location) { + if (location.clone().add(-1, 0, 0).getBlock().getType() == Material.CHEST || location.clone().add(-1, 0, 0).getBlock().getType() == Material.TRAPPED_CHEST) { + Chest chest = (Chest) location.clone().add(-1, 0, 0).getBlock().getState(); + if (isEmpty(chest.getInventory())) { + return location.clone().add(-1, 0, 0); + } + } + if (location.clone().add(0, 0, -1).getBlock().getType() == Material.CHEST || location.clone().add(0, 0, -1).getBlock().getType() == Material.TRAPPED_CHEST) { + Chest chest = (Chest) location.clone().add(0, 0, -1).getBlock().getState(); + if (isEmpty(chest.getInventory())) { + return location.clone().add(0, 0, -1); + } + } + + + if (location.clone().add(1, 0, 0).getBlock().getType() == Material.CHEST || location.clone().add(1, 0, 0).getBlock().getType() == Material.TRAPPED_CHEST) { + Chest chest = (Chest) location.clone().add(1, 0, 0).getBlock().getState(); + if (isEmpty(chest.getInventory())) { + return location.clone().add(1, 0, 0); + } + } + + if (location.clone().add(0, 0, 1).getBlock().getType() == Material.CHEST || location.clone().add(0, 0, 1).getBlock().getType() == Material.TRAPPED_CHEST) { + Chest chest = (Chest) location.clone().add(0, 0, 1).getBlock().getState(); + if (isEmpty(chest.getInventory())) { + return location.clone().add(0, 0, 1); + } + } + return null; + + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/CrateKeyAPI.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/CrateKeyAPI.java new file mode 100644 index 0000000..67462ba --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/CrateKeyAPI.java @@ -0,0 +1,31 @@ +package net.crankedpvp.customblocks.utils; + + +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.cratekeys.items.CrateKeyItem; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; + +public class CrateKeyAPI { + public static HashMap getCrateKeysInInventory(Inventory inventory) { + HashMap keys = new HashMap<>(); + + for (ItemStack itemStack : inventory) { + if (ItemUtils.isAirOrNull(itemStack)) continue; + if (CrankedCrateKeysAPI.isCrateKey(itemStack)) { + CrateKeyType crateType = CrateKeyItem.getCrateType(itemStack); + if (keys.containsKey(crateType)) { + int amount = keys.get(crateType); + keys.put(crateType, amount + itemStack.getAmount()); + } else { + keys.put(crateType, itemStack.getAmount()); + } + } + } + return keys; + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/SlotbotsAPI.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/SlotbotsAPI.java new file mode 100644 index 0000000..3bd159f --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/SlotbotsAPI.java @@ -0,0 +1,20 @@ +package net.crankedpvp.customblocks.utils; + +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.cratekeys.items.CrateKeyItem; +import net.crankedpvp.slotbot.SlotBotAPI; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class SlotbotsAPI { + public static int getSlotsInInv(Player player) { + int slots =0; + for (ItemStack itemStack : player.getInventory()) { + if (SlotBotAPI.isSlotBot(itemStack)) { + slots += itemStack.getAmount(); + } + } + return slots; + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/TimeUtil.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/TimeUtil.java new file mode 100644 index 0000000..8319a93 --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/TimeUtil.java @@ -0,0 +1,125 @@ +package net.crankedpvp.customblocks.utils; + +import java.sql.Timestamp; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class TimeUtil { + + private TimeUtil() { + throw new RuntimeException("Cannot instantiate a utility class."); + } + + public static Timestamp addDuration(long duration) { + return truncateTimestamp(new Timestamp(System.currentTimeMillis() + duration)); + } + + public static Timestamp truncateTimestamp(Timestamp timestamp) { + if (timestamp.toLocalDateTime().getYear() > 2037) { + timestamp.setYear(2037); + } + return timestamp; + } + + public static Timestamp addDuration(Timestamp timestamp) { + return truncateTimestamp(new Timestamp(System.currentTimeMillis() + timestamp.getTime())); + } + + public static Timestamp fromMillis(long millis) { + return new Timestamp(millis); + } + + public static Timestamp getCurrentTimestamp() { + return new Timestamp(System.currentTimeMillis()); + } + + public static long getCurrentMillis() { + return System.currentTimeMillis(); + } + + + + public static String fancy(long seconds) { + seconds = seconds/1000; + int day = (int) TimeUnit.SECONDS.toDays(seconds); + long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24); + long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60); + long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60); + + return hours + "h " + minute + "m " + second + "s "; + + } + + public static String millisToRoundedTime(long millis) { + millis += 1L; // for good shit men + + long seconds = millis / 1000L; + long minutes = seconds / 60L; + long hours = minutes / 60L; + long days = hours / 24L; + long weeks = days / 7L; + long months = weeks / 4L; + long years = months / 12L; + + if (years > 0) { + return years + " year" + (years == 1 ? "" : "s"); + } else if (months > 0) { + return months + " month" + (months == 1 ? "" : "s"); + } else if (weeks > 0) { + return weeks + " week" + (weeks == 1 ? "" : "s"); + } else if (days > 0) { + return days + " day" + (days == 1 ? "" : "s"); + } else if (hours > 0) { + return hours + " hour" + (hours == 1 ? "" : "s"); + } else if (minutes > 0) { + return minutes + " minute" + (minutes == 1 ? "" : "s"); + } else { + return seconds + " second" + (seconds == 1 ? "" : "s"); + } + } + + public static long parseTime(String time) { + long totalTime = 0L; + boolean found = false; + Matcher matcher = Pattern.compile("\\d+\\D+").matcher(time); + + while (matcher.find()) { + String s = matcher.group(); + Long value = Long.parseLong(s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")[0]); + String type = s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")[1]; + switch (type) { + case "s": + totalTime += value; + found = true; + break; + case "m": + totalTime += value * 60; + found = true; + break; + case "h": + totalTime += value * 60 * 60; + found = true; + break; + case "d": + totalTime += value * 60 * 60 * 24; + found = true; + break; + case "w": + totalTime += value * 60 * 60 * 24 * 7; + found = true; + break; + case "M": + totalTime += value * 60 * 60 * 24 * 30; + found = true; + break; + case "y": + totalTime += value * 60 * 60 * 24 * 365; + found = true; + break; + } + } + + return !found ? -1 : totalTime * 1000; + } +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/config/AbstractConfig.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/config/AbstractConfig.java new file mode 100644 index 0000000..0a539dd --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/config/AbstractConfig.java @@ -0,0 +1,108 @@ +package net.crankedpvp.customblocks.utils.config; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class AbstractConfig { + + private final JavaPlugin plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + + public AbstractConfig(JavaPlugin plugin, String path) { + this.plugin = plugin; + this.path = path; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public boolean setupConfigFile() { + boolean copyDefaults = !configFile.exists(); + + this.saveDefaultConfig(); + config = YamlConfiguration.loadConfiguration(configFile); + + if (copyDefaults) this.copyDefaults(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + return result; + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path + "!"); + e.printStackTrace(); + } + return false; + } + + public void saveDefaultConfig() { + if (!configFile.exists()) { + InputStream defConfig = plugin.getResource(path); + if (defConfig != null) { + plugin.saveResource(path,false); + } else { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path + "!"); + e.printStackTrace(); + } + } + } + } + + + public boolean reloadConfig() { + boolean copyDefaults = !configFile.exists(); + + this.saveDefaultConfig(); + config = YamlConfiguration.loadConfiguration(configFile); + + if (copyDefaults) this.copyDefaults(); + + this.saveConfig(); + return this.loadConfigFromDisk(); + } + + public boolean loadConfigFromDisk() { + try { + config.load(configFile); + return true; + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path + "!"); + e.printStackTrace(); + } + return false; + } + + public void copyDefaults() { + InputStream defConfig = plugin.getResource(path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + public FileConfiguration getConfig() { + return config; + } + + public String getPath() { + return path; + } + +} diff --git a/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/config/ConfigManager.java b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/config/ConfigManager.java new file mode 100644 index 0000000..f1382ac --- /dev/null +++ b/CustomBlocks/src/main/java/net/crankedpvp/customblocks/utils/config/ConfigManager.java @@ -0,0 +1,51 @@ +package net.crankedpvp.customblocks.utils.config; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; + +public class ConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public ConfigManager(JavaPlugin plugin) { + + for (ConfigFile configFile : ConfigFile.values()) { + AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName()); + configs.put(configFile, abstractConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AbstractConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AbstractConfig::reloadConfig); + } + + public AbstractConfig getAbstractConfig(ConfigFile configFile) { + return configs.get(configFile); + } + + public FileConfiguration getConfig(ConfigFile configFile) { + return getAbstractConfig(configFile).getConfig(); + } + + @Getter + @RequiredArgsConstructor + public enum ConfigFile { + + SETTINGS("settings.yml"), + ; + + private final String fileName; + + } + +} diff --git a/CustomBlocks/src/main/resources/plugin.yml b/CustomBlocks/src/main/resources/plugin.yml new file mode 100644 index 0000000..dbd9987 --- /dev/null +++ b/CustomBlocks/src/main/resources/plugin.yml @@ -0,0 +1,10 @@ +name: CrankedCustomBlocks +main: net.crankedpvp.customblocks.CustomBlocks +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedSlotBot + - CrankedLootTables + - CrankedCrateKeys \ No newline at end of file diff --git a/CustomBlocks/src/main/resources/settings.yml b/CustomBlocks/src/main/resources/settings.yml new file mode 100644 index 0000000..d114ea6 --- /dev/null +++ b/CustomBlocks/src/main/resources/settings.yml @@ -0,0 +1,5 @@ +commonKeyChance: 15 +rareKeyChance: 5 +mythicKeyChance: 2.5 +expPer: 75 +autoGrinderActivationPrice: 2500000 \ No newline at end of file diff --git a/CustomExplosions/pom.xml b/CustomExplosions/pom.xml new file mode 100644 index 0000000..477b159 --- /dev/null +++ b/CustomExplosions/pom.xml @@ -0,0 +1,30 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + CustomExplosions + + + 8 + 8 + + + + + com.comphenix.protocol + ProtocolLib + + + net.crankedpvp + Utils + + + + \ No newline at end of file diff --git a/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/CustomExplosionsPlugin.java b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/CustomExplosionsPlugin.java new file mode 100644 index 0000000..a1a5d3b --- /dev/null +++ b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/CustomExplosionsPlugin.java @@ -0,0 +1,77 @@ +package net.crankedpvp.customexplosions; + +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.customexplosions.commands.AdminExplosiveCommand; +import net.crankedpvp.customexplosions.listeners.CreeperListener; +import net.crankedpvp.customexplosions.listeners.TntListener; +import net.crankedpvp.customexplosions.struct.CreeperTypes; +import net.crankedpvp.customexplosions.struct.TNTTypes; +import org.bukkit.command.CommandExecutor; +import org.bukkit.event.Listener; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Arrays; +import java.util.stream.Collectors; + +@Getter +public class CustomExplosionsPlugin extends JavaPlugin { + @Getter + private static CustomExplosionsPlugin instance; + + private ProtocolManager protocolManager; + private CommandManager commandManager; + + + public void onEnable() { + instance = this; + this.commandManager = new CommandManager(this, true); + registerCommandParameters(); + registerCommandCompletion(); + registerCommands(); + this.registerListeners(); + this.protocolManager = ProtocolLibrary.getProtocolManager(); + } + + public void onDisable() { + instance = null; + } + + + + private void registerListeners() { + //this.getServer().getPluginManager().registerEvents((Listener)new TntListener(), (Plugin)this); + this.getServer().getPluginManager().registerEvents((Listener)new CreeperListener(), (Plugin)this); + + } + + private void registerCommands() { + commandManager.register(new AdminExplosiveCommand()); + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(TNTTypes.class, argument -> { + TNTTypes tntTypes = TNTTypes.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(tntTypes, argument); + }); + this.commandManager.getParameterHandler().register(CreeperTypes.class, argument -> { + CreeperTypes creeperTypes = CreeperTypes.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(creeperTypes, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#creepertypes", input -> { + return Arrays.stream(CreeperTypes.values()).map(CreeperTypes::name).collect(Collectors.toList()); + }); + this.commandManager.getCompletionHandler().register("#tnttypes", input -> { + return Arrays.stream(TNTTypes.values()).map(TNTTypes::name).collect(Collectors.toList()); + }); + } + +} + diff --git a/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/commands/AdminExplosiveCommand.java b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/commands/AdminExplosiveCommand.java new file mode 100644 index 0000000..cd1f9d5 --- /dev/null +++ b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/commands/AdminExplosiveCommand.java @@ -0,0 +1,38 @@ +package net.crankedpvp.customexplosions.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.customexplosions.struct.CreeperTypes; +import net.crankedpvp.customexplosions.struct.TNTTypes; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Command("ace") +public class AdminExplosiveCommand extends CommandBase { + @Default + @Permission("cranked.admin") + public void onDefault(CommandSender sender) { + sender.sendMessage(CC.translate("&e&lCranked Custom Explosives")); + sender.sendMessage(CC.translate("&e/ace &f- &7Gives you custom tnt or creeper eggs")); + } + + @SubCommand("tnt") + @Permission("cranked.admin") + public void giveTnt(CommandSender sender, @Completion("#tnttypes") TNTTypes type) { + ItemStack item = type.getTNTItem(); + Player player = (Player)sender; + player.getInventory().addItem(item); + player.sendMessage(CC.translate("&a + " + type.getItemName())); + } + + @SubCommand("creeper") + @Permission("cranked.admin") + public void giveCreeper(CommandSender sender, @Completion("#creepertypes") CreeperTypes type) { + ItemStack item = type.getCCItem(); + Player player = (Player)sender; + player.getInventory().addItem(item); + player.sendMessage(CC.translate("&a + " + type.getItemName())); + } +} diff --git a/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/listeners/CreeperListener.java b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/listeners/CreeperListener.java new file mode 100644 index 0000000..f3c77fb --- /dev/null +++ b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/listeners/CreeperListener.java @@ -0,0 +1,160 @@ +package net.crankedpvp.customexplosions.listeners; + +import lombok.SneakyThrows; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import net.crankedpvp.customexplosions.struct.CreeperTypes; +import net.minecraft.server.v1_8_R3.EntityLiving; +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftCreeper; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import java.io.File; +import java.util.*; + +public class CreeperListener implements Listener { + private final List nonSolidBlocks; + public static final Map creepers = new HashMap<>(); + + public CreeperListener() { + this.nonSolidBlocks = new ArrayList<>(Arrays.asList(Material.AIR, Material.CHEST, Material.OBSIDIAN)); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerUseCreeperEgg(PlayerInteractEvent e) { + CreeperTypes ct; + if (e.isCancelled() && e.useItemInHand() != Event.Result.ALLOW) { + return; + } + if (e.hasItem() && (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) && (ct = this.getCCType(e.getItem())) != null) { + this.processCustomCreeperPlaced(e, ct); + } + } + + public void processCustomCreeperPlaced(PlayerInteractEvent e, CreeperTypes ct) { + if (e.hasItem() && (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK)) { + Location spawnLoc; + Block b; + e.setCancelled(true); + Player p = e.getPlayer(); + try { + Material m2; + try { + b = e.getClickedBlock().getY() < 254 ? p.getTargetBlock((HashSet) null, 4) : e.getClickedBlock(); + } catch (Exception err) { + b = e.getClickedBlock(); + } + if (e.getClickedBlock().getY() >= 254 && e.getBlockFace() != BlockFace.UP) { + return; + } + if (!WorldGuardUtils.canPvPInRegion(b.getLocation())) { + return; + } + + spawnLoc = b.getLocation().getY() >= 255.0 ? b.getLocation() : b.getLocation().add(0.0, 1.0, 0.0); + ItemStack egg = e.getItem(); + if (egg.getAmount() > 1) { + egg.setAmount(egg.getAmount() - 1); + p.setItemInHand(egg); + } else { + p.setItemInHand(null); + } + spawnLoc.add(0.5, 0.0, 0.5); + } catch (Exception err) { + err.printStackTrace(); + return; + } + Bukkit.getLogger().info("[CosmicCustomCreeper] (" + ct.name() + ") spawnLocation: " + spawnLoc); + Creeper c = (Creeper) b.getWorld().spawnEntity(spawnLoc, EntityType.CREEPER); + + c.setCustomName(ct.getMobName()); + c.setCustomNameVisible(true); + + creepers.put(c.getUniqueId(), ct); + } + } + + + + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onCustomCreeperExplode(EntityExplodeEvent e) { + if (e.getEntity() == null || !creepers.containsKey(e.getEntity().getUniqueId())) { + return; + } + Creeper c = (Creeper) e.getEntity(); + if (creepers.containsKey(c.getUniqueId())) { + CreeperTypes egg_type = creepers.get(c.getUniqueId()); + Bukkit.getLogger().info("[CosmicCustomCreepers] EntityExplodeEvent for CustomCreeperEgg: " + egg_type.name() + " entity: " + c); + + switch (egg_type) { + case HUGE: + Location loc = c.getLocation(); + this.spawnFastExplosion(loc.clone().add(0.0, 3.0, 0.0)); + this.spawnFastExplosion(loc.clone().add(0.0, -3.0, 0.0)); + if (new Random().nextBoolean()) { + this.spawnFastExplosion(loc.clone().add(3.0, 0.0, 0.0)); + this.spawnFastExplosion(loc.clone().add(0.0, 0.0, 3.0)); + } else { + this.spawnFastExplosion(loc.clone().add(-3.0, 0.0, 0.0)); + this.spawnFastExplosion(loc.clone().add(0.0, 0.0, -3.0)); + } + break; + case LUCKY: + //This is handled in the spawners plugin (SpawnerBreakListener) + break; + case RAID: + //This is handled in the spawners plugin (SpawnerBreakListener) + break; + default: + Bukkit.getLogger().info("[CosmicCustomCreeper] No Creeper type found!"); + + } + + + } + } + + private void spawnFastExplosion(Location l) { + if (this.nonSolidBlocks.contains(l.getBlock().getType()) || l.getBlock().isLiquid()) { + return; + } + CraftCreeper creeper = l.getWorld().spawn(l, CraftCreeper.class); + net.minecraft.server.v1_8_R3.Entity nms = ((CraftEntity) creeper).getHandle(); + NBTTagCompound nbt = new NBTTagCompound(); + nms.c(nbt); + nbt.setInt("Fuse", 0); + EntityLiving living = (EntityLiving) nms; + living.a(nbt); + } + + private CreeperTypes getCCType(ItemStack creeper_egg) { + if (!(creeper_egg != null && creeper_egg.hasItemMeta() && creeper_egg.getItemMeta().hasDisplayName() && creeper_egg.getItemMeta().hasLore())) { + return null; + } + CreeperTypes tnt_type = null; + String name = creeper_egg.getItemMeta().getDisplayName(); + for (CreeperTypes tt : CreeperTypes.values()) { + if (!name.equals(tt.getItemName())) continue; + tnt_type = tt; + break; + } + return tnt_type; + } +} + diff --git a/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/listeners/TntListener.java b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/listeners/TntListener.java new file mode 100644 index 0000000..8cd635b --- /dev/null +++ b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/listeners/TntListener.java @@ -0,0 +1,169 @@ +package net.crankedpvp.customexplosions.listeners; + +import net.crankedpvp.customexplosions.CustomExplosionsPlugin; +import net.crankedpvp.customexplosions.struct.TNTTypes; +import net.minecraft.server.v1_8_R3.EntityTNTPrimed; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftTNTPrimed; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDispenseEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.ExplosionPrimeEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +public class TntListener implements Listener { + public static Map tnt_tracker = new HashMap<>(); + private final List nonSolidBlocks; + public static final Map customTnt = new HashMap<>(); + + + public TntListener() { + this.nonSolidBlocks = new ArrayList(Arrays.asList(Material.AIR, Material.SAND, Material.WATER, Material.LAVA, Material.STATIONARY_LAVA, Material.STATIONARY_WATER)); + } + + @EventHandler(priority= EventPriority.MONITOR, ignoreCancelled=true) + public void onTNTPlace(BlockPlaceEvent e) { + if (e.getBlockPlaced().getType() == Material.TNT) { + TNTTypes tnt_type = this.getTNTType(e.getItemInHand()); + if (tnt_type == null) { + return; + } + tnt_tracker.put(e.getBlockPlaced().getLocation(), tnt_type); + } + } + + @EventHandler + public void onBlockDispense(BlockDispenseEvent e) { + if (e.getItem().getType() == Material.TNT) { + TNTTypes tnt_type = this.getTNTType(e.getItem()); + if (tnt_type == null) { + return; + } + tnt_tracker.put(e.getBlock().getLocation(), tnt_type); + } + } + + @EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true) + public void onTNTBreak(BlockBreakEvent e) { + if (e.getBlock().getType() == Material.TNT && tnt_tracker.containsKey(e.getBlock().getLocation())) { + e.setCancelled(true); + Location loc = e.getBlock().getLocation(); + e.getBlock().setType(Material.AIR); + e.getBlock().getWorld().dropItemNaturally(loc, tnt_tracker.get(loc).getTNTItem()); + tnt_tracker.remove(loc); + } + } + + @EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true) + public void onExplosivePrime(ExplosionPrimeEvent e) { + if (e.getEntity() != null && e.getEntity() instanceof TNTPrimed) { + EntityTNTPrimed tntPrimed = ((CraftTNTPrimed)e.getEntity()).getHandle(); + TNTTypes tntType = tnt_tracker.get(e.getEntity().getLocation()); + if (tntType != null) { + customTnt.put(e.getEntity().getUniqueId(), tntType); + return; + } + Location loc = tntPrimed.getSource().getBukkitEntity().getLocation(); + TNTTypes tnt_type = tnt_tracker.remove(loc); + if (tnt_type != null) { + customTnt.put(e.getEntity().getUniqueId(), tnt_type); + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onTNTExplode(EntityExplodeEvent e) { + if (e.getEntity() == null || e.getEntityType() != EntityType.PRIMED_TNT) + return; + TNTPrimed tnt = (TNTPrimed)e.getEntity(); + + if (customTnt.containsKey(tnt.getUniqueId())) { + TNTTypes tnt_type = customTnt.get(tnt.getUniqueId()); + + + switch (tnt_type) { + case LUCKY: + //Coded in AstroSpawners plugin + case HUGE: + Location loc = tnt.getLocation(); + spawnFastExplosion(loc.clone().add(0.0D, 3.0D, 0.0D), true); + spawnFastExplosion(loc.clone().add(0.0D, -3.0D, 0.0D), true); + if (ThreadLocalRandom.current().nextBoolean()) { + spawnFastExplosion(loc.clone().add(3.0D, 0.0D, 0.0D), true); + spawnFastExplosion(loc.clone().add(0.0D, 0.0D, 3.0D), true); + } else { + spawnFastExplosion(loc.clone().add(-3.0D, 0.0D, 0.0D), true); + spawnFastExplosion(loc.clone().add(0.0D, 0.0D, -3.0D), true); + } + break; + case LETHAL: + for (int i = 0; i < 4; i++) + spawnFastExplosion(tnt.getLocation()); + break; + case MIMIC: + final Location l = tnt.getLocation(); + Bukkit.getScheduler().runTaskLater(CustomExplosionsPlugin.getInstance(), new Runnable() { + public void run() { + TntListener.this.spawnFastExplosion(l); + } + },100L); + Bukkit.getScheduler().runTaskLater(CustomExplosionsPlugin.getInstance(), new Runnable() { + public void run() { + spawnFastExplosion(l); + } + },200L); + Bukkit.getScheduler().runTaskLater(CustomExplosionsPlugin.getInstance(), new Runnable() { + public void run() { + spawnFastExplosion(l); + } + },300L); + break; + default: + Bukkit.getLogger().info("[CosmicCustomCreeper] No Creeper type found!"); + + } + + } + } + + private TNTTypes getTNTType(ItemStack tnt_is) { + if (!(tnt_is != null && tnt_is.hasItemMeta() && tnt_is.getItemMeta().hasDisplayName() && tnt_is.getItemMeta().hasLore())) { + return null; + } + TNTTypes tnt_type = null; + String name = tnt_is.getItemMeta().getDisplayName(); + for (TNTTypes tt : TNTTypes.values()) { + if (!name.equals(tt.getItemName())) continue; + tnt_type = tt; + break; + } + return tnt_type; + } + + private void spawnFastExplosion(Location l) { + this.spawnFastExplosion(l, true); + } + + private void spawnFastExplosion(Location l, boolean onlyAir) { + Material type = l.getBlock().getType(); + if (onlyAir && type != Material.AIR || !this.nonSolidBlocks.contains(type)) { + return; + } + TNTPrimed tnt = (TNTPrimed)l.getWorld().spawnEntity(l, EntityType.PRIMED_TNT); + tnt.setFuseTicks(0); + } + + +} + diff --git a/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/struct/CreeperTypes.java b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/struct/CreeperTypes.java new file mode 100644 index 0000000..3da9489 --- /dev/null +++ b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/struct/CreeperTypes.java @@ -0,0 +1,33 @@ +package net.crankedpvp.customexplosions.struct; + +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public enum CreeperTypes { + HUGE(ChatColor.AQUA.toString() + ChatColor.BOLD + "Gigantic Creeper", ChatColor.GRAY.toString() + ChatColor.ITALIC + "Explodes in a much larger radius."), + RAID(ChatColor.RED.toString() + ChatColor.BOLD + "Raid Creeper", ChatColor.GRAY.toString() + ChatColor.ITALIC + "100% chance of spawner drops."), + LUCKY(ChatColor.YELLOW.toString() + ChatColor.BOLD + "Lucky Creeper", ChatColor.GRAY.toString() + ChatColor.ITALIC + "Increases chances of spawner drops."); + final String display; + final String[] lore; + + CreeperTypes(String name, String... lore) { + this.display = name; + this.lore = lore; + } + + public String getItemName() { + return this.display.replace(ChatColor.BOLD.toString(), ""); + } + + public String getMobName() { + return this.display; + } + + public ItemStack getCCItem() { + return new ItemBuilder(Material.MONSTER_EGG, 1, (short)50).setLore(lore).setName(display).colorize().build(); + } + +} + diff --git a/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/struct/TNTTypes.java b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/struct/TNTTypes.java new file mode 100644 index 0000000..4ca3342 --- /dev/null +++ b/CustomExplosions/src/main/java/net/crankedpvp/customexplosions/struct/TNTTypes.java @@ -0,0 +1,31 @@ +package net.crankedpvp.customexplosions.struct; + +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public enum TNTTypes { + HUGE(ChatColor.AQUA + "Gigantic TNT", new String[]{ChatColor.AQUA.toString() + ChatColor.ITALIC + "Explodes in a much larger radius.", "", ChatColor.GRAY + "Spawns 2 extra explosions at", ChatColor.GRAY + "y+3 and y-3 of TNT, and another", ChatColor.GRAY + "2 explosions at either x+3, z+3 or", ChatColor.GRAY + "x-3 and z-3."}), + LETHAL(ChatColor.DARK_RED + "Lethal TNT", new String[]{ChatColor.DARK_RED.toString() + ChatColor.ITALIC + "A more dense, dangerous explosion.", "", ChatColor.GRAY + "Creates 4x extra TNT explosions at", ChatColor.GRAY + "same location as the original."}), + LUCKY(ChatColor.YELLOW + "Lucky TNT", new String[]{ChatColor.YELLOW.toString() + ChatColor.ITALIC + "Increases chances of spawner drops.", "", ChatColor.GRAY + "200% the normal chance of a", ChatColor.GRAY + "spawner dropping from explosion."}), + MIMIC(ChatColor.GREEN + "Mimic TNT", new String[]{ChatColor.GREEN.toString() + ChatColor.ITALIC + "Repeats the same explosion many times.", "", ChatColor.GRAY + "Spawns a TNT explosion at", ChatColor.GRAY + "same location every 5s", ChatColor.GRAY + "for 15s total, or 3 explosions."}); + + final String display; + final String[] lore; + + TNTTypes(String name, String[] lore) { + this.display = name; + this.lore = lore; + } + + public String getItemName() { + return this.display; + } + + public ItemStack getTNTItem() { + return new ItemBuilder(Material.TNT, display, lore).colorize().build(); + } + +} + diff --git a/CustomExplosions/src/main/resources/plugin.yml b/CustomExplosions/src/main/resources/plugin.yml new file mode 100644 index 0000000..80952ee --- /dev/null +++ b/CustomExplosions/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedCustomExplosives +main: net.crankedpvp.customexplosions.CustomExplosionsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/DTC/pom.xml b/DTC/pom.xml new file mode 100644 index 0000000..518cdb6 --- /dev/null +++ b/DTC/pom.xml @@ -0,0 +1,41 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + DTC + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + LootTable + + + net.crankedpvp + Leaderboards + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/DTC/src/main/java/net/crankedpvp/dtc/DTCPlugin.java b/DTC/src/main/java/net/crankedpvp/dtc/DTCPlugin.java new file mode 100644 index 0000000..6f14e8e --- /dev/null +++ b/DTC/src/main/java/net/crankedpvp/dtc/DTCPlugin.java @@ -0,0 +1,79 @@ +package net.crankedpvp.dtc; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.crankedutils.utils.serializer.location.LocationSerializerDeserializer; +import net.crankedpvp.dtc.commands.DTCCommand; +import net.crankedpvp.dtc.inventory.DTCInventory; +import net.crankedpvp.dtc.listeners.DTCSummonerListener; +import net.crankedpvp.dtc.listeners.DestroyCoreListener; +import net.crankedpvp.dtc.listeners.PlaceLocationSetter; +import net.crankedpvp.dtc.struct.DTCManager; +import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.ArrayList; +import java.util.List; + +public class DTCPlugin extends JavaPlugin { + + @Getter + private DTCManager dtcManager; + + private CommandManager commandManager; + + @Getter + private DTCInventory dtcInventory; + + @Override + public void onEnable() { + + + this.saveDefaultConfig(); + + this.dtcManager = new DTCManager(this); + this.registerLocationsFromConfig(); + + this.commandManager = new CommandManager(this); + this.commandManager.register(new DTCCommand(this)); + + + this.registerListeners(this.getServer().getPluginManager()); + this.dtcInventory = new DTCInventory(); + + } + + @Override + public void onDisable() { + saveLocationsToConfig(); + this.dtcManager.removeAllCores(); + } + + private void registerListeners(PluginManager pluginManager) { + pluginManager.registerEvents(new PlaceLocationSetter(this), this); + pluginManager.registerEvents(new DTCSummonerListener(this), this); + pluginManager.registerEvents(new DestroyCoreListener(this), this); + } + + public void saveLocationsToConfig() { + final FileConfiguration yamlConfiguration = this.getConfig(); + final List locations = new ArrayList<>(); + for(Location location : this.dtcManager.getLocationList()) { + locations.add(LocationSerializerDeserializer.serialize(location)); + } + yamlConfiguration.set("locations", locations); + this.saveConfig(); + } + + private void registerLocationsFromConfig() { + final FileConfiguration yamlConfiguration = this.getConfig(); + if(yamlConfiguration.contains("locations")) { + for(String string : yamlConfiguration.getStringList("locations")) { + this.dtcManager.getLocationList().add(LocationSerializerDeserializer.deserialize(string)); + } + } + } + +} diff --git a/DTC/src/main/java/net/crankedpvp/dtc/commands/DTCCommand.java b/DTC/src/main/java/net/crankedpvp/dtc/commands/DTCCommand.java new file mode 100644 index 0000000..524019d --- /dev/null +++ b/DTC/src/main/java/net/crankedpvp/dtc/commands/DTCCommand.java @@ -0,0 +1,95 @@ +package net.crankedpvp.dtc.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.dtc.DTCPlugin; +import net.crankedpvp.dtc.struct.DTCManager; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +@Command("destroythecore") +@Alias("dtc") +public class DTCCommand extends CommandBase { + + private DTCPlugin plugin; + public DTCCommand(DTCPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getDtcInventory().getUI().open(player); + } + + @SubCommand("save") + @Permission("cranked.admin") + public void saveCommand(final CommandSender commandSender) { + final long current = System.currentTimeMillis(); + this.plugin.saveLocationsToConfig(); + commandSender.sendMessage(CC.translate(DTCManager.prefix + "&7Saved DTC location data in &n" + (System.currentTimeMillis() - current) + "ms")); + SoundUtils.tryPlaySuccessSound(commandSender); + } + + @SubCommand("edit") + @Alias("editor") + @Permission("cranked.admin") + public void editCommand(final CommandSender commandSender) { + if(!(commandSender instanceof Player)) { + commandSender.sendMessage(CC.translate("&cOnly players can execute this command")); + return; + } + + Player player = ((Player)commandSender); + if(InventoryUtils.hasAvailableSlot(player)) { + final ItemBuilder itemBuilder = new ItemBuilder(Material.CHEST, "&b&lDTC &8- &fLocation Setter", + "&7Place this chest down at the", + "&7locations that you want the", + "&7dtc events to spawn at"); + final ItemStack itemStack = CustomItemUtils.setCrankedCustomItem(itemBuilder.colorize().build(), "dtcLocationSetter"); + player.getInventory().addItem(itemStack); + player.sendMessage(CC.translate(DTCManager.prefix + "&7Received a destroy the core location setter")); + SoundUtils.tryPlaySuccessSound(player); + } + } + + @SubCommand("start") + @Alias({"forcestart", "begin"}) + @Permission("cranked.admin") + public void startCommand(final CommandSender commandSender) { + Location location = this.plugin.getDtcManager().startEvent(); + if(location == null) return; + commandSender.sendMessage(CC.translate(DTCManager.prefix + "&7Successfully started a DTC event at: " + LocationUtils.locationToFancy(location))); + SoundUtils.tryPlaySuccessSound(commandSender); + } + + @SubCommand("end") + @Alias("forceend") + @Permission("cranked.admin") + public void endCommand(final CommandSender commandSender) { + this.plugin.getDtcManager().endEvent(); + commandSender.sendMessage(CC.translate(DTCManager.prefix + "&7Successfully ended the current DTC event")); + SoundUtils.tryPlaySuccessSound(commandSender); + } + + + @SubCommand("summoner") + @Permission("cranked.admin") + public void summonerCommand(final CommandSender commandSender, @Optional @Completion("#players") Player player) { + if(player == null) player = (Player)commandSender; + ItemBuilder itemBuilder = new ItemBuilder(Material.TORCH, "&f&ki&r&e✦&f&ki&r &6&lCore Summoner &f&ki&e✦&f&ki&r", + "&7Right-Click this summoner to", + "&7forcefully begin a dtc event", + "", + "&7The event will not start if", + "&7another dtc event is ongoing"); + itemBuilder.setGlowing(); + PlayerUtils.giveOrDropProtectedItem(player, CustomItemUtils.setCrankedCustomItem(itemBuilder.colorize().build(), "dtcSummoner"), 15); + } + +} diff --git a/DTC/src/main/java/net/crankedpvp/dtc/inventory/DTCInventory.java b/DTC/src/main/java/net/crankedpvp/dtc/inventory/DTCInventory.java new file mode 100644 index 0000000..036667c --- /dev/null +++ b/DTC/src/main/java/net/crankedpvp/dtc/inventory/DTCInventory.java @@ -0,0 +1,36 @@ +package net.crankedpvp.dtc.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class DTCInventory { + + private final Gui dtcInventory; + + public Gui getUI() { + return this.dtcInventory; + } + + public DTCInventory() { + this.dtcInventory = new Gui(GuiType.HOPPER, "Destroy The Core"); + this.dtcInventory.setDefaultClickAction(event -> event.setCancelled(true)); + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, "&6Destroy The Core Info", + "&7The &eDestroy The Core &7event (DTC) is", + "&7a small scale event whereby players", + "&7attack a &fbeacon &7spawned randomly", + "&7within the &4warzone&7.", + "", + "&7Once the beacon has been &ffully", + "&7destroyed, it's &fcontents &7will", + "&7spill onto the ground for &fanyone", + "&7to loot, so be &aquick!").colorize().build(); + this.dtcInventory.setItem(1, new GuiItem(info)); + + ItemStack rewards = new ItemBuilder(Material.CHEST, "&d&lLoot Table", "&7Click to view all potential rewards", "&7from the destroy the core event").colorize().build(); + this.dtcInventory.setItem(3, new GuiItem(rewards)); + } +} diff --git a/DTC/src/main/java/net/crankedpvp/dtc/listeners/DTCSummonerListener.java b/DTC/src/main/java/net/crankedpvp/dtc/listeners/DTCSummonerListener.java new file mode 100644 index 0000000..d7725d8 --- /dev/null +++ b/DTC/src/main/java/net/crankedpvp/dtc/listeners/DTCSummonerListener.java @@ -0,0 +1,39 @@ +package net.crankedpvp.dtc.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CustomItemUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.dtc.DTCPlugin; +import net.crankedpvp.dtc.struct.DTCManager; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class DTCSummonerListener implements Listener { + + private final DTCPlugin plugin; + public DTCSummonerListener(DTCPlugin envoyPlugin) { + this.plugin = envoyPlugin; + } + + @EventHandler + public void useItem(PlayerInteractEvent event) { + if(event.getPlayer() == null) return; + if(event.getPlayer().getItemInHand() == null) return; + ItemStack itemStack = event.getPlayer().getItemInHand(); + if(!CustomItemUtils.isCrankedCustomItem(itemStack)) return; + if(!CustomItemUtils.getCrankedCustomItem(itemStack).equals("dtcSummoner")) return; + if(this.plugin.getDtcManager().isActive()) { + event.setCancelled(true); + event.getPlayer().sendMessage(CC.translate(DTCManager.prefix + "&cThere is already an active destroy the core event")); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + event.getPlayer().setItemInHand(ItemUtils.decreaseItemStackAmountByOne(itemStack)); + this.plugin.getDtcManager().startEvent(); + + } +} diff --git a/DTC/src/main/java/net/crankedpvp/dtc/listeners/DestroyCoreListener.java b/DTC/src/main/java/net/crankedpvp/dtc/listeners/DestroyCoreListener.java new file mode 100644 index 0000000..cb72c86 --- /dev/null +++ b/DTC/src/main/java/net/crankedpvp/dtc/listeners/DestroyCoreListener.java @@ -0,0 +1,108 @@ +package net.crankedpvp.dtc.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.LocationUtils; +import net.crankedpvp.dtc.DTCPlugin; +import net.crankedpvp.dtc.struct.DTCManager; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.*; +import org.bukkit.entity.Firework; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.meta.FireworkMeta; + +import java.util.concurrent.ThreadLocalRandom; + +public class DestroyCoreListener implements Listener { + + private final DTCPlugin plugin; + private final DTCManager manager; + public DestroyCoreListener(DTCPlugin plugin) { + this.plugin = plugin; + this.manager = plugin.getDtcManager(); + } + + @EventHandler + public void destroyCore(PlayerInteractEvent event) { + if(event.getPlayer() == null) return; + if(event.getClickedBlock() == null) return; + final Location location = event.getClickedBlock().getLocation(); + if(this.manager.getCurrentLocation() == null) return; + if(!locationEquals(location, this.manager.getCurrentLocation())) return; + event.setCancelled(true); + Player player = event.getPlayer(); + if(this.manager.getCooldownToHit().contains(player)) return; + this.manager.getCooldownToHit().add(player); + this.manager.setHealth(this.manager.getHealth() - 1); + player.playSound(player.getLocation(), Sound.GLASS, 4.0F, 2.0F); + + if(this.manager.getHealth() <= 0) { + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).incrementCoresBroken(); + this.sendFirework(); + this.manager.endEvent(); + int max = ThreadLocalRandom.current().nextInt(3, 14); + Bukkit.broadcastMessage(""); + Bukkit.broadcastMessage(CC.translate("&6&lCore Destroyed: &f" + LocationUtils.locationToFancySav(location))); + Bukkit.broadcastMessage(CC.translate(" &6• &eBroken By: &f" + player.getDisplayName())); + Bukkit.broadcastMessage(CC.translate(" &6• &eRewards: &f" + max + " Items")); + Bukkit.broadcastMessage(""); + int current = 0; + while (current != max) { + if(current >= max-2) { + location.getWorld().dropItem(getUppedLocation(location), LootTableAPI.getRandomLootItem(LootTableType.SEASON_KEY)); + } else if(current >= max-6) { + location.getWorld().dropItem(getUppedLocation(location), LootTableAPI.getRandomLootItem(LootTableType.ABYSS_KEY)); + } else { + location.getWorld().dropItem(getUppedLocation(location), LootTableAPI.getRandomLootItem(LootTableType.MYTHIC_KEY)); + } + current++; + } + this.manager.getCooldownToHit().remove(player); + return; + + } + + player.sendMessage(CC.translate("&6&lCore &8➥ &eYou are destroying the core &8- &cHealth&8: " + getHealth(this.manager.getHealth()))); + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> { + this.manager.getCooldownToHit().remove(player); + }, 20L); + } + + private void sendFirework() { + Location location = this.plugin.getDtcManager().getCurrentLocation(); + Firework firework = location.getWorld().spawn(location.clone().add(0.5D, 0.0D, 0.5D), Firework.class); + FireworkMeta fireworkMeta = firework.getFireworkMeta(); + fireworkMeta.addEffect(FireworkEffect.builder().withColor(Color.YELLOW).withFade(Color.ORANGE) + .with(FireworkEffect.Type.BURST).flicker(true).withTrail().build()); + firework.setFireworkMeta(fireworkMeta); + fireworkMeta.setPower(6); + Bukkit.getScheduler().runTaskLater(this.plugin, firework::detonate, 25L); + } + + + private Location getUppedLocation(Location location) { + Location newLocation = location.clone(); + newLocation.setY(location.getY() + 1.5); + return newLocation; + } + + private String getHealth(int health) { + return + health > 55 ? ("&a" + health + " ❤") : + health > 40 ? ("&e" + health + " ❤") : + health > 25 ? ("&6" + health + " ❤") : + health > 9 ? ("&c" + health + " ❤") : + ("&4" + health + " ❤"); + } + + private boolean locationEquals(Location location1, Location location2) { + if(location1.getWorld() != location2.getWorld()) return false; + if(location1.getX() != location2.getX()) return false; + if(location1.getY() != location2.getY()) return false; + return location1.getZ() == location2.getZ(); + } +} diff --git a/DTC/src/main/java/net/crankedpvp/dtc/listeners/PlaceLocationSetter.java b/DTC/src/main/java/net/crankedpvp/dtc/listeners/PlaceLocationSetter.java new file mode 100644 index 0000000..13477e6 --- /dev/null +++ b/DTC/src/main/java/net/crankedpvp/dtc/listeners/PlaceLocationSetter.java @@ -0,0 +1,39 @@ +package net.crankedpvp.dtc.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CustomItemUtils; +import net.crankedpvp.crankedutils.utils.LocationUtils; +import net.crankedpvp.dtc.DTCPlugin; +import net.crankedpvp.dtc.struct.DTCManager; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; + +public class PlaceLocationSetter implements Listener { + + private final DTCPlugin plugin; + public PlaceLocationSetter(DTCPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void placeBlockListener(BlockPlaceEvent event) { + if(event.getBlockPlaced() == null) return; + if(event.getItemInHand() == null) return; + + final Player player = event.getPlayer(); + final ItemStack itemStack = event.getItemInHand(); + if(!CustomItemUtils.isCrankedCustomItem(itemStack)) return; + if(!CustomItemUtils.getCrankedCustomItem(itemStack).equals("dtcLocationSetter")) return; + + event.setCancelled(true); + final Location location = event.getBlockPlaced().getLocation(); + player.sendMessage(CC.translate(DTCManager.prefix + "&aSuccessfully placed a core location at: " + LocationUtils.locationToFancy(location))); + this.plugin.getDtcManager().getLocationList().add(location); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } +} diff --git a/DTC/src/main/java/net/crankedpvp/dtc/struct/DTCManager.java b/DTC/src/main/java/net/crankedpvp/dtc/struct/DTCManager.java new file mode 100644 index 0000000..fd38f63 --- /dev/null +++ b/DTC/src/main/java/net/crankedpvp/dtc/struct/DTCManager.java @@ -0,0 +1,108 @@ +package net.crankedpvp.dtc.struct; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.LocationUtils; +import net.crankedpvp.dtc.DTCPlugin; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.*; +import org.bukkit.inventory.meta.FireworkMeta; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class DTCManager { + + private DTCPlugin plugin; + public DTCManager(DTCPlugin plugin) { + this.plugin = plugin; + this.locationList = new ArrayList<>(); + this.cooldownToHit = new ArrayList<>(); + } + + public static String prefix = "&6&lDTC &8➥ "; + + @Getter + private List locationList; + + @Getter @Setter + private Location currentLocation; + + @Getter @Setter + private boolean active = false; + + @Getter @Setter + private int health = 0; + + @Getter + private List cooldownToHit; + + public Location startEvent() { + if(this.isActive()) return null; + + final List locationList = new ArrayList<>(this.plugin.getDtcManager().getLocationList()); + final Location location = locationList.get(ThreadLocalRandom.current().nextInt(locationList.size())); + + if(location.getBlock().getType() == Material.AIR) { + + this.plugin.getDtcManager().setCurrentLocation(location); + + this.plugin.getDtcManager().setActive(true); + this.plugin.getDtcManager().setCurrentLocation(location); + this.plugin.getDtcManager().setHealth(30); + location.getBlock().setType(Material.BEACON); + ArmorStand armorStand = (ArmorStand)location.getWorld().spawnEntity(location.clone().add(0.5D, 0.1D, 0.5D), EntityType.ARMOR_STAND); + armorStand.setCustomName(CC.translate("&6&l✧&e&l✧ &6&lCore &e&l✧&6&l✧")); + armorStand.setCustomNameVisible(true); + armorStand.setGravity(false); + armorStand.setVisible(false); + armorStand.setSmall(true); + Firework firework = location.getWorld().spawn(location.clone().add(0.5D, 0.0D, 0.5D), Firework.class); + FireworkMeta fireworkMeta = firework.getFireworkMeta(); + fireworkMeta.setPower(0); + fireworkMeta.addEffect(FireworkEffect.builder().withColor(Color.ORANGE).withFade(Color.YELLOW) + .with(FireworkEffect.Type.STAR).trail(true).flicker(true).build()); + firework.setFireworkMeta(fireworkMeta); + this.plugin.getServer().getOnlinePlayers().forEach(player -> player.sendMessage(CC.translate(prefix + "&eA destroy the core event has started at: &7" + LocationUtils.locationToFancy(location)))); + return location; + + } else { + System.out.println("[-] DTC Event force ended due to dtc block obstruction"); + } + + return null; + } + + public void endEvent() { + if(this.getCurrentLocation() == null) return; + Location location = this.getCurrentLocation(); + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.3D, 0.6D, 0.3D)) { + if (!(entity instanceof ArmorStand)) + continue; + entity.remove(); + } + if(location.getBlock().getType() == Material.BEACON) + location.getBlock().setType(Material.AIR); + this.setActive(false); + this.setHealth(0); + this.setCurrentLocation(null); + this.getCooldownToHit().clear(); + } + + public void removeAllCores() { + for(Location location : this.getLocationList()) { + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.3D, 0.6D, 0.3D)) { + if (!(entity instanceof ArmorStand)) + continue; + entity.remove(); + } + if(location.getBlock().getType() == Material.BEACON) + location.getBlock().setType(Material.AIR); + } + } +} diff --git a/DTC/src/main/resources/config.yml b/DTC/src/main/resources/config.yml new file mode 100644 index 0000000..7bed763 --- /dev/null +++ b/DTC/src/main/resources/config.yml @@ -0,0 +1 @@ +locations: [] \ No newline at end of file diff --git a/DTC/src/main/resources/plugin.yml b/DTC/src/main/resources/plugin.yml new file mode 100644 index 0000000..27c51f2 --- /dev/null +++ b/DTC/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedDTC +main: net.crankedpvp.dtc.DTCPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + diff --git a/DeadMansChest/pom.xml b/DeadMansChest/pom.xml new file mode 100644 index 0000000..26fd722 --- /dev/null +++ b/DeadMansChest/pom.xml @@ -0,0 +1,45 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + DeadMansChest + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + com.massivecraft + Factions + + + net.crankedpvp + PvPTop + + + net.crankedpvp + Lootboxes + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/DeadmansChestPlugin.java b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/DeadmansChestPlugin.java new file mode 100644 index 0000000..7796c1d --- /dev/null +++ b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/DeadmansChestPlugin.java @@ -0,0 +1,116 @@ +package net.crankedpvp.deadmanschest; + +import com.massivecraft.factions.Factions; +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.deadmanschest.commands.DeadmansChestCommand; +import net.crankedpvp.deadmanschest.inventory.DeadmansChestInventory; +import net.crankedpvp.deadmanschest.listeners.DestroyDeadmansChestListener; +import net.crankedpvp.deadmanschest.listeners.PlaceDeadmansChestItemListener; +import net.crankedpvp.deadmanschest.manager.DeadmansChestManager; +import net.crankedpvp.deadmanschest.tasks.UpdateNextDeadmansChestTimerTask; +import net.crankedpvp.crankedutils.utils.serializer.location.LocationSerializerDeserializer; +import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.TimeZone; + +public class DeadmansChestPlugin extends JavaPlugin { + + public static String WORLD = ""; + + public final static String PREFIX = "&d&lDead Mans Chest &8➥ &7"; + + @Getter + private static DeadmansChestPlugin instance; + + @Getter + private DeadmansChestManager deadmansChestManager; + @Getter + private DeadmansChestInventory deadmansChestInventory; + @Getter + private CommandManager commandManager; + + + @Override + public void onEnable() { + instance = this; + + this.saveDefaultConfig(); + + this.commandManager = new CommandManager(this); + this.commandManager.register(new DeadmansChestCommand(this)); + + this.deadmansChestManager = new DeadmansChestManager(this); + this.deadmansChestInventory = new DeadmansChestInventory(this); + + this.registerListeners(); + new UpdateNextDeadmansChestTimerTask(this).runTaskTimer(this, 40L, 20L); + this.registerLocationsFromConfig(); + + WORLD = this.getConfig().getString("DEADMANS_CHEST_WORLD"); + + this.deadmansChestManager.setLastFactionWon((this.getConfig().getString("LAST_CAPTURED_ID").equals("0") || this.getConfig().getString("LAST_CAPTURED_ID") == null) ? null : Factions.getInstance().getFactionById(this.getConfig().getString("LAST_CAPTURED_ID"))); + } + + @Override + public void onDisable() { + + this.deadmansChestManager.stop(); + this.saveLocationsToConfig(); + this.getConfig().set("LAST_CAPTURED_ID", this.getDeadmansChestManager().getLastFactionWon() == null ? "0" : this.getDeadmansChestManager().getLastFactionWon().getId()); + this.saveConfig(); + instance = null; + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new DestroyDeadmansChestListener(this), this); + pluginManager.registerEvents(new PlaceDeadmansChestItemListener(this), this); + //pluginManager.registerEvents(new PlayerListener(this), this); + } + + public void saveLocationsToConfig() { + final FileConfiguration yamlConfiguration = this.getConfig(); + final List locations = new ArrayList<>(); + for(Location location : this.deadmansChestManager.getLocationList()) { + locations.add(LocationSerializerDeserializer.serialize(location)); + } + yamlConfiguration.set("Locations", locations); + this.saveConfig(); + } + + private void registerLocationsFromConfig() { + final FileConfiguration yamlConfiguration = this.getConfig(); + if(yamlConfiguration.contains("Locations")) { + for(String string : yamlConfiguration.getStringList("Locations")) { + this.deadmansChestManager.getLocationList().add(LocationSerializerDeserializer.deserialize(string)); + } + } + } + + public long getTimeUntilNextChest() { + Calendar nextDeadMansChest = Calendar.getInstance(TimeZone.getTimeZone("America/New_York")); + nextDeadMansChest.set(Calendar.MINUTE, 0); + nextDeadMansChest.set(Calendar.SECOND, 0); + int currentHour = nextDeadMansChest.get(Calendar.HOUR_OF_DAY); + if (currentHour < 5) { + nextDeadMansChest.set(Calendar.HOUR_OF_DAY, 5); + return (nextDeadMansChest.getTimeInMillis() - System.currentTimeMillis()) - 1000; + } else if (currentHour < 17) { + nextDeadMansChest.set(Calendar.HOUR_OF_DAY, 17); + return (nextDeadMansChest.getTimeInMillis() - System.currentTimeMillis()) - 1000; + } else { + nextDeadMansChest.add(Calendar.DAY_OF_MONTH, 1); + nextDeadMansChest.set(Calendar.HOUR_OF_DAY, 5); + return (nextDeadMansChest.getTimeInMillis() - System.currentTimeMillis()) - 1000; + } + } + + +} diff --git a/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/commands/DeadmansChestCommand.java b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/commands/DeadmansChestCommand.java new file mode 100644 index 0000000..099a918 --- /dev/null +++ b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/commands/DeadmansChestCommand.java @@ -0,0 +1,72 @@ +package net.crankedpvp.deadmanschest.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.deadmanschest.DeadmansChestPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CustomItemUtils; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Command("deadmanschest") +@Alias({"dmc", "deadman", "deadmans", "deadchest"}) +public class DeadmansChestCommand extends CommandBase { + + private final DeadmansChestPlugin plugin; + public DeadmansChestCommand(DeadmansChestPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getDeadmansChestInventory().getUI().open(player); + } + + @SubCommand("start") + @Permission("cranked.admin") + public void startCommand(final CommandSender commandSender) { + this.plugin.getDeadmansChestManager().start(); + commandSender.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "You have forcefully started a dead mans chest event")); + } + + @SubCommand("edit") + @Alias("editor") + @Permission("cranked.admin") + public void editCommand(final Player player) { + if(InventoryUtils.hasAvailableSlot(player)) { + final ItemBuilder itemBuilder = new ItemBuilder(Material.CHEST, "&d&lDead Mans Chest Location Setter", + "&7Place this chest down at the", + "&7locations that you want the", + "&7DMC events to spawn at"); + final ItemStack itemStack = CustomItemUtils.setCrankedCustomItem(itemBuilder.colorize().build(), "deadmansChestLocationSetter"); + player.getInventory().addItem(itemStack); + player.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "&7Received a dead mans chest location setter")); + SoundUtils.tryPlaySuccessSound(player); + } + } + + @SubCommand("stop") + @Permission("cranked.admin") + public void stopCommand(final CommandSender commandSender) { + this.plugin.getDeadmansChestManager().stop(); + commandSender.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "You have forcefully stopped the ongoing dead mans chest event")); + } + + @SubCommand("debug") + @Permission("cranked.admin") + public void debugCommand(final CommandSender commandSender) { + if(this.plugin.getDeadmansChestManager().isActive()) { + this.plugin.getDeadmansChestManager().stop(); + commandSender.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "You have forcefully stopped the ongoing dead mans chest event")); + } + this.plugin.getDeadmansChestManager().debugAndRemoveDeadMansChests(); + commandSender.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "You have debugged all dead mans chests")); + } + +} diff --git a/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/inventory/DeadmansChestInventory.java b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/inventory/DeadmansChestInventory.java new file mode 100644 index 0000000..8215d76 --- /dev/null +++ b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/inventory/DeadmansChestInventory.java @@ -0,0 +1,105 @@ +package net.crankedpvp.deadmanschest.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.deadmanschest.DeadmansChestPlugin; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class DeadmansChestInventory { + + @Getter + private ItemStack deadMansChestItemStack; + + @Getter + private final DeadmansChestPlugin plugin; + + private final Gui deadMansChestInventory; + + public Gui getUI() { + return this.deadMansChestInventory; + } + + public DeadmansChestInventory(DeadmansChestPlugin plugin) { + this.plugin = plugin; + this.deadMansChestInventory = new Gui(3, "Dead Mans Chest"); + this.deadMansChestInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.buildDeadmansChestItem(); + + ItemStack howToPlay = new ItemBuilder(Material.SIGN, "&b&lHow to Play?", + "&fThis is a competitive event which will", + "&fstart twice per day, where factions compete", + "&fto control, and destroy the chest", + "", + "&fThe objective is to destroy the chest,", + "&fhowever you can &c&lONLY &fbreak the", + "&fchest if your faction is the only faction", + "&finside of the capture zone which surrounds", + "&fthe dead mans chest.", + "", + "&fYour faction must work together to clear", + "&fenemy players from the capture zone before", + "&fyou can attempt to break the chest." + ).colorize().build(); + + + ItemStack viewAllEvents = new ItemBuilder(Material.ARROW, "&d&lAll Events", + "&fClick here to view all of the", + "&fevents currently active on Cranked" + ).colorize().build(); + this.deadMansChestInventory.setItem(2, 5, new GuiItem(this.getDeadMansChestItemStack())); + this.deadMansChestInventory.setItem(2, 3, new GuiItem(howToPlay)); + this.deadMansChestInventory.setItem(2, 7, new GuiItem(viewAllEvents, event -> { + event.getWhoClicked().closeInventory(); + if(event.getWhoClicked() instanceof Player) { + ((Player)event.getWhoClicked()).performCommand("events"); + } + })); + } + + private String getNextChestTimeString() { + return this.plugin.getDeadmansChestManager().isActive() ? "Now" : TimeUtils.formatMillisecondsInFull(this.plugin.getTimeUntilNextChest()); + } + + private String getActiveString() { + return this.plugin.getDeadmansChestManager().isActive() ? "&a&lACTIVE" : "&c&lINACTIVE"; + } + + + public void updateInformationItem() { + this.buildDeadmansChestItem(); + this.deadMansChestInventory.updateItem(2, 5, new GuiItem(this.getDeadMansChestItemStack())); + } + + public void buildDeadmansChestItem() { + this.deadMansChestItemStack = new ItemBuilder(Material.ENDER_CHEST, "&d&lDead Mans Chest &7(Information)", + "&fA competitive event on Cranked. Conquer", + "&fall enemies and destroy the chest", + "", + "&dInformation:", + " &f• Located at &d/warp nether", + " &f• Chest has &d150 &fHealth Points", + " &f• Chest health is &dunique &fper faction", + "", + "&dRewards &7(Upon capture)", + " &f• 3x Dead Mans Chest Lootbags", + " &f• Gain &d+" + FactionData.Points.DEADMANS_CHEST.getPoints() + " &fFaction Points", + "", + "&dDead Mans Chest:", + " &f• Event Status: " + this.getActiveString(), + " &f• Next Event: &a" + this.getNextChestTimeString(), + " &f• Captured Last: &d" + this.getLastFactionWon() + ).colorize().build(); + } + + private String getLastFactionWon() { + return this.plugin.getDeadmansChestManager().getLastFactionWon() == null ? "None" : this.plugin.getDeadmansChestManager().getLastFactionWon().getTag(); + } + +} diff --git a/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/DestroyDeadmansChestListener.java b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/DestroyDeadmansChestListener.java new file mode 100644 index 0000000..9cabeca --- /dev/null +++ b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/DestroyDeadmansChestListener.java @@ -0,0 +1,135 @@ +package net.crankedpvp.deadmanschest.listeners; + +import com.massivecraft.factions.Faction; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.deadmanschest.DeadmansChestPlugin; +import net.crankedpvp.deadmanschest.manager.DeadmansChestManager; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.pvptop.PvPTopAPI; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Firework; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.meta.FireworkMeta; + +public class DestroyDeadmansChestListener implements Listener { + + private final DeadmansChestPlugin plugin; + private final DeadmansChestManager manager; + public DestroyDeadmansChestListener(DeadmansChestPlugin plugin) { + this.plugin = plugin; + this.manager = plugin.getDeadmansChestManager(); + } + + @EventHandler + public void attemptToAttackChest(PlayerInteractEvent event) { + if(event.getPlayer() == null) return; + if(event.getClickedBlock() == null) return; + final Location location = event.getClickedBlock().getLocation(); + if(this.manager.getCurrentLocation() == null) return; + if(!locationEquals(location, this.manager.getCurrentLocation())) return; + event.setCancelled(true); + Player player = event.getPlayer(); + if(this.manager.getCooldownToHit().contains(player)) return; + + if(!isPlayerInRequiredRegion(player)) return; + Faction faction = FactionUtils.getFaction(player); + if(!faction.isNormal()) { + player.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "You must be in a faction to attack the dead mans chest")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 1.0f, 1.0f); + return; + } + player.playSound(player.getLocation(), Sound.ZOMBIE_WOODBREAK, 4.0F, 2.0F); + + for(Entity nearbyEntity : player.getNearbyEntities(20, 20, 20)) { + if(!(nearbyEntity instanceof Player)) continue; + Player nearbyPlayer = (Player) nearbyEntity; + if(!isPlayerInRequiredRegion(nearbyPlayer)) continue; + + Faction nearbyPlayersFaction = FactionUtils.getFaction(nearbyPlayer); + if(nearbyPlayersFaction != faction) { + this.manager.getCooldownToHit().add(player); + player.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "You cannot attack the chest while another faction is in the capture zone")); + player.playSound(player.getLocation(), Sound.FIZZ, 2.0f, 1.0f); + this.resetCooldownForPlayer(player); + return; + } + } + + if(this.incrementHitsFor(faction)) { + PvPTopAPI.getFactionData(faction).addPoint(FactionData.Points.DEADMANS_CHEST); + this.giveRewards(player); + this.sendFirework(); + this.sendMessage(faction, player); + this.manager.stop(); + this.manager.getCooldownToHit().clear(); + this.manager.setLastFactionWon(faction); + return; + } + + int hitsForFaction = this.manager.getHitsPerFaction().get(faction); + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "&fYour faction member &d" + player.getName() + " &fis attacking the chest &d(&7" + hitsForFaction + "/" + DeadmansChestManager.HEALTH + "&d)")); + } + + this.manager.getCooldownToHit().add(player); + this.resetCooldownForPlayer(player); + } + + private void giveRewards(Player player) { + PlayerUtils.giveOrDropProtectedItem(player, CrankedLootboxes.getInstance().getLootboxRegister().getLootbox("DeadMansChestLootbox").createLootbox(3), 30); + } + + private void resetCooldownForPlayer(Player player) { + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> this.manager.getCooldownToHit().remove(player), 20L); + } + + private boolean isPlayerInRequiredRegion(Player player) { + return WorldGuardUtils.getRegionName(player.getLocation()).equals(this.plugin.getConfig().get("CAPTURE_ZONE")); + } + + private void sendMessage(Faction faction, Player player) { + for(Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.sendMessage(""); + onlinePlayer.sendMessage(CC.translate("&d&lDead Mans Chest Captured")); + onlinePlayer.sendMessage(CC.translate(" &5• &dCapturing Faction: &f" + faction.getTag())); + onlinePlayer.sendMessage(CC.translate(" &5• &dCapturing Player: &f" + player.getName())); + onlinePlayer.sendMessage(CC.translate(" &5• &dRewards: &f3x Dead Mans Chest Lootbags")); + onlinePlayer.sendMessage(CC.translate(" &5• &dFaction Points: &f+" + FactionData.Points.DEADMANS_CHEST.getPoints() + " Gained")); + onlinePlayer.sendMessage(CC.translate(" &5• &dRuntime: &f" + TimeUtils.formatMilliseconds(System.currentTimeMillis() - this.manager.getStartTime()))); + onlinePlayer.sendMessage(""); + } + } + + private boolean incrementHitsFor(Faction faction) { + if(this.manager.getHitsPerFaction().containsKey(faction)) { + int amount = this.manager.getHitsPerFaction().get(faction) + 1; + this.manager.getHitsPerFaction().put(faction, amount); + return amount >= DeadmansChestManager.HEALTH; + } + this.manager.getHitsPerFaction().put(faction, 1); + return false; + } + + private void sendFirework() { + Location location = this.plugin.getDeadmansChestManager().getCurrentLocation(); + Firework firework = location.getWorld().spawn(location.clone().add(0.5D, 0.0D, 0.5D), Firework.class); + FireworkMeta fireworkMeta = firework.getFireworkMeta(); + fireworkMeta.addEffect(FireworkEffect.builder().withColor(Color.YELLOW).withFade(Color.ORANGE) + .with(FireworkEffect.Type.BURST).flicker(true).withTrail().build()); + firework.setFireworkMeta(fireworkMeta); + fireworkMeta.setPower(6); + Bukkit.getScheduler().runTaskLater(this.plugin, firework::detonate, 25L); + } + + private boolean locationEquals(Location location1, Location location2) { + if(location1.getWorld() != location2.getWorld()) return false; + if(location1.getX() != location2.getX()) return false; + if(location1.getY() != location2.getY()) return false; + return location1.getZ() == location2.getZ(); + } +} diff --git a/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/PlaceDeadmansChestItemListener.java b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/PlaceDeadmansChestItemListener.java new file mode 100644 index 0000000..458effc --- /dev/null +++ b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/PlaceDeadmansChestItemListener.java @@ -0,0 +1,38 @@ +package net.crankedpvp.deadmanschest.listeners; + +import net.crankedpvp.deadmanschest.DeadmansChestPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CustomItemUtils; +import net.crankedpvp.crankedutils.utils.LocationUtils; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; + +public class PlaceDeadmansChestItemListener implements Listener { + + private final DeadmansChestPlugin plugin; + public PlaceDeadmansChestItemListener(DeadmansChestPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void placeBlockListener(BlockPlaceEvent event) { + if(event.getBlockPlaced() == null) return; + if(event.getItemInHand() == null) return; + + final Player player = event.getPlayer(); + final ItemStack itemStack = event.getItemInHand(); + if(!CustomItemUtils.isCrankedCustomItem(itemStack)) return; + if(!CustomItemUtils.getCrankedCustomItem(itemStack).equals("deadmansChestLocationSetter")) return; + + event.setCancelled(true); + final Location location = event.getBlockPlaced().getLocation(); + player.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "&aSuccessfully placed a dead mans chest location at: " + LocationUtils.locationToFancy(location))); + this.plugin.getDeadmansChestManager().getLocationList().add(location); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } +} \ No newline at end of file diff --git a/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/PlayerListener.java b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/PlayerListener.java new file mode 100644 index 0000000..9ee6073 --- /dev/null +++ b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/listeners/PlayerListener.java @@ -0,0 +1,33 @@ +package net.crankedpvp.deadmanschest.listeners; + +import net.crankedpvp.deadmanschest.DeadmansChestPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.ProjectileLaunchEvent; + +public class PlayerListener implements Listener { + + private final DeadmansChestPlugin plugin; + public PlayerListener(DeadmansChestPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onProjectileShoot(ProjectileLaunchEvent event) { + if(event.getEntity() == null) return; + if(event.getEntity().getShooter() == null || !(event.getEntity().getShooter() instanceof Player)) return; + + if(!event.getEntity().getType().equals(EntityType.ENDER_PEARL)) return; + Player shooter = (Player) event.getEntity().getShooter(); + if(shooter.getWorld().getName().equals(DeadmansChestPlugin.WORLD)) { + event.setCancelled(true); + shooter.playSound(shooter.getLocation(), Sound.ENDERMAN_TELEPORT, 1.0f, 1.0f); + shooter.sendMessage(CC.translate(DeadmansChestPlugin.PREFIX + "You cannot use ender pearls at dead mans chest")); + } + } +} diff --git a/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/manager/DeadmansChestManager.java b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/manager/DeadmansChestManager.java new file mode 100644 index 0000000..e403cde --- /dev/null +++ b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/manager/DeadmansChestManager.java @@ -0,0 +1,139 @@ +package net.crankedpvp.deadmanschest.manager; + +import com.massivecraft.factions.Faction; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.deadmanschest.DeadmansChestPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.meta.FireworkMeta; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +public class DeadmansChestManager { + + private final DeadmansChestPlugin plugin; + public DeadmansChestManager(DeadmansChestPlugin plugin) { + this.plugin = plugin; + this.locationList = new ArrayList<>(); + this.hitsPerFaction = new HashMap<>(); + this.cooldownToHit = new ArrayList<>(); + } + + public final static int HEALTH = 150; + + @Getter + private final List cooldownToHit; + + @Getter + private final List locationList; + + @Getter + private final Map hitsPerFaction; + + @Getter @Setter + private Faction lastFactionWon; + + @Getter @Setter + private Location currentLocation; + + @Getter + private boolean active; + + @Getter + private long startTime = 0L; + + public void start() { + if(this.isActive()) return; + this.startTime = System.currentTimeMillis(); + this.spawnDeadmansChest(); + this.hitsPerFaction.clear(); + this.cooldownToHit.clear(); + this.active = true; + + for(Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.sendMessage(""); + onlinePlayer.sendMessage(CC.translate("&d&lDead Mans Chest")); + onlinePlayer.sendMessage(CC.translate(" &f• Status: &a&lACTIVE")); + onlinePlayer.sendMessage(CC.translate(" &f• Located: &d/warp nether &7(West)")); + onlinePlayer.sendMessage(CC.translate(" &f• Information: &d/deadmanschest")); + onlinePlayer.sendMessage(""); + } + } + + private void spawnDeadmansChest() { + final List locationList = new ArrayList<>(this.locationList); + final Location location = locationList.get(ThreadLocalRandom.current().nextInt(locationList.size())); + + if(location.getBlock().getType() == Material.AIR) { + + this.plugin.getDeadmansChestManager().setCurrentLocation(location); + + this.active = true; + location.getBlock().setType(Material.ENDER_CHEST); + + this.spawnFirework(location); + this.addHologram(location); + } else { + System.out.println("[-] Theres a block in the way for the dead mans chest, buddy."); + } + } + + private void addHologram(Location location) { + ArmorStand armorStand = (ArmorStand)location.getWorld().spawnEntity(location.clone().add(0.5D, 0.9D, 0.5D), EntityType.ARMOR_STAND); + armorStand.setCustomName(CC.translate("&d&lDead Mans Chest")); + armorStand.setCustomNameVisible(true); + armorStand.setGravity(false); + armorStand.setVisible(false); + armorStand.setSmall(true); + } + + private void spawnFirework(Location location) { + Firework firework = location.getWorld().spawn(location.clone().add(0.5D, 0.0D, 0.5D), Firework.class); + FireworkMeta fireworkMeta = firework.getFireworkMeta(); + fireworkMeta.setPower(0); + fireworkMeta.addEffect(FireworkEffect.builder().withColor(Color.AQUA).withFade(Color.PURPLE) + .with(FireworkEffect.Type.STAR).trail(true).flicker(true).build()); + firework.setFireworkMeta(fireworkMeta); + } + + public void stop() { + if(!this.isActive()) return; + + this.hitsPerFaction.clear(); + this.active = false; + this.cooldownToHit.clear(); + + Location location = this.getCurrentLocation(); + Location hologramloc = location.clone(); + hologramloc.setY(location.getY() + 0.9); + for (Entity entity : location.getWorld().getNearbyEntities(hologramloc, 0.3D, 0.6D, 0.3D)) { + if (!(entity instanceof ArmorStand)) + continue; + entity.remove(); + } + if(location.getBlock().getType() == Material.ENDER_CHEST) + location.getBlock().setType(Material.AIR); + + this.setCurrentLocation(null); + } + + + public void debugAndRemoveDeadMansChests() { + for(Location location : this.getLocationList()) { + Location newLoc = location.clone(); + newLoc.setY(newLoc.getY() + 0.9); + for (Entity entity : location.getWorld().getNearbyEntities(newLoc, 0.3D, 0.6D, 0.3D)) { + if (!(entity instanceof ArmorStand)) + continue; + entity.remove(); + } + if(location.getBlock().getType() == Material.ENDER_CHEST) { + location.getBlock().setType(Material.AIR); + } + + } + } +} diff --git a/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/tasks/UpdateNextDeadmansChestTimerTask.java b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/tasks/UpdateNextDeadmansChestTimerTask.java new file mode 100644 index 0000000..6bb420f --- /dev/null +++ b/DeadMansChest/src/main/java/net/crankedpvp/deadmanschest/tasks/UpdateNextDeadmansChestTimerTask.java @@ -0,0 +1,27 @@ +package net.crankedpvp.deadmanschest.tasks; + +import net.crankedpvp.deadmanschest.DeadmansChestPlugin; +import net.crankedpvp.deadmanschest.inventory.DeadmansChestInventory; +import org.bukkit.scheduler.BukkitRunnable; + +public class UpdateNextDeadmansChestTimerTask extends BukkitRunnable { + + private final DeadmansChestInventory deadmansChestInventory; + private final DeadmansChestPlugin plugin; + + public UpdateNextDeadmansChestTimerTask(DeadmansChestPlugin plugin) { + this.plugin = plugin; + this.deadmansChestInventory = plugin.getDeadmansChestInventory(); + } + + @Override + public void run() { + if(this.plugin.getTimeUntilNextChest() <= 1000L) + if(this.plugin.getTimeUntilNextChest() <= 0L) { + this.plugin.getDeadmansChestManager().start(); + } + deadmansChestInventory.updateInformationItem(); + } + + +} diff --git a/DeadMansChest/src/main/resources/config.yml b/DeadMansChest/src/main/resources/config.yml new file mode 100644 index 0000000..107dfd3 --- /dev/null +++ b/DeadMansChest/src/main/resources/config.yml @@ -0,0 +1,5 @@ +DEADMANS_CHEST_WORLD: world +CAPTURE_ZONE: deadmanschest_capture_zone +LAST_CAPTURED_ID: 0 +Locations: [] + diff --git a/DeadMansChest/src/main/resources/plugin.yml b/DeadMansChest/src/main/resources/plugin.yml new file mode 100644 index 0000000..a9d6666 --- /dev/null +++ b/DeadMansChest/src/main/resources/plugin.yml @@ -0,0 +1,10 @@ +name: CrankedDeadMansChest +main: net.crankedpvp.deadmanschest.DeadmansChestPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - WorldGuard + - CrankedPvPTop + diff --git a/DiscordSync/pom.xml b/DiscordSync/pom.xml new file mode 100644 index 0000000..e1b6207 --- /dev/null +++ b/DiscordSync/pom.xml @@ -0,0 +1,85 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + DiscordSync + + + 8 + 8 + + + + + jcenter + jcenter-bintray + https://jcenter.bintray.com + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.1 + + false + false + + + com.google + shaded.com.google + + + + + + package + + shade + + + true + + + + + + + + + net.dv8tion + JDA + 4.2.0_204 + compile + + + club.minnced + opus-java + + + + + Utils + net.crankedpvp + + + + + diff --git a/DiscordSync/src/main/java/net/crankedpvp/discordsync/DiscordSyncPlugin.java b/DiscordSync/src/main/java/net/crankedpvp/discordsync/DiscordSyncPlugin.java new file mode 100644 index 0000000..e4e1961 --- /dev/null +++ b/DiscordSync/src/main/java/net/crankedpvp/discordsync/DiscordSyncPlugin.java @@ -0,0 +1,102 @@ +package net.crankedpvp.discordsync; + + +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.discordsync.commands.SyncCommand; +import net.crankedpvp.discordsync.commands.UnSyncCommand; +import net.crankedpvp.discordsync.listeners.ChatListener; +import net.crankedpvp.discordsync.listeners.DiscordListener; +import net.crankedpvp.discordsync.managers.DatabaseManager; +import net.crankedpvp.discordsync.managers.SyncManager; +import net.crankedpvp.discordsync.utils.DiscordSettings; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.OnlineStatus; +import net.dv8tion.jda.api.entities.Activity; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.security.auth.login.LoginException; +import java.sql.SQLException; + +public class DiscordSyncPlugin extends JavaPlugin { + private static final String TOKEN = DiscordSettings.DISCORD_BOT_TOKEN; + private JDA jda; + private SyncManager syncManager; + private CommandManager commandManager; + private DatabaseManager databaseManager; + private DiscordListener discordListener; + private ChatListener chatListener; + + public SyncManager getSyncManager() { + return this.syncManager; + } + + public ChatListener getChatListener() { + return this.chatListener; + } + + public JDA getJda() { + return this.jda; + } + + public DatabaseManager getDatabaseManager() { + return this.databaseManager; + } + + public void onEnable() { + Bukkit.getScheduler().runTaskAsynchronously(this, () -> { + try { + this.jda = (new JDABuilder()).setToken(TOKEN).setActivity(Activity.playing("play.crankedpvp.org")).setStatus(OnlineStatus.ONLINE).build(); + } catch (LoginException var2) { + Bukkit.getScheduler().runTask(this, () -> { + Bukkit.getPluginManager().disablePlugin(this); + throw new RuntimeException("Shutting Discord Link plugin down, failed to initiate bot!", var2); + }); + } + + Bukkit.getScheduler().runTask(this, () -> { + this.commandManager = new CommandManager(this, true); + this.syncManager = new SyncManager(this); + this.chatListener = new ChatListener(this); + this.getServer().getPluginManager().registerEvents(this.chatListener, this); + this.commandManager.register(new SyncCommand(this)); + this.commandManager.register(new UnSyncCommand(this)); + this.discordListener = new DiscordListener(this); + this.jda.addEventListener(this.discordListener); + }); + }); + this.databaseManager = new DatabaseManager(this); + Bukkit.getScheduler().runTaskAsynchronously(this, ()-> { + try { + DiscordSyncPlugin.this.databaseManager.connect(); + DiscordSyncPlugin.this.databaseManager.createTable(); + Bukkit.getScheduler().runTaskLater(DiscordSyncPlugin.this, () -> { + DiscordSyncPlugin.this.databaseManager.fetchMap(); + }, 5L); + DiscordSyncPlugin.this.databaseManager.autoReconnect(850); + } catch (Exception var2) { + var2.printStackTrace(); + } + }); + } + + public void onDisable() { + this.jda.removeEventListener(this.discordListener); + + try { + this.databaseManager.getConnection().close(); + } catch (SQLException var2) { + var2.printStackTrace(); + } + + } + + public CommandManager getCommandManager() { + return this.commandManager; + } + + public DiscordListener getDiscordListener() { + return this.discordListener; + } +} diff --git a/DiscordSync/src/main/java/net/crankedpvp/discordsync/commands/SyncCommand.java b/DiscordSync/src/main/java/net/crankedpvp/discordsync/commands/SyncCommand.java new file mode 100644 index 0000000..afb3410 --- /dev/null +++ b/DiscordSync/src/main/java/net/crankedpvp/discordsync/commands/SyncCommand.java @@ -0,0 +1,62 @@ +package net.crankedpvp.discordsync.commands; + + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.discordsync.DiscordSyncPlugin; +import net.crankedpvp.discordsync.managers.SyncManager; +import net.dv8tion.jda.api.entities.User; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.List; + +@Command("sync") +@Alias({"syncaccount", "syncdiscord"}) +public class SyncCommand extends CommandBase { + private DiscordSyncPlugin plugin; + private SyncManager syncManager; + + public SyncCommand(DiscordSyncPlugin plugin) { + this.plugin = plugin; + this.syncManager = plugin.getSyncManager(); + } + + @Default + public void onCommand(Player player) { + if (!this.plugin.getDatabaseManager().isConnected()) { + player.sendMessage(CC.translate("&c&l(!)&c Account Sync is currently unavailable right now, please try again in a few.")); + } else if (this.syncManager.isAccountLinked(player.getUniqueId())) { + player.sendMessage(CC.translate("&c&l(!) &cYour account is already linked to &f&n" + this.syncManager.getLinkedUser(player.getUniqueId()).getAsTag() + "&c. Type &f/unsync&c to unsync your account.")); + } else { + int newCode; + if (this.syncManager.isCurrentlySyncing(player)) { + newCode = this.syncManager.getActiveSyncCode(player); + player.sendMessage(CC.translate("&a&l(!)&f Please send the &bCranked Sync Bot&f this message \"!verify " + newCode + "\".")); + } else { + newCode = this.syncManager.getRandomCode(); + this.syncManager.getActiveSyncMap().put(newCode, player.getUniqueId()); + List messages = new ArrayList<>(); + + messages.add(""); + messages.add("&b&lDISCORD ACCOUNT SYNC &8(Tutorial)"); + messages.add(""); + messages.add("&f* &7Join the Cranked /discord and find the &bCranked Sync Bot&7."); + messages.add("&f* &7Send the bot this message: &b'!verify " + newCode + "'&7."); + messages.add(""); + messages.add("&7Once you have followed these steps, your account should be linked!"); + messages.add(""); + + for (String message : messages) { + player.sendMessage(CC.translate(message)); + } + } + } + } +} diff --git a/DiscordSync/src/main/java/net/crankedpvp/discordsync/commands/UnSyncCommand.java b/DiscordSync/src/main/java/net/crankedpvp/discordsync/commands/UnSyncCommand.java new file mode 100644 index 0000000..d821680 --- /dev/null +++ b/DiscordSync/src/main/java/net/crankedpvp/discordsync/commands/UnSyncCommand.java @@ -0,0 +1,52 @@ +package net.crankedpvp.discordsync.commands; + + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.discordsync.DiscordSyncPlugin; +import net.crankedpvp.discordsync.managers.SyncManager; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import java.util.Objects; + +@Command("unsync") +@Alias({"unsyncaccount", "unsyncaccount", "unsyncdiscord"}) +public class UnSyncCommand extends CommandBase { + private final DiscordSyncPlugin plugin; + private final SyncManager syncManager; + public UnSyncCommand(DiscordSyncPlugin plugin) { + this.plugin = plugin; + this.syncManager = plugin.getSyncManager(); + + } + + @Default + public void onCommand(Player player, String toUnsync) { + if (!player.isOp()) { + player.sendMessage(CC.translate("&c&l(!)&c Only administrators can unsync your account, open a #general-support ticket in the crankedpvp /discord!")); + return; + } + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(toUnsync); + if (!this.plugin.getDatabaseManager().isConnected()) { + player.sendMessage(CC.translate("&c&l(!)&c Account Sync is currently unavailable right now, please try again in a few.")); + } else if (!this.syncManager.isAccountLinked(offlinePlayer.getUniqueId())) { + player.sendMessage(CC.translate("&c&l(!) &cTheir account is not synced!")); + } else { + Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> this.plugin.getDatabaseManager().remove(offlinePlayer.getUniqueId())); + player.sendMessage(CC.translate("&a&l(!) &fYou have &asuccessfully &funsync'ed " + offlinePlayer.getName() + "'s account")); + if (offlinePlayer.isOnline()) { + offlinePlayer.getPlayer().sendMessage(CC.translate("&c&l(!)&c Your account has been &funsync'ed &cby an administrator!")); + } + + + if (syncManager.isAccountLinked(offlinePlayer.getUniqueId())) { + this.plugin.getJda().getGuildById("470324147411615744").removeRoleFromMember(this.syncManager.getLinkedUser(offlinePlayer.getUniqueId()).getId(), Objects.requireNonNull(this.plugin.getJda().getGuildById("470324147411615744").getRoleById("980116575736696853"))).queue(); + } + } + } +} diff --git a/DiscordSync/src/main/java/net/crankedpvp/discordsync/listeners/ChatListener.java b/DiscordSync/src/main/java/net/crankedpvp/discordsync/listeners/ChatListener.java new file mode 100644 index 0000000..dde9c8e --- /dev/null +++ b/DiscordSync/src/main/java/net/crankedpvp/discordsync/listeners/ChatListener.java @@ -0,0 +1,157 @@ +package net.crankedpvp.discordsync.listeners; + + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.discordsync.DiscordSyncPlugin; +import net.crankedpvp.discordsync.utils.DiscordSettings; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.User; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +import java.util.*; + +public class ChatListener implements Listener { + public static final String LEADER_BADGE = CC.translate("&9&l❖"); + public static final String BOOSTER_BADGE = CC.translate("&d&l✪"); + private static final Set nitroBoosterList = new HashSet<>(); + private static final Set factionLeaderList = new HashSet<>(); + private static final Set youtuberList = new HashSet<>(); + private static final Set famousList = new HashSet<>(); + + private static final Map ranksAndPrefixes = new HashMap() {{ + put("", ""); + }}; + + + private final Guild crankedDiscord; + private final DiscordSyncPlugin plugin; + + public ChatListener(DiscordSyncPlugin plugin) { + this.plugin = plugin; + this.crankedDiscord = plugin.getJda().getGuildById(DiscordSettings.SERVER_ID); + + Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, ChatListener.this::updateNitroBoosters, 100L, 300*20); + + } + + public void updateNitroBoosters() { + if (this.plugin.getDatabaseManager().isConnected()) { + Map uuidUserMap = this.plugin.getDatabaseManager().fetchMap(); + Set toAddBoosters = new HashSet<>(); + Set toAddLeaders = new HashSet<>(); + Set toAddYoutubers = new HashSet<>(); + Set toAddFamous = new HashSet<>(); + + for (UUID uuid : uuidUserMap.keySet()) { + Long discordId = uuidUserMap.get(uuid); + User user = this.plugin.getJda().getUserById(discordId); + this.plugin.getJda().getGuilds().stream().filter((g) -> g.getName().equals(DiscordSettings.DISCORD_NAME)).findFirst().ifPresent((g) -> { + Member member = this.getMemberById(user, g); + if (user != null && member != null) { + if (member.getRoles().stream().anyMatch((r) -> r.getId().equals(DiscordSettings.NITRO_BOOSTER_ROLE))) { + toAddBoosters.add(uuid); + } + + if (member.getRoles().stream().anyMatch((r) -> r.getId().equals(DiscordSettings.FACTION_LEADER_ROLE))) { + toAddLeaders.add(uuid); + } + + if (member.getRoles().stream().anyMatch((r) -> r.getId().equals(DiscordSettings.MEDIA_ROLE))) { + toAddYoutubers.add(uuid); + } + + if (member.getRoles().stream().anyMatch((r) -> r.getId().equals(DiscordSettings.FAMOUS_ROLE))) { + toAddFamous.add(uuid); + } + } + }); + } + + Bukkit.getScheduler().runTask(this.plugin, () -> factionLeaderList.addAll(toAddLeaders)); + Bukkit.getScheduler().runTask(this.plugin, () -> nitroBoosterList.addAll(toAddBoosters)); + Bukkit.getScheduler().runTask(this.plugin, () -> youtuberList.addAll(toAddYoutubers)); + Bukkit.getScheduler().runTask(this.plugin, () -> famousList.addAll(toAddFamous)); + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + for (Player player : Bukkit.getOnlinePlayers()) { + checkPermissions(player); + } + }, 20L); + + + } + } + + + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + checkPermissions(player); + + } + + private void checkPermissions(Player player) { + if (player.hasPermission("cranked.kit.nitro") && !isNitroBooster(player)) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " permission set cranked.kit.nitro false"); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " permission set cranked.kit.nitro false"); + + } else if (isNitroBooster(player) && !player.hasPermission("cranked.kit.nitro")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " permission set cranked.kit.nitro true"); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " permission set cranked.kit.nitro true"); + } + if (player.hasPermission("cranked.kit.faction") && !isFactionLeader(player)) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " permission set cranked.kit.faction false"); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " permission set cranked.kit.faction false"); + } else if (isFactionLeader(player) && !player.hasPermission("cranked.kit.faction")) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " permission set cranked.kit.faction true"); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " permission set cranked.kit.faction true"); } + + if (player.hasPermission("cranked.kit.media") && !isYoutuber(player) && !player.isOp()) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " parent remove media"); + } else if (isYoutuber(player) && !player.hasPermission("cranked.kit.media") && !player.isOp()) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + player.getUniqueId() + " parent add media"); + } + + } + + public Member getMember(User user) { + try { + return this.crankedDiscord.getMember(user); + } catch (Exception var3) { + return null; + } + } + + public Member getMemberById(User user, Guild guild) { + try { + return guild.getMemberById(user.getId()); + } catch (Exception var4) { + return null; + } + } + + public static boolean isNitroBooster(Player player) { + return nitroBoosterList.contains(player.getUniqueId()); + } + + public static boolean isYoutuber(Player player) { + return youtuberList.contains(player.getUniqueId()); + } + + public static boolean isFamous(Player player) { + return famousList.contains(player.getUniqueId()); + } + + public static boolean isFactionLeader(Player player) { + return factionLeaderList.contains(player.getUniqueId()); + } + + public Set getNitroBoosterList() { + return nitroBoosterList; + } +} diff --git a/DiscordSync/src/main/java/net/crankedpvp/discordsync/listeners/DiscordListener.java b/DiscordSync/src/main/java/net/crankedpvp/discordsync/listeners/DiscordListener.java new file mode 100644 index 0000000..5fa614c --- /dev/null +++ b/DiscordSync/src/main/java/net/crankedpvp/discordsync/listeners/DiscordListener.java @@ -0,0 +1,57 @@ +package net.crankedpvp.discordsync.listeners; + + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.discordsync.DiscordSyncPlugin; +import net.crankedpvp.discordsync.utils.DiscordSettings; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.GenericEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import net.dv8tion.jda.api.hooks.EventListener; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import java.util.Objects; +import java.util.UUID; + +public class DiscordListener implements EventListener { + private final DiscordSyncPlugin plugin; + + public DiscordListener(DiscordSyncPlugin plugin) { + this.plugin = plugin; + } + + public void onEvent(GenericEvent gEvent) { + if (gEvent instanceof PrivateMessageReceivedEvent) { + PrivateMessageReceivedEvent event = (PrivateMessageReceivedEvent)gEvent; + User user = event.getAuthor(); + String message = event.getMessage().getContentStripped(); + if (message.startsWith("!verify ")) { + int codeEntered = Integer.parseInt(message.split(" ")[1]); + if (this.plugin.getDatabaseManager().contains(user.getIdLong())) { + event.getChannel().sendMessage("Your discord account is already linked!").queue(); + } else if (!this.plugin.getSyncManager().isActiveCode(codeEntered)) { + event.getChannel().sendMessage("You have entered an invalid code!").queue(); + } else { + UUID playerId = this.plugin.getSyncManager().getActiveSyncMap().get(codeEntered); + Player player = Bukkit.getPlayer(playerId); + if (player == null) { + event.getChannel().sendMessage("That player isn't online anymore!").queue(); + } else { + event.getChannel().sendMessage("Congrats! You have successfully linked your account to " + player.getName() + " on CrankedPvP! It can take up to 5 minutes to apply ingame.").queue(); + Objects.requireNonNull(Objects.requireNonNull(this.plugin.getJda().getGuildById(DiscordSettings.SERVER_ID)).getMember(user)).modifyNickname(player.getName()).queue(); + this.plugin.getJda().getGuildById(DiscordSettings.SERVER_ID).addRoleToMember(user.getId(), Objects.requireNonNull(this.plugin.getJda().getGuildById(DiscordSettings.SERVER_ID).getRoleById(DiscordSettings.SYNCED_ROLE))).queue(); + + this.plugin.getSyncManager().getActiveSyncMap().remove(codeEntered, playerId); + player.sendMessage(CC.translate("&a&l(!)&a You have successfully linked your account to &f&n" + user.getAsTag() + "&a.")); + player.playSound(player.getLocation(),Sound.ORB_PICKUP, 10, 10); + Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> { + this.plugin.getDatabaseManager().insert(playerId, user.getIdLong()); + }); + } + } + } + } + } +} diff --git a/DiscordSync/src/main/java/net/crankedpvp/discordsync/managers/DatabaseManager.java b/DiscordSync/src/main/java/net/crankedpvp/discordsync/managers/DatabaseManager.java new file mode 100644 index 0000000..fce559d --- /dev/null +++ b/DiscordSync/src/main/java/net/crankedpvp/discordsync/managers/DatabaseManager.java @@ -0,0 +1,190 @@ +package net.crankedpvp.discordsync.managers; + +import net.crankedpvp.discordsync.DiscordSyncPlugin; +import net.crankedpvp.discordsync.utils.DiscordSettings; +import org.bukkit.scheduler.BukkitRunnable; + +import java.sql.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class DatabaseManager { + private static final String TABLE_NAME = "discord_data"; + private Connection connection; + private final DiscordSyncPlugin plugin; + private final Map cachedResults = new HashMap<>(); + + public Connection getConnection() { + return this.connection; + } + + public DatabaseManager(DiscordSyncPlugin plugin) { + this.plugin = plugin; + } + + public void autoReconnect(int interval) { + (new BukkitRunnable() { + public void run() { + System.out.println("Running Auto Reconnect"); + + try { + if (DatabaseManager.this.plugin.getDatabaseManager().isConnected()) { + System.out.println("DB is currently connected, closing the connection..."); + DatabaseManager.this.plugin.getDatabaseManager().getConnection().close(); + System.out.println("Disconnected from DB."); + } else { + System.out.println("DB is currently NOT connected, opening new connection."); + } + + System.out.println("Opening a new connection."); + DatabaseManager.this.plugin.getDatabaseManager().connect(); + System.out.println("New connection opened successfully."); + } catch (Exception var2) { + var2.printStackTrace(); + System.out.println("Error in console."); + } + + } + }).runTaskTimerAsynchronously(this.plugin, interval * 20L, interval * 20L); + } + + public boolean isConnected() { + try { + return this.connection != null && !this.connection.isClosed(); + } catch (SQLException var2) { + var2.printStackTrace(); + return false; + } + } + + public void insert(UUID uuid, long discordId) { + try { + PreparedStatement insert = this.connection.prepareStatement("INSERT INTO discord_data (uuid,discordId) VALUES (?,?)"); + insert.setString(1, uuid.toString()); + insert.setLong(2, discordId); + insert.executeUpdate(); + } catch (Exception var5) { + var5.printStackTrace(); + } + + } + + public void remove(UUID uuid) { + try { + PreparedStatement remove = this.connection.prepareStatement("DELETE FROM discord_data WHERE UUID=?"); + remove.setString(1, uuid.toString()); + remove.executeUpdate(); + this.cachedResults.remove(uuid); + } catch (SQLException var3) { + var3.printStackTrace(); + } + + } + + public Long get(UUID uuid) throws Exception { + if (this.cachedResults.containsKey(uuid)) { + return this.cachedResults.get(uuid); + } else { + PreparedStatement statement = this.connection.prepareStatement("SELECT * FROM discord_data WHERE uuid=?"); + statement.setString(1, uuid.toString()); + ResultSet results = statement.executeQuery(); + if (!results.next()) { + return null; + } else { + Long discordId = results.getLong("discordId"); + this.cachedResults.put(uuid, discordId); + + return discordId; + } + } + } + + public boolean contains(UUID uuid) { + if (this.cachedResults.containsKey(uuid)) { + return true; + } else { + try { + return this.get(uuid) != null; + } catch (Exception var3) { + var3.printStackTrace(); + return false; + } + } + } + + public boolean contains(Long discordId) { + try { + PreparedStatement statement = this.connection.prepareStatement("SELECT * FROM discord_data WHERE discordId=?"); + statement.setLong(1, discordId); + ResultSet resultSet = statement.executeQuery(); + return resultSet.next(); + } catch (Exception var4) { + var4.printStackTrace(); + return false; + } + } + + public Map fetchMap() { + try { + PreparedStatement statement = this.connection.prepareStatement("SELECT * FROM discord_data"); + ResultSet results = statement.executeQuery(); + Map fetchedMap = new HashMap<>(); + + while(results.next()) { + try { + UUID uuid = UUID.fromString(results.getString("uuid")); + Long discordId = results.getLong("discordId"); + fetchedMap.put(uuid, discordId); + this.cachedResults.putIfAbsent(uuid, discordId); + } catch (Exception var6) { + System.out.println("error while mapping data"); + } + } + + return fetchedMap; + } catch (Exception var7) { + var7.printStackTrace(); + return Collections.EMPTY_MAP; + } + } + + /** @deprecated */ + @Deprecated + public ResultSet executeAsync(String sql) { + return null; + } + + public void connect() throws Exception { + synchronized(this) { + if (this.getConnection() != null && !this.getConnection().isClosed()) { + System.out.println("Current connect isn't closed!"); + } else { + try { + Class.forName("com.mysql.cj.jdbc.Driver"); + } catch (ClassNotFoundException ignored) { + Class.forName("com.mysql.jdbc.Driver"); + } + //this.connection = DriverManager.getConnection("jdbc:mysql://u4_1KRTto7gWF:96+HGu!c8h5Tt0PZ^5Nc=l3+@127.0.0.1:3306/s4_DiscordSync"); + this.connection = DriverManager.getConnection("jdbc:mysql://172.18.0.1:3306/s4_discordsync", DiscordSettings.DATABASE_USERNAME, DiscordSettings.DATABASE_PASSWORD); + System.out.println("DB connected!"); + } + } + } + + public void createTable() throws SQLException { + String sqlCreate = "CREATE TABLE IF NOT EXISTS `discord_data` (\t`uuid` VARCHAR(36),\n\t`discordId` BIGINT\n);"; + Statement statement = this.connection.createStatement(); + statement.execute(sqlCreate); + statement.close(); + } + + public DiscordSyncPlugin getPlugin() { + return this.plugin; + } + + public Map getCachedResults() { + return this.cachedResults; + } +} diff --git a/DiscordSync/src/main/java/net/crankedpvp/discordsync/managers/SyncManager.java b/DiscordSync/src/main/java/net/crankedpvp/discordsync/managers/SyncManager.java new file mode 100644 index 0000000..bd81d66 --- /dev/null +++ b/DiscordSync/src/main/java/net/crankedpvp/discordsync/managers/SyncManager.java @@ -0,0 +1,73 @@ +package net.crankedpvp.discordsync.managers; + +import net.crankedpvp.discordsync.DiscordSyncPlugin; +import net.crankedpvp.discordsync.utils.DiscordSettings; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +public class SyncManager { + private final DiscordSyncPlugin plugin; + private final HashMap activeSyncMap = new HashMap<>(); + private final Guild crankedDiscord; + + public HashMap getActiveSyncMap() { + return this.activeSyncMap; + } + + public SyncManager(DiscordSyncPlugin plugin) { + this.plugin = plugin; + this.crankedDiscord = plugin.getJda().getGuildById(DiscordSettings.SERVER_ID); + } + + public int getRandomCode() { + int randomCode; + for(randomCode = 0; this.isActiveCode(randomCode) || randomCode == 0; randomCode = ThreadLocalRandom.current().nextInt(10000, 99999)) { + + } + + return randomCode; + } + + public int getActiveSyncCode(Player player) { + return (Integer)this.activeSyncMap.keySet().stream().filter((code) -> ((UUID)this.activeSyncMap.get(code)).equals(player.getUniqueId())).findFirst().orElse(-1); + } + + public User getLinkedUser(UUID uuid) { + if (!this.plugin.getDatabaseManager().contains(uuid)) { + return null; + } else { + try { + return this.plugin.getJda().getUserById(this.plugin.getDatabaseManager().get(uuid)); + } catch (Exception var3) { + var3.printStackTrace(); + return null; + } + } + } + + public boolean isCurrentlySyncing(Player player) { + return this.activeSyncMap.containsValue(player.getUniqueId()); + } + + public boolean isAccountLinked(UUID uuid) { + return this.getLinkedUser(uuid) != null; + } + + public boolean isActiveCode(int code) { + return this.activeSyncMap.containsKey(code); + } + + public DiscordSyncPlugin getPlugin() { + return this.plugin; + } + + public Guild getCrankedDiscord() { + return this.crankedDiscord; + } + +} diff --git a/DiscordSync/src/main/java/net/crankedpvp/discordsync/utils/DiscordSettings.java b/DiscordSync/src/main/java/net/crankedpvp/discordsync/utils/DiscordSettings.java new file mode 100644 index 0000000..70f5a30 --- /dev/null +++ b/DiscordSync/src/main/java/net/crankedpvp/discordsync/utils/DiscordSettings.java @@ -0,0 +1,15 @@ +package net.crankedpvp.discordsync.utils; + +public class DiscordSettings { + public static final String NITRO_BOOSTER_ROLE = "1020069304965795891"; + public static final String FACTION_LEADER_ROLE = "1020057161994346632"; + public static final String MEDIA_ROLE = "1020057161994346634"; + public static final String FAMOUS_ROLE = "1020057161994346635"; + public static final String SYNCED_ROLE = "1020057161948217504"; + public static final String DISCORD_NAME = "CrankedPvP - Factions"; + public static final String SERVER_ID = "1020057161948217495"; + public static final String DISCORD_BOT_TOKEN = "MTAzOTk1NTkzNzA0MzE2MTE3OA.G3pu91.BnteWWBhtiueVMKi0Ydh4hla0gYXVbfXqxaFoI"; + public static final String DATABASE_USERNAME = "u4_ViERKcPbaQ"; + public static final String DATABASE_PASSWORD = "!Hjzx42w@Of0E0nQUT9oAQ@q"; + +} diff --git a/DiscordSync/src/main/resources/plugin.yml b/DiscordSync/src/main/resources/plugin.yml new file mode 100644 index 0000000..8b81a42 --- /dev/null +++ b/DiscordSync/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedDiscordSync +main: net.crankedpvp.discordsync.DiscordSyncPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/Duels/pom.xml b/Duels/pom.xml new file mode 100644 index 0000000..fa45bcf --- /dev/null +++ b/Duels/pom.xml @@ -0,0 +1,49 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Duels + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + Teams + + + net.crankedpvp + Collect + + + net.crankedpvp + Pets + + + net.crankedpvp + Enchants + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/Duels/src/main/java/net/crankedpvp/duels/DuelsAPI.java b/Duels/src/main/java/net/crankedpvp/duels/DuelsAPI.java new file mode 100644 index 0000000..2256236 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/DuelsAPI.java @@ -0,0 +1,144 @@ +package net.crankedpvp.duels; + +import com.google.common.collect.Maps; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.MiscUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.duels.struct.*; +import net.crankedpvp.teams.TeamsAPI; +import net.crankedpvp.teams.struct.Team; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.*; +import java.util.stream.Collectors; + +public class DuelsAPI { + + private static DuelManager duelManager = DuelsPlugin.getInstance().getDuelManager(); + + private static DuelTeam createDuelTeamFromPlayer(Player sender) { + Team team = TeamsAPI.hasTeam(sender) ? TeamsAPI.getTeamFromPlayer(sender) : TeamsAPI.createTeam(sender); + List duelPlayerList = new ArrayList<>(); + if(team.getMembers() != null && team.getMembers().size() > 0) + team.getMembers().stream() + .map(DuelsAPI::createDuelPlayer) + .forEach(duelPlayerList::add); + + Player player = team.getLeader().getPlayer(); + return new DuelTeam(createDuelPlayer(player), duelPlayerList); + } + + private static DuelPlayer createDuelPlayer(Player player) { + return new DuelPlayer(player.getUniqueId(), + Arrays.stream(player.getInventory().getContents()) + .filter(Objects::nonNull) + .map(ItemStack::clone) + .toArray(ItemStack[]::new), + MiscUtils.defaultIfNull(player.getInventory().getHelmet(), new ItemStack(Material.AIR)).clone(), + MiscUtils.defaultIfNull(player.getInventory().getChestplate(), new ItemStack(Material.AIR)).clone(), + MiscUtils.defaultIfNull(player.getInventory().getLeggings(), new ItemStack(Material.AIR)).clone(), + MiscUtils.defaultIfNull(player.getInventory().getBoots(), new ItemStack(Material.AIR)).clone()); + } + + public static DuelTeam getDuelTeamByPlayer(Player player) { + for(DuelMatch duelMatch : duelManager.getDuelMatches()) { + if(duelMatch.getTeamTwo().getDuelPlayersAsPlayers().contains(player)) return duelMatch.getTeamTwo(); + if(duelMatch.getTeamOne().getDuelPlayersAsPlayers().contains(player)) return duelMatch.getTeamOne(); + } + return createDuelTeamFromPlayer(player); + } + + public static DuelPlayer getDuelPlayerByPlayer(Player player) { + for(DuelMatch duelMatch : duelManager.getDuelMatches()) { + for(DuelPlayer duelPlayer : duelMatch.getTeamTwo().getDuelPlayersAsDuelPlayers()) { + if(duelPlayer.getPlayerUUID().equals(player.getUniqueId())) return duelPlayer; + } + for(DuelPlayer duelPlayer : duelMatch.getTeamOne().getDuelPlayersAsDuelPlayers()) { + if(duelPlayer.getPlayerUUID().equals(player.getUniqueId())) return duelPlayer; + } + } + System.out.println("not a player?"); + return null; + } + + public static DuelMatch getDuelMatchByPlayer(Player player) { + return duelManager.getDuelMatchFromTeam(getDuelTeamByPlayer(player)); + } + + public static EnumMap getDefaultSettings() { + EnumMap settings = Maps.newEnumMap(DuelSetting.class); + for(DuelSetting value : DuelSetting.values()) { + settings.put(value, value.isDefaultSetting()); + } + return settings; + } + + public static boolean isPlayerInDuel(Player player) { + for(DuelMatch duelMatch : duelManager.getDuelMatches()) { + if(duelMatch.getTeamTwo().getDuelPlayersAsPlayers().contains(player)) return true; + if(duelMatch.getTeamOne().getDuelPlayersAsPlayers().contains(player)) return true; + } + return false; + } + + public static void setPlayerDeadInDuel(Player player) { + for(DuelMatch duelMatch : duelManager.getDuelMatches()) { + if(duelMatch.getTeamTwo().getDuelPlayersAsPlayers().contains(player)) { + for(DuelPlayer duelPlayersAsDuelPlayer : duelMatch.getTeamTwo().getDuelPlayersAsDuelPlayers()) { + if(!duelPlayersAsDuelPlayer.isDead() && duelPlayersAsDuelPlayer.getPlayerUUID() == player.getUniqueId()) { + duelPlayersAsDuelPlayer.setDead(true);}}} + if(duelMatch.getTeamOne().getDuelPlayersAsPlayers().contains(player)) { + for(DuelPlayer duelPlayersAsDuelPlayer : duelMatch.getTeamOne().getDuelPlayersAsDuelPlayers()) { + if(!duelPlayersAsDuelPlayer.isDead() && duelPlayersAsDuelPlayer.getPlayerUUID() == player.getUniqueId()) { + duelPlayersAsDuelPlayer.setDead(true);}}} + } + } + + public static void setPlayerDeadAndCheckForWin(Player player) { + InventoryUtils.clearInventory(player); + player.teleport(Bukkit.getWorld("world").getSpawnLocation()); + SoundUtils.tryPlayErrorSound(player); + setPlayerDeadInDuel(player); + } + + public static List getItemsFromTeam(DuelTeam duelTeam) { + List itemStacks = new ArrayList<>(); + duelTeam.getDuelPlayersAsDuelPlayers().forEach(duelPlayer -> { + itemStacks.addAll(Arrays.asList(duelPlayer.getInitialInventory())); + itemStacks.add(duelPlayer.getHelmet()); + itemStacks.add(duelPlayer.getChestplate()); + itemStacks.add(duelPlayer.getLeggings()); + itemStacks.add(duelPlayer.getBoots()); + }); + return itemStacks.stream().filter(Objects::nonNull).filter(itemStack -> itemStack.getType() != Material.AIR).collect(Collectors.toList()); + } + + public static List getItemsFromPlayer(DuelPlayer duelPlayer) { + List itemStacks = new ArrayList<>(Arrays.asList(duelPlayer.getInitialInventory())); + itemStacks.add(duelPlayer.getHelmet()); + itemStacks.add(duelPlayer.getChestplate()); + itemStacks.add(duelPlayer.getLeggings()); + itemStacks.add(duelPlayer.getBoots()); + return itemStacks.stream().filter(Objects::nonNull).filter(itemStack -> itemStack.getType() != Material.AIR).collect(Collectors.toList()); + } + + public static DuelArena findOpenArena() { + List duelArenas = new ArrayList<>(DuelsPlugin.getInstance().getArenaRegister().getCacheValues()); + Collections.shuffle(duelArenas); + for(DuelArena duelArena : duelArenas) { + if(!duelArena.isActive()) return duelArena; + } + return null; + } + + public static boolean isParticipant(Player player) { + if(player == null || !player.isOnline()) return false; + for(DuelMatch duelMatch : DuelsPlugin.getInstance().getDuelManager().getDuelMatches()) { + if(duelMatch.getAllPlayers().contains(player)) return true; + } + return false; + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/DuelsPlugin.java b/Duels/src/main/java/net/crankedpvp/duels/DuelsPlugin.java new file mode 100644 index 0000000..67529fe --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/DuelsPlugin.java @@ -0,0 +1,81 @@ +package net.crankedpvp.duels; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.collect.CollectPlugin; +import net.crankedpvp.collect.struct.CollectCategory; +import net.crankedpvp.collect.struct.CollectType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.duels.commands.DuelCommand; +import net.crankedpvp.duels.listeners.DamageListener; +import net.crankedpvp.duels.listeners.PlayerDeathListener; +import net.crankedpvp.duels.listeners.PlayerDisconnectListener; +import net.crankedpvp.duels.listeners.PlayerListener; +import net.crankedpvp.duels.struct.*; +import org.bukkit.Bukkit; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.List; +import java.util.Objects; + +public class DuelsPlugin extends JavaPlugin { + + @Getter + private static DuelsPlugin instance; + + @Getter + private DuelManager duelManager; + + @Getter + private ArenaRegister arenaRegister; + + @Getter + private DuelPlayerHandler duelPlayerHandler; + + @Override + public void onEnable() { + instance = this; + this.duelManager = new DuelManager(this); + this.arenaRegister = new ArenaRegister(this); + this.arenaRegister.loadAll(); + + this.duelPlayerHandler = new DuelPlayerHandler(this); + CommandManager commandManager = new CommandManager(this); + commandManager.register(new DuelCommand(this)); + + registerListeners(); + } + + @Override + public void onDisable() { + this.arenaRegister.saveAll(); + this.getLogger().info("Removing players from active duel matches..."); + for(DuelMatch duelMatch : this.duelManager.getDuelMatches()) { + if(duelMatch.getDuelStatus() != DuelStatus.ACTIVE) continue; + this.getLogger().info("Arena: " + duelMatch.getDuelArena().getArenaName() + " Removing " + duelMatch.getAllPlayers().size() + " players"); + for(DuelPlayer duelPlayer : duelMatch.getAllDuelPlayers()) { + if(!duelPlayer.isDead()) { + InventoryUtils.clearInventory(duelPlayer.getPlayer()); + } + duelPlayer.getPlayer().teleport(Bukkit.getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + duelPlayer.getPlayer().sendMessage(CC.translate("&cYour duel match has been forcefully ")); + List items = DuelsAPI.getItemsFromPlayer(Objects.requireNonNull(duelPlayer)); + if(items.size() == 0) return; + CollectPlugin.getInstance().getCollectManager().getOrCreate(duelPlayer.getPlayerUUID().toString()).add(new CollectCategory(CollectType.DUEL, items.toArray(new ItemStack[items.size() - 1]), CC.RedB + "Your duel items", System.currentTimeMillis())); + } + } + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new PlayerDeathListener(this), this); + pluginManager.registerEvents(new PlayerDisconnectListener(this), this); + pluginManager.registerEvents(new DamageListener(this), this); + pluginManager.registerEvents(new PlayerListener(), this); + } + +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/commands/DuelCommand.java b/Duels/src/main/java/net/crankedpvp/duels/commands/DuelCommand.java new file mode 100644 index 0000000..2307964 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/commands/DuelCommand.java @@ -0,0 +1,165 @@ +package net.crankedpvp.duels.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.DuelsPlugin; +import net.crankedpvp.duels.inventory.DuelAcceptUI; +import net.crankedpvp.duels.inventory.DuelSettingsUI; +import net.crankedpvp.duels.struct.*; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("duel") +public class DuelCommand extends CommandBase { + + private final DuelsPlugin plugin; + public DuelCommand(DuelsPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final CommandSender commandSender, @Optional @Completion("#players") final Player toDuel) { + if(!(commandSender instanceof Player)) { + commandSender.sendMessage(CC.translate("&cOnly players can execute this command")); + return; + } + + Player sender = ((Player) commandSender); + + if(toDuel == null) { + sender.sendMessage(CC.translate("&cPlayer Duels")); + sender.sendMessage(CC.translate("&f/duel ")); + return; + } + + if(!toDuel.isOnline()) { + sender.sendMessage(CC.translate("&cThat player is not online")); + SoundUtils.tryPlayErrorSound(sender); + return; + } + + if(this.plugin.getDuelManager().getDuelMatches().contains(DuelsAPI.getDuelMatchByPlayer(sender))) { + DuelMatch duelMatch = DuelsAPI.getDuelMatchByPlayer(sender); + if(duelMatch.getSendingTeam().getDuelPlayersAsPlayers().contains(sender)) { + sender.sendMessage(CC.translate(DuelManager.prefix + "&cYou have already sent another team a duel request")); + SoundUtils.tryPlayErrorSound(sender); + return; + } + DuelsPlugin.getInstance().getDuelManager().getDuelMatches().remove(duelMatch); + sender.sendMessage(CC.translate(DuelManager.prefix + "&cYour incoming duel request has been cancelled")); + } + + if(WorldGuardUtils.canPvPInRegion(sender)) { + sender.sendMessage(CC.translate(DuelManager.prefix + "&cYou cannot send a duel request unless you are in a safezone")); + SoundUtils.tryPlayErrorSound(sender); + return; + } + + DuelTeam senderDuelTeam = DuelsAPI.getDuelTeamByPlayer(sender); + DuelTeam receiverDuelTeam = DuelsAPI.getDuelTeamByPlayer(toDuel); + if(senderDuelTeam.getAmountOfPlayers() != receiverDuelTeam.getAmountOfPlayers()) { + sender.sendMessage(CC.translate(DuelManager.prefix + "&cYour team &7(" + senderDuelTeam.getAmountOfPlayers() + " players) &cdoes not have equal players to this team")); + return; + } + + DuelSettingsUI duelSettingsUI = new DuelSettingsUI(senderDuelTeam, receiverDuelTeam, DuelsAPI.getDefaultSettings()); + duelSettingsUI.getSettingsUI().open(sender); + } + + + @SubCommand("setspawn") + @Permission("cranked.admin") + public void setSpawnCommand(final Player player, String duelArenaName, String team) { + if(this.plugin.getArenaRegister().containsKey(duelArenaName)) { + DuelArena duelArena = this.plugin.getArenaRegister().getFromCache(duelArenaName); + if(team.equals("true")) duelArena.setSpawnPointOne(player.getLocation()); + if(team.equals("false")) duelArena.setSpawnPointTwo(player.getLocation()); + return; + } + this.plugin.getArenaRegister().addToCache(new DuelArena(duelArenaName, player.getLocation(), player.getLocation())); + + player.sendMessage("setup"); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + + } + + @SubCommand("cancel") + public void cancelCommand(final CommandSender commandSender) { + if(!(commandSender instanceof Player)) { + commandSender.sendMessage(CC.translate("&cOnly players can execute this command")); + return; + } + + Player sender = ((Player) commandSender); + DuelTeam duelReceiver = DuelsAPI.getDuelTeamByPlayer(sender); + if(!sender.getName().equals(duelReceiver.getDuelTeamLeader().getName())) { + sender.sendMessage(CC.translate(DuelManager.prefix + "&cOnly the team leader can cancel duel requests")); + return; + } + + DuelMatch duelMatch = this.plugin.getDuelManager().getDuelMatchFromTeam(duelReceiver); + this.plugin.getDuelManager().getDuelMatches().remove(duelMatch); + for(Player allPlayer : duelMatch.getAllPlayers()) { + allPlayer.sendMessage(CC.translate(DuelManager.prefix + "&cThis duel has been aborted by " + sender.getName())); + } + + } + + + @SubCommand("accept") + public void acceptCommand(final CommandSender commandSender, @Completion("#players") final Player player) { + if(!(commandSender instanceof Player)) { + commandSender.sendMessage(CC.translate("&cOnly players can execute this command")); + return; + } + + Player sender = ((Player) commandSender); + DuelTeam duelReceiver = DuelsAPI.getDuelTeamByPlayer(sender); + if(!sender.getName().equals(duelReceiver.getDuelTeamLeader().getName())) { + sender.sendMessage(CC.translate(DuelManager.prefix + "&cOnly the team leader can accept duel requests")); + return; + } + + if(!this.plugin.getDuelManager().hasBeenDueled(duelReceiver)) { + sender.sendMessage(CC.translate(DuelManager.prefix + "&cYour team has not been sent a duel request")); + return; + } + DuelTeam duelSender = DuelsAPI.getDuelTeamByPlayer(player); + + if(duelReceiver.getAmountOfPlayers() != duelSender.getAmountOfPlayers()) { + sender.sendMessage(CC.translate(DuelManager.prefix + "&cYour team &7(" + duelReceiver.getAmountOfPlayers() + " players) &cdoes not have equal amount of players to this team")); + return; + } + + + DuelMatch duelMatch = this.plugin.getDuelManager().getDuelMatchFromTeam(duelReceiver); + if(WorldGuardUtils.canPvPInRegion(sender)) { + sender.sendMessage(CC.translate(DuelManager.prefix + "&cYou cannot accept a duel request unless you are in a safezone")); + SoundUtils.tryPlayErrorSound(sender); + return; + } + + for(Player duelMatchPlayer : duelMatch.getAllPlayers()) { + if(WorldGuardUtils.canPvPInRegion(duelMatchPlayer)) { + duelMatch.sendToAllPlayers(CC.translate(DuelManager.prefix + "&cThe duel cannot be accepted as &4" + duelMatchPlayer.getName() + " &cis not in a safezone")); + SoundUtils.tryPlayErrorSound(sender); + return; + } + } + + if(duelMatch.getDuelStatus() == DuelStatus.ACTIVE) { + sender.sendMessage(DuelManager.prefix + "&cThis duel has already begun"); + sender.playSound(sender.getLocation(), Sound.ANVIL_BREAK, 2.0f, 2.0f); + return; + } + //sender.sendMessage("YOUR TEAM (" + duelMatch.getTeamTwo().getAmountOfPlayers() + ") vs " + duelMatch.getTeamOne().getDuelTeamLeader().getName() + "'s Team (" + duelMatch.getTeamOne().getAmountOfPlayers() + ")"); + DuelAcceptUI duelAcceptUI = new DuelAcceptUI(duelMatch); + duelAcceptUI.getAcceptUI().open(duelReceiver.getDuelTeamLeader()); + + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelAcceptUI.java b/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelAcceptUI.java new file mode 100644 index 0000000..d7a16cf --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelAcceptUI.java @@ -0,0 +1,122 @@ +package net.crankedpvp.duels.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.MiscUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.DuelsPlugin; +import net.crankedpvp.duels.struct.DuelManager; +import net.crankedpvp.duels.struct.DuelMatch; +import net.crankedpvp.duels.struct.DuelPlayer; +import net.crankedpvp.duels.struct.DuelSetting; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +public class DuelAcceptUI { + + private boolean forceClose = false; + private final EnumMap currentSettings; + + @Getter + private final Gui acceptUI; + + public DuelAcceptUI(DuelMatch duelMatch) { + this.currentSettings = duelMatch.getSettings(); + this.acceptUI = new Gui(GuiType.HOPPER, "Duel Accept"); + this.acceptUI.setDefaultClickAction(event -> event.setCancelled(true)); + this.acceptUI.setCloseGuiAction(inventoryCloseEvent -> { + if(forceClose) return; + DuelManager duelManager = DuelsPlugin.getInstance().getDuelManager(); + duelMatch.getTeamOne().getDuelPlayersAsPlayers().forEach(player -> { + player.sendMessage(CC.translate(DuelManager.prefix + "&c" + duelMatch.getTeamTwo().getDuelTeamLeader().getName() + "'s team has declined the duel")); + SoundUtils.tryPlayErrorSound(player); + }); + duelMatch.getTeamTwo().getDuelPlayersAsPlayers().forEach(player -> { + player.sendMessage(CC.translate(DuelManager.prefix + "&cYour team has declined the duel against " + duelMatch.getTeamOne().getDuelTeamLeader().getName() + "'s team")); + SoundUtils.tryPlayErrorSound(player); + }); + duelManager.getDuelMatches().remove(duelMatch); + }); + + updateConfirmButton(duelMatch); + + } + + private void updateConfirmButton(DuelMatch duelMatch) { + this.acceptUI.updateItem(2, new GuiItem(createConfirmButton(), event -> { + this.forceClose = true; + event.getWhoClicked().closeInventory(); + SoundUtils.tryPlaySuccessSound(event.getWhoClicked()); + event.getWhoClicked().sendMessage(CC.translate(DuelManager.prefix + "&aAccepted duel against " + duelMatch.getTeamOne().getDuelTeamLeader().getName() + "'s team")); + duelMatch.getTeamOne().getDuelTeamLeader().sendMessage(CC.translate(DuelManager.prefix + "&aThe player &6" + duelMatch.getReceivingTeam().getDuelTeamLeader().getName() + " &ahas accepted your teams duel request")); + + DuelConfirmUI duelConfirmUI = new DuelConfirmUI(duelMatch); + Gui gui = duelConfirmUI.getDuelConfirmUI(); + duelMatch.getAllPlayers().forEach(gui::open); + /* + for(Player teamOnePlayer : duelMatch.getTeamOne().getDuelPlayersAsPlayers()) { + resetInventory(teamOnePlayer); + teamOnePlayer.teleport(duelMatch.getDuelArena().getSpawnPointOne(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + InventorySettings.applyInventorySettings(teamOnePlayer, this.currentSettings); + } + + for(Player teamTwoPlayer : duelMatch.getTeamTwo().getDuelPlayersAsPlayers()) { + resetInventory(teamTwoPlayer); + teamTwoPlayer.teleport(duelMatch.getDuelArena().getSpawnPointTwo(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + InventorySettings.applyInventorySettings(teamTwoPlayer, this.currentSettings); + } + + */ + })); + } + + + private void resetInventory(Player player) { + DuelPlayer duelPlayer = DuelsAPI.getDuelPlayerByPlayer(player); + assert duelPlayer != null; + ItemStack[] itemStacks = Arrays.stream(player.getInventory().getContents()) + .filter(Objects::nonNull) + .map(ItemStack::clone) + .toArray(ItemStack[]::new); + duelPlayer.setInitialInventory(itemStacks); + duelPlayer.setHelmet(MiscUtils.defaultIfNull(player.getInventory().getHelmet(), new ItemStack(Material.AIR)).clone()); + duelPlayer.setChestplate(MiscUtils.defaultIfNull(player.getInventory().getChestplate(), new ItemStack(Material.AIR)).clone()); + duelPlayer.setLeggings(MiscUtils.defaultIfNull(player.getInventory().getLeggings(), new ItemStack(Material.AIR)).clone()); + duelPlayer.setBoots(MiscUtils.defaultIfNull(player.getInventory().getBoots(), new ItemStack(Material.AIR)).clone()); + } + + /* + private void equipPlayer(Player player) { + player.getInventory().clear(); + player.getInventory().setHelmet(new ItemBuilder(Material.DIAMOND_HELMET, "&b&lDuel Armor").addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).colorize().build()); + player.getInventory().setChestplate(new ItemBuilder(Material.DIAMOND_CHESTPLATE, "&b&lDuel Armor").addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).colorize().build()); + player.getInventory().setLeggings(new ItemBuilder(Material.DIAMOND_LEGGINGS, "&b&lDuel Armor").addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).colorize().build()); + player.getInventory().setBoots(new ItemBuilder(Material.DIAMOND_BOOTS, "&b&lDuel Armor").addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4).addEnchantment(Enchantment.DURABILITY, 3).colorize().build()); + player.getInventory().setHeldItemSlot(0); + player.getInventory().setItemInHand(new ItemBuilder(Material.DIAMOND_SWORD, "&b&lDuel Weapon").addEnchantment(Enchantment.DAMAGE_ALL, 5).colorize().build()); + } + + */ + + private ItemStack createConfirmButton() { + ItemBuilder itemBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.LIME.getWoolData()); + itemBuilder.setName("&a&lAccept Duel"); + List lore = new ArrayList<>(); + this.currentSettings.forEach((key, value) -> lore.add("&4&l* &c" + key.getSettingName() + ": " + getEnabled(value))); + itemBuilder.setLore(lore); + return itemBuilder.colorize().build(); + } + + private String getEnabled(boolean enabled) { + return enabled ? "&a&lENABLED" : "&c&lDISABLED"; + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelConfirmUI.java b/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelConfirmUI.java new file mode 100644 index 0000000..04330a2 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelConfirmUI.java @@ -0,0 +1,232 @@ +package net.crankedpvp.duels.inventory; + +import de.tr7zw.nbtapi.NBTItem; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import net.crankedpvp.crankedutils.utils.MiscUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.DuelsPlugin; +import net.crankedpvp.duels.struct.DuelManager; +import net.crankedpvp.duels.struct.DuelMatch; +import net.crankedpvp.duels.struct.DuelPlayer; +import net.crankedpvp.duels.struct.DuelStatus; +import net.crankedpvp.duels.utils.InventorySettings; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; + +public class DuelConfirmUI { + private boolean forceClose = false; + private List settingsLore; + private List clickCooldown; + private DuelMatch duelMatch; + private int maxPlayers; + private int acceptedPlayers = 0; + + private boolean closed = false; + + private int countdownTaskID; + + @Getter + private final Gui duelConfirmUI; + + public DuelConfirmUI(DuelMatch duelMatch) { + this.registerValues(duelMatch); + this.duelConfirmUI = new Gui(6, "Duel Accept"); + this.duelConfirmUI.setDefaultClickAction(event -> event.setCancelled(true)); + this.duelConfirmUI.setCloseGuiAction(inventoryCloseEvent -> { + if(!this.forceClose) { + this.closed = true; + duelMatch.setDuelStatus(DuelStatus.CANCELLED); + Player closingPlayer = (Player)inventoryCloseEvent.getPlayer(); + List players = duelMatch.getAllPlayers(); + players.remove(closingPlayer); + this.stopCountdown(); + closingPlayer.sendMessage(CC.translate(DuelManager.prefix + "&cYou have aborted your duel")); + DuelsPlugin.getInstance().getDuelManager().getDuelMatches().remove(duelMatch); + players.forEach(player -> { + player.closeInventory(); + player.sendMessage(CC.translate(DuelManager.prefix + "&cThis duel has been aborted by " + closingPlayer.getName())); + }); + } + if(duelMatch.getDuelStatus() == DuelStatus.CANCELLED) return; + if(this.closed) return; + this.closed = true; + List players = duelMatch.getAllPlayers(); + duelMatch.setDuelStatus(DuelStatus.ACTIVE); + players.forEach(player -> { + EssentialsUtils.clearTeleportRequests(player); + player.closeInventory(); + player.sendMessage(CC.translate(DuelManager.prefix + "&aThe duel has started")); + }); + this.startDuel(); + }); + + splitGui(0); + addPlayersConfirmButtonsToUI(); + } + + private void startDuel() { + for(Player teamOnePlayer : duelMatch.getTeamOne().getDuelPlayersAsPlayers()) { + resetInventory(teamOnePlayer); + teamOnePlayer.teleport(duelMatch.getDuelArena().getSpawnPointOne(), PlayerTeleportEvent.TeleportCause.PLUGIN); + InventorySettings.applyInventorySettings(teamOnePlayer, this.duelMatch.getSettings()); + } + + for(Player teamTwoPlayer : duelMatch.getTeamTwo().getDuelPlayersAsPlayers()) { + resetInventory(teamTwoPlayer); + teamTwoPlayer.teleport(duelMatch.getDuelArena().getSpawnPointTwo(), PlayerTeleportEvent.TeleportCause.PLUGIN); + InventorySettings.applyInventorySettings(teamTwoPlayer, this.duelMatch.getSettings()); + } + } + + private void registerValues(DuelMatch duelMatch) { + duelMatch.setDuelStatus(DuelStatus.CONFIRMING); + this.duelMatch = duelMatch; + this.maxPlayers = duelMatch.getAllPlayers().size(); + this.clickCooldown = new ArrayList<>(); + List settingsLore = new ArrayList<>(); + duelMatch.getSettings().forEach((key, value) -> settingsLore.add("&4&l* &c" + key.getSettingName() + ": " + getEnabled(value))); + this.settingsLore = settingsLore; + } + + private void addPlayersConfirmButtonsToUI() { + List teamOne = duelMatch.getTeamOne().getDuelPlayersAsPlayers(); + List teamTwo = duelMatch.getTeamTwo().getDuelPlayersAsPlayers(); + int[] teamOneSlots = new int[] {0, 1, 2, 3, 9, 10, 11, 12, 18, 19, 20, 21}; + int[] teamTwoSlots = new int[] {8, 7, 6, 5, 17, 16, 15, 14, 26, 25, 24, 23}; + for(int i = 0; i < teamOne.size(); i++) { + this.duelConfirmUI.updateItem(teamOneSlots[i], new GuiItem(setupPlayersAcceptButton(teamOne.get(i), false), this::runAcceptCheck)); + } + for(int i = 0; i < teamTwo.size(); i++) { + this.duelConfirmUI.updateItem(teamTwoSlots[i], new GuiItem(setupPlayersAcceptButton(teamTwo.get(i), false), this::runAcceptCheck)); + } + } + + private void runAcceptCheck(InventoryClickEvent event) { + if(this.clickCooldown.contains((Player) event.getWhoClicked())) return; + this.clickCooldown.add((Player) event.getWhoClicked()); + Bukkit.getScheduler().runTaskLater(DuelsPlugin.getInstance(), () -> this.clickCooldown.remove((Player) event.getWhoClicked()), 10L); + NBTItem nbtItem = new NBTItem(event.getCurrentItem()); + UUID playerUUID = UUID.fromString(nbtItem.getString("playerUUID")); + if(!event.getWhoClicked().getUniqueId().equals(playerUUID)) return; + this.duelConfirmUI.updateItem(event.getSlot(), new GuiItem(setupPlayersAcceptButton(Bukkit.getPlayer(playerUUID), !nbtItem.getBoolean("accepted")), this::runAcceptCheck)); + this.updateGuiForAllPlayers(); + } + + private void updateGuiForAllPlayers() { + duelMatch.getAllPlayers().forEach(Player::updateInventory); + } + + private ItemStack setupPlayersAcceptButton(Player player, boolean accepted) { + ItemBuilder itemBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, "&a&lAccept? &7(" + player.getName() + ")", "&fClick to accept the duel"); + if(accepted) { + this.acceptedPlayers++; + itemBuilder.setDurability((short) 5); + itemBuilder.setGlowing(); + if(this.acceptedPlayers == this.maxPlayers) this.startCountdown(); + + } else { + itemBuilder.setDurability((short) 14); + if(this.acceptedPlayers != 0) { + this.acceptedPlayers--; + this.stopCountdown(); + } + + } + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("playerUUID", player.getUniqueId().toString()); + nbtItem.setBoolean("accepted", accepted); + return nbtItem.getItem(); + } + + private void stopCountdown() { + DuelsPlugin.getInstance().getServer().getScheduler().cancelTask(this.countdownTaskID); + this.splitGui(0); + } + + private void startCountdown() { + AtomicInteger countdown = new AtomicInteger(5); + this.countdownTaskID = DuelsPlugin.getInstance().getServer().getScheduler().scheduleAsyncRepeatingTask(DuelsPlugin.getInstance(), () -> { + this.splitGui(countdown.get()); + if(countdown.get() == 0) { + this.stopCountdown(); + this.forceClose = true; + this.duelMatch.getAllPlayers().forEach(HumanEntity::closeInventory); + return; + } + + countdown.getAndDecrement(); + this.getAllPlayers().forEach(player -> player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0f, 2.0f)); + }, 0L, 20); + } + + private List getAllPlayers() { + return this.duelMatch.getAllPlayers(); + } + + private void splitGui(int num) { + for(int i = 1; i < 7; i++) { + this.duelConfirmUI.updateItem(i, 5, new GuiItem(this.getSplitterItem(num))); + } + } + + private ItemStack getSplitterItem(int num) { + ItemBuilder itemBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, (num == 0 ? 1 : num)); + itemBuilder.setLore(this.settingsLore); + switch(num) { + case 0: + if(this.maxPlayers == this.acceptedPlayers) { + itemBuilder.setName("&a&lStarting Duel.."); + } else { + itemBuilder.setName("&fWaiting for players to accept..."); + } + break; + case 4: + case 3: + itemBuilder.setDurability((short) 1); + itemBuilder.setName("&6&l" + num + ".."); + break; + case 2: + case 1: + itemBuilder.setDurability((short) 14); + itemBuilder.setName("&c&l" + num + ".."); + break; + default: + itemBuilder.setDurability((short) 4); + itemBuilder.setName("&e&l" + num + ".."); + } + return itemBuilder.colorize().build(); + } + + private String getEnabled(boolean enabled) { + return enabled ? "&a&lENABLED" : "&c&lDISABLED"; + } + + private void resetInventory(Player player) { + DuelPlayer duelPlayer = DuelsAPI.getDuelPlayerByPlayer(player); + assert duelPlayer != null; + ItemStack[] itemStacks = Arrays.stream(player.getInventory().getContents()) + .filter(Objects::nonNull) + .map(ItemStack::clone) + .toArray(ItemStack[]::new); + duelPlayer.setInitialInventory(itemStacks); + duelPlayer.setHelmet(MiscUtils.defaultIfNull(player.getInventory().getHelmet(), new ItemStack(Material.AIR)).clone()); + duelPlayer.setChestplate(MiscUtils.defaultIfNull(player.getInventory().getChestplate(), new ItemStack(Material.AIR)).clone()); + duelPlayer.setLeggings(MiscUtils.defaultIfNull(player.getInventory().getLeggings(), new ItemStack(Material.AIR)).clone()); + duelPlayer.setBoots(MiscUtils.defaultIfNull(player.getInventory().getBoots(), new ItemStack(Material.AIR)).clone()); + } + +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelSettingsUI.java b/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelSettingsUI.java new file mode 100644 index 0000000..bf6ca32 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/inventory/DuelSettingsUI.java @@ -0,0 +1,112 @@ +package net.crankedpvp.duels.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.Clickable; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.DuelsPlugin; +import net.crankedpvp.duels.struct.*; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; + +public class DuelSettingsUI { + + private boolean forceClose = false; + + private EnumMap currentSettings; + + @Getter + private final Gui settingsUI; + + public DuelSettingsUI(DuelTeam teamOne, DuelTeam teamTwo, EnumMap currentSettings) { + this.currentSettings = currentSettings; + this.settingsUI = new Gui(3, "Duel Settings"); + this.settingsUI.setDefaultClickAction(event -> event.setCancelled(true)); + + /* + this.settingsUI.setCloseGuiAction(inventoryCloseEvent -> { + if(forceClose) return; + }); + + */ + + updateConfirmButton(teamOne, teamTwo); + + for(DuelSetting duelSetting : DuelSetting.values()) { + this.settingsUI.addItem(new GuiItem(buildSetting(duelSetting), event -> { + this.currentSettings.put(duelSetting, !currentSettings.get(duelSetting)); + this.settingsUI.updateItem(event.getSlot(), buildSetting(duelSetting)); + updateConfirmButton(teamOne, teamTwo); + SoundUtils.tryPlaySuccessSound(event.getWhoClicked()); + })); + } + this.settingsUI.getFiller().fill(new GuiItem(GuiUtil.createFillerItem())); + } + + private void updateConfirmButton(DuelTeam senderTeam, DuelTeam receiverTeam) { + this.settingsUI.updateItem(3, 5, new GuiItem(createConfirmButton(), event -> { + forceClose = true; + event.getWhoClicked().closeInventory(); + SoundUtils.tryPlaySuccessSound(event.getWhoClicked()); + DuelArena duelArena = DuelsAPI.findOpenArena(); + if(duelArena == null) { + senderTeam.getDuelTeamLeader().sendMessage(DuelManager.prefix + "&eYou cannot duel as there are no open arenas"); + return; + } + DuelMatch duelMatch = new DuelMatch(senderTeam, receiverTeam, this.currentSettings, duelArena, DuelStatus.INACTIVE); + duelMatch.setDuelStatus(DuelStatus.SELECTING); + DuelsPlugin.getInstance().getDuelManager().getDuelMatches().add(duelMatch); + Clickable clickable = new Clickable(CC.translate(DuelManager.prefix + "&eThe player &7" + senderTeam.getDuelTeamLeader().getName() + " &ehas sent your team a duel request"), + "&7Click &fhere &7to accept the duel", + "/duel accept " + senderTeam.getDuelTeamLeader().getName()); + clickable.sendToPlayer(receiverTeam.getDuelTeamLeader()); + senderTeam.getDuelTeamLeader().sendMessage(CC.translate(DuelManager.prefix + "&eDuel request sent to " + receiverTeam.getDuelTeamLeader().getName() + "'s team")); + senderTeam.getDuelTeamLeader().sendMessage(CC.translate(DuelManager.prefix + "&eThis duel request will expire in &730 seconds")); + + DuelsPlugin.getInstance().getServer().getScheduler().runTaskLater(DuelsPlugin.getInstance(), () -> { + if(duelMatch.getDuelStatus() == DuelStatus.INACTIVE) { + DuelsPlugin.getInstance().getDuelManager().getDuelMatches().remove(duelMatch); + duelMatch.getTeamOne().getDuelTeamLeader().sendMessage(CC.translate(DuelManager.prefix + "&cYour duel request to " + duelMatch.getTeamTwo().getDuelTeamLeader().getName() + " has expired")); + duelMatch.getTeamTwo().getDuelTeamLeader().sendMessage(CC.translate(DuelManager.prefix + "&cThe incoming duel request from " + duelMatch.getTeamOne().getDuelTeamLeader().getName() + " has expired")); + SoundUtils.tryPlayErrorSound(duelMatch.getTeamTwo().getDuelTeamLeader()); + SoundUtils.tryPlayErrorSound(duelMatch.getTeamOne().getDuelTeamLeader()); + } + }, 20L * 30); + })); + } + + private ItemStack createConfirmButton() { + ItemBuilder itemBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.LIME.getWoolData()); + itemBuilder.setName("&a&lConfirm Selection"); + List lore = new ArrayList<>(); + this.currentSettings.forEach((key, value) -> lore.add("&4&l* &c" + key.getSettingName() + ": " + getEnabled(value))); + itemBuilder.setLore(lore); + return itemBuilder.colorize().build(); + } + + private String getEnabled(boolean enabled) { + return enabled ? "&a&lENABLED" : "&c&lDISABLED"; + } + + private ItemStack buildSetting(DuelSetting duelSetting) { + List lore = new ArrayList<>(); + boolean enabled = this.currentSettings.get(duelSetting); + for(String line : duelSetting.getDisplayLore()) { + if(line.contains("{enabled}")) line = line.replace("{enabled}", getEnabled(enabled)); + lore.add(line); + } + ItemBuilder itemBuilder = new ItemBuilder(duelSetting.getDisplayMaterial(), duelSetting.getDisplayName(), lore); + if(enabled) itemBuilder.setGlowing(); + return itemBuilder.colorize().build(); + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/listeners/DamageListener.java b/Duels/src/main/java/net/crankedpvp/duels/listeners/DamageListener.java new file mode 100644 index 0000000..ab8713e --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/listeners/DamageListener.java @@ -0,0 +1,58 @@ +package net.crankedpvp.duels.listeners; + +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.DuelsPlugin; +import net.crankedpvp.duels.struct.DuelPlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class DamageListener implements Listener { + + private DuelsPlugin plugin; + public DamageListener(DuelsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void entityDamage(EntityDamageByEntityEvent event) { + if(event.getEntity() == null) return; + if(event.getDamager() == null) return; + if(!(event.getEntity() instanceof Player)) return; + if(!(event.getDamager() instanceof Player)) return; + + Player entity = (Player) event.getEntity(); + Player damager = (Player) event.getDamager(); + + if(!DuelsAPI.isPlayerInDuel(entity)) return; + if(!DuelsAPI.isPlayerInDuel(damager)) return; + + DuelPlayer duelPlayerEntity = DuelsAPI.getDuelPlayerByPlayer(entity); + DuelPlayer duelPlayerDamager = DuelsAPI.getDuelPlayerByPlayer(damager); + + assert duelPlayerEntity != null; + duelPlayerEntity.setDamageReceived(duelPlayerEntity.getDamageReceived() + event.getFinalDamage()); + duelPlayerEntity.setHitsReceived(duelPlayerEntity.getHitsReceived() + 1); + + assert duelPlayerDamager != null; + duelPlayerDamager.setDamageSent(duelPlayerDamager.getDamageSent() + event.getFinalDamage()); + duelPlayerDamager.setHitsSent(duelPlayerDamager.getHitsSent() + 1); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void noTeamDamage(EntityDamageByEntityEvent event) { + if(event.getEntity() == null) return; + if(event.getDamager() == null) return; + if(!(event.getEntity() instanceof Player)) return; + if(!(event.getDamager() instanceof Player)) return; + Player entity = (Player) event.getEntity(); + Player damager = (Player) event.getDamager(); + if(!DuelsAPI.isPlayerInDuel(entity)) return; + if(!DuelsAPI.isPlayerInDuel(damager)) return; + if(DuelsAPI.getDuelTeamByPlayer(entity) == DuelsAPI.getDuelTeamByPlayer(damager)) { + event.setCancelled(true); + } + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerDeathListener.java b/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerDeathListener.java new file mode 100644 index 0000000..714565d --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerDeathListener.java @@ -0,0 +1,29 @@ +package net.crankedpvp.duels.listeners; + +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.DuelsPlugin; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; + +public class PlayerDeathListener implements Listener { + + private final DuelsPlugin plugin; + public PlayerDeathListener(DuelsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void deathEvent(PlayerDeathEvent event) { + if(event.getEntity() == null) return; + final Player player = event.getEntity(); + if(!DuelsAPI.isPlayerInDuel(player)) return; + if(!DuelsAPI.getDuelMatchByPlayer(player).getDuelStatus().isActive()) return; + event.getDrops().clear(); + this.plugin.getDuelPlayerHandler().handle(player); + + } + +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerDisconnectListener.java b/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerDisconnectListener.java new file mode 100644 index 0000000..5a1701d --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerDisconnectListener.java @@ -0,0 +1,35 @@ +package net.crankedpvp.duels.listeners; + +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.DuelsPlugin; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class PlayerDisconnectListener implements Listener { + + private DuelsPlugin plugin; + public PlayerDisconnectListener(DuelsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void disconnectPlayer(PlayerQuitEvent event) { + if(event.getPlayer() == null) return; + Player player = event.getPlayer(); + if(!DuelsAPI.isPlayerInDuel(player)) return; + if(!DuelsAPI.getDuelMatchByPlayer(player).getDuelStatus().isActive()) return; + this.plugin.getDuelPlayerHandler().handle(player); + } + + @EventHandler + public void kickPlayer(PlayerKickEvent event) { + if(event.getPlayer() == null) return; + Player player = event.getPlayer(); + if(!DuelsAPI.isPlayerInDuel(player)) return; + if(!DuelsAPI.getDuelMatchByPlayer(player).getDuelStatus().isActive()) return; + this.plugin.getDuelPlayerHandler().handle(player); + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerListener.java b/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerListener.java new file mode 100644 index 0000000..31799f0 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/listeners/PlayerListener.java @@ -0,0 +1,100 @@ +package net.crankedpvp.duels.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.struct.DuelManager; +import net.crankedpvp.duels.struct.DuelStatus; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.event.player.*; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Locale; + +public class PlayerListener implements Listener { + + @EventHandler + public void onJoin(PlayerJoinEvent event) { + if(event.getPlayer() == null) return; + if(!event.getPlayer().getWorld().getName().contains("tournament")) return; + event.getPlayer().teleport(Bukkit.getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + event.getPlayer().getInventory().setArmorContents(new ItemStack[4]); + event.getPlayer().getInventory().clear(); + } + + + @EventHandler + public void onPickUpWhileInGame(PlayerPickupItemEvent event) { + if (!DuelsAPI.isPlayerInDuel(event.getPlayer())) return; + if(!DuelsAPI.getDuelMatchByPlayer(event.getPlayer()).getDuelStatus().isActive()) return; + event.setCancelled(true); + } + + @EventHandler + public void onBlockPlaceWhileInGame(BlockPlaceEvent event) { + if (!DuelsAPI.isParticipant(event.getPlayer())) return; + if(!DuelsAPI.getDuelMatchByPlayer(event.getPlayer()).getDuelStatus().isActive()) return; + event.setCancelled(true); + } + + @EventHandler + public void onBlockBreakWhileInGame(BlockBreakEvent event) { + if (!DuelsAPI.isParticipant(event.getPlayer())) return; + if(!DuelsAPI.getDuelMatchByPlayer(event.getPlayer()).getDuelStatus().isActive()) return; + event.setCancelled(true); + } + + @EventHandler + public void onDropWhileInGame(PlayerDropItemEvent event) { + if (!DuelsAPI.isParticipant(event.getPlayer())) return; + if(!DuelsAPI.getDuelMatchByPlayer(event.getPlayer()).getDuelStatus().isActive()) return; + event.setCancelled(true); + } + + + @EventHandler(priority = EventPriority.LOWEST) + public void onCommandWhileInGame(PlayerCommandPreprocessEvent event) { + if (!DuelsAPI.isParticipant(event.getPlayer())) return; + if(DuelsAPI.getDuelMatchByPlayer(event.getPlayer()).getDuelStatus() != DuelStatus.ACTIVE) return; + String command = event.getMessage().replace("/", "").toLowerCase(Locale.ROOT); + + if (Arrays.stream(this.excludedBlockedCommands).noneMatch(command::startsWith)) { + event.setCancelled(true); + Player player = event.getPlayer(); + player.sendMessage(CC.translate(DuelManager.prefix + "&cYou cannot run /" + event.getMessage() + " while in a duel")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + } + } + + @EventHandler + public void onOpenInventory(InventoryOpenEvent event) { + if(event.getPlayer() == null) return; + if(event.getInventory() == null) return; + if(event.getInventory() == event.getPlayer().getInventory()) return; + if(!(event.getPlayer() instanceof Player)) return; + if(!DuelsAPI.isParticipant((Player) event.getPlayer())) return; + if(!DuelsAPI.getDuelMatchByPlayer((Player) event.getPlayer()).getDuelStatus().isActive()) return; + event.setCancelled(true); + event.getPlayer().sendMessage(CC.translate("&cYou cannot open external inventories while in a duel match")); + } + + private final String[] excludedBlockedCommands = {"f c", "bless", "feed", "msg", "r "}; + + @EventHandler + public void teleport(PlayerTeleportEvent event) { + if(DuelsAPI.isParticipant(event.getPlayer())) { + if(!(event.getCause() == PlayerTeleportEvent.TeleportCause.ENDER_PEARL || event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) { + event.setCancelled(true); + event.getPlayer().sendMessage(CC.translate(DuelManager.prefix + "&cYou cannot teleport during a duel match")); + } + } + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/ArenaRegister.java b/Duels/src/main/java/net/crankedpvp/duels/struct/ArenaRegister.java new file mode 100644 index 0000000..9c06a16 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/ArenaRegister.java @@ -0,0 +1,22 @@ +package net.crankedpvp.duels.struct; + +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.struct.NewSaveLoadManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class ArenaRegister extends NewSaveLoadManager { + public ArenaRegister(JavaPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "arenas", DuelArena.class); + } + + @Override + public String serialize(String string) { + return string; + } + + @Override + public String deserialize(String string) { + return string; + } + +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/DuelArena.java b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelArena.java new file mode 100644 index 0000000..ab31d08 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelArena.java @@ -0,0 +1,34 @@ +package net.crankedpvp.duels.struct; + + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.storageutils.struct.NewKeyToSave; +import org.bukkit.Location; + +@Getter @AllArgsConstructor @Setter +public class DuelArena implements NewKeyToSave { + + private String arenaName; + private Location spawnPointOne; + private Location spawnPointTwo; + private boolean active; + + public DuelArena(String arenaName, Location spawnPointOne, Location spawnPointTwo) { + this.arenaName = arenaName; + this.spawnPointOne = spawnPointOne; + this.spawnPointTwo = spawnPointTwo; + this.active = false; + } + + @Override + public String getKey() { + return this.arenaName; + } + + @Override + public void setKey(String name) { + this.arenaName = name; + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/DuelManager.java b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelManager.java new file mode 100644 index 0000000..708ed83 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelManager.java @@ -0,0 +1,46 @@ +package net.crankedpvp.duels.struct; + +import lombok.Getter; +import net.crankedpvp.duels.DuelsPlugin; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class DuelManager { + + private final DuelsPlugin plugin; + public DuelManager(DuelsPlugin plugin) { + this.plugin = plugin; + this.duelMatches = new ArrayList<>(); + } + + public static String prefix = "&e&lDuels &8➥ "; + + @Getter + private final List duelMatches; + + public List getActiveDuelMatches() { + return duelMatches.stream().filter(duelMatch -> duelMatch.getDuelStatus().isActive()).collect(Collectors.toList()); + } + + public List getRequestedDuelMatches() { + return duelMatches.stream().filter(duelMatch -> !duelMatch.getDuelStatus().isActive()).collect(Collectors.toList()); + } + + public DuelMatch getDuelMatchFromTeam(DuelTeam duelTeam) { + for(DuelMatch duelMatch : this.duelMatches) { + if(duelMatch.getTeamTwo().getDuelTeamLeader() == duelTeam.getDuelTeamLeader()) return duelMatch; + if(duelMatch.getTeamOne().getDuelTeamLeader() == duelTeam.getDuelTeamLeader()) return duelMatch; + } + return null; + } + + public boolean hasBeenDueled(DuelTeam duelTeam) { + for(DuelMatch duelMatch : this.duelMatches) { + if(duelMatch.getTeamTwo().getDuelTeamLeader() == duelTeam.getDuelTeamLeader()) return true; + if(duelMatch.getTeamOne().getDuelTeamLeader() == duelTeam.getDuelTeamLeader()) return true; + } + return false; + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/DuelMatch.java b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelMatch.java new file mode 100644 index 0000000..f0e6add --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelMatch.java @@ -0,0 +1,58 @@ +package net.crankedpvp.duels.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.function.Predicate; + +@Getter @AllArgsConstructor +public class DuelMatch { + + private DuelTeam teamOne; + private DuelTeam teamTwo; + private EnumMap settings; + private DuelArena duelArena; + + @Setter + private DuelStatus duelStatus; + + public DuelTeam getSendingTeam() { + return this.teamOne; + } + + public DuelTeam getReceivingTeam() { + return this.teamTwo; + } + + public List getAllDuelPlayers() { + List players = new ArrayList<>(); + players.addAll(this.teamOne.getDuelPlayersAsDuelPlayers()); + players.addAll(this.teamTwo.getDuelPlayersAsDuelPlayers()); + return players; + } + + public List getAllPlayers() { + List players = new ArrayList<>(); + players.addAll(this.teamOne.getDuelPlayersAsPlayers()); + players.addAll(this.teamTwo.getDuelPlayersAsPlayers()); + return players; + } + + public void sendToAllPlayers(String message) { + this.getAllPlayers().forEach(player -> player.sendMessage(CC.translate(message))); + } + + public boolean checkConditionOnMembers(Predicate condition) { + for(Player player : this.getAllPlayers()) { + if(!condition.test(player)) return false; + } + return true; + } + +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/DuelPlayer.java b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelPlayer.java new file mode 100644 index 0000000..0db1107 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelPlayer.java @@ -0,0 +1,50 @@ +package net.crankedpvp.duels.struct; + +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +@Getter @Setter +public class DuelPlayer { + + private UUID playerUUID; + private boolean dead; + + private ItemStack[] initialInventory; + private ItemStack helmet; + private ItemStack chestplate; + private ItemStack leggings; + private ItemStack boots; + + private double damageReceived; + private double damageSent; + private int hitsReceived; + private int hitsSent; + + public DuelPlayer(UUID uuid, ItemStack[] initialInventory, ItemStack helmet, ItemStack chestplate, ItemStack leggings, ItemStack boots) { + this.playerUUID = uuid; + this.initialInventory = initialInventory; + this.helmet = helmet; + this.chestplate = chestplate; + this.leggings = leggings; + this.boots = boots; + this.dead = false; + + this.damageReceived = 0; + this.damageSent = 0; + this.hitsReceived = 0; + this.hitsSent = 0; + } + + public double getAverageDamage() { + return damageSent / hitsSent; + } + + public Player getPlayer() { + return Bukkit.getPlayer(this.playerUUID); + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/DuelPlayerHandler.java b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelPlayerHandler.java new file mode 100644 index 0000000..40fb87a --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelPlayerHandler.java @@ -0,0 +1,127 @@ +package net.crankedpvp.duels.struct; + +import net.crankedpvp.collect.CollectPlugin; +import net.crankedpvp.collect.struct.CollectCategory; +import net.crankedpvp.collect.struct.CollectType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.duels.DuelsAPI; +import net.crankedpvp.duels.DuelsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class DuelPlayerHandler { + + private final DecimalFormat decimalFormat = new DecimalFormat("##.00"); + + private final DuelsPlugin plugin; + public DuelPlayerHandler(DuelsPlugin plugin) { + this.plugin = plugin; + } + + public void handle(Player player) { + final DuelMatch duelMatch = DuelsAPI.getDuelMatchByPlayer(player); + DuelsAPI.setPlayerDeadInDuel(player); + + List winners = new ArrayList<>(); + List losers = new ArrayList<>(); + + if(duelMatch.getTeamOne().getRemainingPlayersAmount() <= 0 || duelMatch.getTeamTwo().getRemainingPlayersAmount() <= 0) { + DuelTeam winningTeam = null; + DuelTeam losingTeam = null; + if(duelMatch.getTeamOne().getRemainingPlayersAmount() <= 0) { + losers.addAll(duelMatch.getTeamOne().getDuelPlayersAsPlayers()); + winners.addAll(duelMatch.getTeamTwo().getDuelPlayersAsPlayers()); + winningTeam = duelMatch.getTeamTwo(); + losingTeam = duelMatch.getTeamOne(); + } else if(duelMatch.getTeamTwo().getRemainingPlayersAmount() <= 0) { + winners.addAll(duelMatch.getTeamOne().getDuelPlayersAsPlayers()); + losers.addAll(duelMatch.getTeamTwo().getDuelPlayersAsPlayers()); + winningTeam = duelMatch.getTeamOne(); + losingTeam = duelMatch.getTeamTwo(); + } + assert winningTeam != null; + sendDuelEndMessage(winningTeam, losingTeam); + winners.forEach(winningPlayer -> { + this.finalise(winningPlayer); + if(duelMatch.getSettings().get(DuelSetting.RISK_INVENTORY)) { + winningPlayer.sendMessage(CC.translate(DuelManager.prefix + "&aYour team leader has received ALL duel rewards &7(/collect)")); + } else { + winningPlayer.sendMessage(CC.translate(DuelManager.prefix + "&aYour duel items have been stored in your /collect")); + } + giveOwnItemsBack(winningPlayer); + }); + + if(duelMatch.getSettings().get(DuelSetting.RISK_INVENTORY)) { + giveItemsToWinner(winningTeam.getDuelTeamLeader(), losingTeam); + } else { + losers.forEach(loser -> { + this.giveOwnItemsBack(loser); + loser.sendMessage(CC.translate(DuelManager.prefix + "&aYour duel items have been stored in your /collect")); + }); + } + duelMatch.setDuelStatus(DuelStatus.INACTIVE); + this.plugin.getDuelManager().getDuelMatches().remove(duelMatch); + } + + this.finalise(player); + player.sendMessage(CC.translate(DuelManager.prefix + "&cYou have been eliminated from the duel")); + } + + private void sendDuelEndMessage(DuelTeam winners, DuelTeam losers) { + List players = new ArrayList<>(); + players.addAll(winners.getDuelPlayersAsPlayers()); + players.addAll(losers.getDuelPlayersAsPlayers()); + + Bukkit.broadcastMessage(CC.translate(DuelManager.prefix + "&4" + winners.getDuelTeamLeader().getName() + "'s &cTeam has beaten &4" + losers.getDuelTeamLeader().getName() + "'s &cteam in a duel")); + + players.forEach(player -> { + double overAllDmgWinners = 0; + double overAllDmgLosers = 0; + int overAllHitsWinners = 0; + int overAllHitsLosers = 0; + player.sendMessage(CC.translate("&4&lWinning Team &8➥ &c" + winners.getDuelPlayersAsPlayers().stream().map(HumanEntity::getName).collect(Collectors.joining(", ")))); + for(DuelPlayer duelPlayer : winners.getDuelPlayersAsDuelPlayers()) { + overAllDmgWinners += duelPlayer.getDamageSent(); + overAllHitsWinners += duelPlayer.getHitsSent(); + } + player.sendMessage(CC.translate("&cOutgoing Hits: &f" + this.decimalFormat.format(overAllHitsWinners))); + player.sendMessage(CC.translate("&cOutgoing Damage: &f" + this.decimalFormat.format(overAllDmgWinners))); + player.sendMessage(""); + player.sendMessage(CC.translate("&4&lLosing Team &8➥ &c" + losers.getDuelPlayersAsPlayers().stream().map(HumanEntity::getName).collect(Collectors.joining(", ")))); + for(DuelPlayer duelPlayer : losers.getDuelPlayersAsDuelPlayers()) { + overAllDmgLosers += duelPlayer.getDamageSent(); + overAllHitsLosers += duelPlayer.getHitsSent(); + } + player.sendMessage(CC.translate("&cOutgoing Hits: &f" + this.decimalFormat.format(overAllHitsLosers))); + player.sendMessage(CC.translate("&cOutgoing Damage: &f" + this.decimalFormat.format(overAllDmgLosers))); + }); + } + + private void finalise(Player player) { + player.teleport(Bukkit.getWorld("world").getSpawnLocation()); + InventoryUtils.clearInventory(player); + SoundUtils.tryPlayErrorSound(player); + } + + private void giveItemsToWinner(Player player, DuelTeam losingTeam) { + List items = DuelsAPI.getItemsFromTeam(losingTeam); + if(items.size() == 0) return; + CollectPlugin.getInstance().getCollectManager().getOrCreate(player.getUniqueId().toString()).add(new CollectCategory(CollectType.DUEL, items.toArray(new ItemStack[items.size() - 1]), CC.RedB + losingTeam.getDuelTeamLeader().getName() + "'s Duel Teams Items", System.currentTimeMillis())); + } + + private void giveOwnItemsBack(Player player) { + List items = DuelsAPI.getItemsFromPlayer(Objects.requireNonNull(DuelsAPI.getDuelPlayerByPlayer(player))); + if(items.size() == 0) return; + CollectPlugin.getInstance().getCollectManager().getOrCreate(player.getUniqueId().toString()).add(new CollectCategory(CollectType.DUEL, items.toArray(new ItemStack[items.size() - 1]), CC.RedB + "Your duel items", System.currentTimeMillis())); + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/DuelSetting.java b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelSetting.java new file mode 100644 index 0000000..831beb0 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelSetting.java @@ -0,0 +1,35 @@ +package net.crankedpvp.duels.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.List; + +@Getter @AllArgsConstructor +public enum DuelSetting { + + RISK_INVENTORY("Risk Inventory", Material.PAPER, "&b&lRisk Inventory", Arrays.asList("&7Should your inventory be at", "&7risk in this duel?", "", "{enabled}"), false), + ENDER_PEARLS("Ender Pearls", Material.ENDER_PEARL, "&5&lEnder Pearls", Arrays.asList("&7Should ender pearls be", "&7allowed in this duel?", "", "{enabled}"), true), + GOLDEN_APPLES("Golden Apples", Material.GOLDEN_APPLE, "&e&lGolden Apples", Arrays.asList("&7Should golden apples be", "&7allowed in this duel?", "", "{enabled}"), true), + DEATH_CERTIFICATES("Death Certificates", Material.PAPER, "&c&lDeath Certificates", Arrays.asList("&7Should the winner receive", "&7a death certificate from the", "&7loser in this duel?", "", "{enabled}"), true), + POTIONS("Potions", Material.POTION, "&a&lPotions", Arrays.asList("&7Should potions be allowed", "&7in this duel?", "", "{enabled}"), true), + FIX("Fix", Material.GOLD_HELMET, "&d&lFix", Arrays.asList("&7Should players be allowed to", "&7/fix their armor during the duel?", "", "{enabled}"), true), + PETS("Pets", Material.SKULL_ITEM, "&e&lPets", Arrays.asList("&7Should players be allowed to", "&7bring inventory pets to the duel", "", "{enabled}"), true), + FLY("Fly", Material.FEATHER, "&b&lFly", Arrays.asList("&7Should players be allowed to", "&7fly during the duel", "", "{enabled}"), false), + FOOD_LOSS("Food Loss", Material.COOKED_BEEF, "&e&lFood Loss", Arrays.asList("&7Should players lose hunger", "&7during the duel?", "", "{enabled}"), false), + HEALING("Healing", Material.GHAST_TEAR, "&c&lHealing", Arrays.asList("&7Should players be able to", "&7heal during the duel?", "", "{enabled}"), true), + SOUL_GEMS("Soul Gems", Material.EMERALD, "&c&lSoul Gems", Arrays.asList("&7Should players be able to use", "&7soul gems during the duel?", "", "{enabled}"), true), + BOWS("Bows", Material.BOW, "&6&lBows", Arrays.asList("&7Should players be able to use", "&7bows during the duel?", "", "{enabled}"), true), + ARMOR("Armor", Material.DIAMOND_CHESTPLATE, "&b&lArmor", Arrays.asList("&7Should players be able to use", "&7armor during the duel?", "", "{enabled}"), true), + WEAPONS("Weapons", Material.DIAMOND_SWORD, "&b&lWeapons", Arrays.asList("&7Should players be able to use", "&7weapons during the duel?", "", "{enabled}"), true), + ; + + private final String settingName; + private final Material displayMaterial; + private final String displayName; + private final List displayLore; + private final boolean defaultSetting; + +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/DuelStatus.java b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelStatus.java new file mode 100644 index 0000000..947cb8b --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelStatus.java @@ -0,0 +1,9 @@ +package net.crankedpvp.duels.struct; + +public enum DuelStatus { + ACTIVE, SELECTING, CONFIRMING, INACTIVE, CANCELLED; + + public boolean isActive() { + return this == ACTIVE; + } +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/struct/DuelTeam.java b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelTeam.java new file mode 100644 index 0000000..06dd6b2 --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/struct/DuelTeam.java @@ -0,0 +1,59 @@ +package net.crankedpvp.duels.struct; + +import lombok.AllArgsConstructor; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +@AllArgsConstructor +public class DuelTeam { + + private DuelPlayer duelLeader; + private List duelTeamMembers; + + public List getDuelPlayersAsDuelPlayers() { + List players = this.duelTeamMembers.size() > 0 ? new ArrayList<>(this.duelTeamMembers) : new ArrayList<>(); + players.add(duelLeader); + return players; + } + + public int getAmountOfPlayers() { + return this.getDuelPlayersAsDuelPlayers().size(); + } + + public Player getDuelTeamLeader() { + return Bukkit.getPlayer(this.duelLeader.getPlayerUUID()); + } + + public List getDuelPlayersAsPlayers() { + return getDuelPlayersAsDuelPlayers().stream().map(duelPlayer -> Bukkit.getPlayer(duelPlayer.getPlayerUUID())).collect(Collectors.toList()); + } + + public List getDuelPlayersAsPlayerUUIDs() { + return getDuelPlayersAsDuelPlayers().stream().map(DuelPlayer::getPlayerUUID).collect(Collectors.toList()); + } + + public int getRemainingPlayersAmount() { + return (int) getDuelPlayersAsDuelPlayers().stream().filter(duelPlayer -> !duelPlayer.isDead()).count(); + } + + public DuelPlayer getDuelPlayerFromPlayer(Player player) { + for(DuelPlayer duelPlayer : getDuelPlayersAsDuelPlayers()) { + if(duelPlayer.getPlayerUUID().equals(player.getUniqueId())) return duelPlayer; + } + return null; + } + + public boolean checkConditionOnMembers(Predicate condition) { + for(Player player : this.getDuelPlayersAsPlayers()) { + if(!condition.test(player)) return false; + } + return true; + } + +} diff --git a/Duels/src/main/java/net/crankedpvp/duels/utils/InventorySettings.java b/Duels/src/main/java/net/crankedpvp/duels/utils/InventorySettings.java new file mode 100644 index 0000000..b70228f --- /dev/null +++ b/Duels/src/main/java/net/crankedpvp/duels/utils/InventorySettings.java @@ -0,0 +1,112 @@ +package net.crankedpvp.duels.utils; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedpets.CrankedPetsAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.duels.struct.DuelManager; +import net.crankedpvp.duels.struct.DuelSetting; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.EnumMap; + +public class InventorySettings { + + public static void applyInventorySettings(Player player, EnumMap currentSettings) { + if(!currentSettings.get(DuelSetting.POTIONS)) + checkPotions(player); + + if(!currentSettings.get(DuelSetting.ENDER_PEARLS)) + checkEnderPearls(player); + + if(!currentSettings.get(DuelSetting.GOLDEN_APPLES)) + checkGoldenApples(player); + + if(!currentSettings.get(DuelSetting.BOWS)) + checkBows(player); + + if(!currentSettings.get(DuelSetting.PETS)) + checkPets(player); + + if(!currentSettings.get(DuelSetting.SOUL_GEMS)) + checkSoulGems(player); + + if(!currentSettings.get(DuelSetting.ARMOR)) + checkArmor(player); + + if(!currentSettings.get(DuelSetting.WEAPONS)) + checkWeapons(player); + } + + private static void checkPotions(Player player) { + if(!player.getInventory().contains(Material.POTION)) return; + player.getInventory().remove(Material.POTION); + player.sendMessage(CC.translate(DuelManager.prefix + "&cPotion(s) were removed from your inventory due to duel settings")); + } + + private static void checkEnderPearls(Player player) { + if(!player.getInventory().contains(Material.ENDER_PEARL)) return; + player.getInventory().remove(Material.ENDER_PEARL); + player.sendMessage(CC.translate(DuelManager.prefix + "&cEnder Pearl(s) were removed from your inventory due to duel settings")); + } + + private static void checkGoldenApples(Player player) { + if(!player.getInventory().contains(Material.GOLDEN_APPLE)) return; + player.getInventory().remove(Material.GOLDEN_APPLE); + player.sendMessage(CC.translate(DuelManager.prefix + "&cGolden Apple(s) were removed from your inventory due to duel settings")); + } + + private static void checkPets(Player player) { + if(!player.getInventory().contains(Material.SKULL_ITEM)) return; + for(int i = 0; i < player.getInventory().getContents().length; i++) { + ItemStack itemStack = player.getInventory().getItem(i); + if(itemStack.getType() == Material.SKULL_ITEM) { + if(CrankedPetsAPI.isPet(itemStack)) player.getInventory().remove(itemStack); + } + } + player.sendMessage(CC.translate(DuelManager.prefix + "&cPet(s) were removed from your inventory due to duel settings")); + } + + private static void checkArmor(Player player) { + boolean msg = false; + for(int i = 0; i < player.getInventory().getContents().length; i++) { + ItemStack itemStack = player.getInventory().getItem(i); + if(ItemUtils.isArmor(itemStack)) { + msg = true; + player.getInventory().remove(itemStack); + } + } + if(msg) player.sendMessage(CC.translate(DuelManager.prefix + "&cArmor has been removed from your inventory due to duel settings")); + } + + private static void checkWeapons(Player player) { + boolean msg = false; + for(int i = 0; i < player.getInventory().getContents().length; i++) { + ItemStack itemStack = player.getInventory().getItem(i); + if(ItemUtils.isWeapon(itemStack)) { + msg = true; + player.getInventory().remove(itemStack); + } + } + if(msg) player.sendMessage(CC.translate(DuelManager.prefix + "&cWeapon(s) were removed from your inventory due to duel settings")); + } + + private static void checkSoulGems(Player player) { + if(!player.getInventory().contains(Material.EMERALD)) return; + for(int i = 0; i < player.getInventory().getContents().length; i++) { + ItemStack itemStack = player.getInventory().getItem(i); + if(itemStack.getType() == Material.EMERALD) { + if(CrankedEnchantsAPI.isSoulGem(itemStack)) player.getInventory().remove(itemStack); + } + } + player.sendMessage(CC.translate(DuelManager.prefix + "&cSoul Gem(s) were removed from your inventory due to duel settings")); + } + + private static void checkBows(Player player) { + if(!player.getInventory().contains(Material.BOW)) return; + player.getInventory().remove(Material.BOW); + player.sendMessage(CC.translate(DuelManager.prefix + "&cBow(s) were removed from your inventory due to duel settings")); + } +} diff --git a/Duels/src/main/resources/plugin.yml b/Duels/src/main/resources/plugin.yml new file mode 100644 index 0000000..7e3f102 --- /dev/null +++ b/Duels/src/main/resources/plugin.yml @@ -0,0 +1,12 @@ +name: CrankedDuels +main: net.crankedpvp.duels.DuelsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedCollect + - StorageUtil + - CrankedPets + - CrankedEnchants + diff --git a/Enchants/pom.xml b/Enchants/pom.xml new file mode 100644 index 0000000..564b028 --- /dev/null +++ b/Enchants/pom.xml @@ -0,0 +1,71 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Enchants + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + com.massivecraft + Factions + + + net.crankedpvp + Masks + + + net.crankedpvp + Pets + + + net.crankedpvp + Bosses + + + net.crankedpvp + Armor + + + net.crankedpvp + StarItems + + + net.crankedpvp + AdminWeapons + + + coreprotect + coreprotect + 1.0 + system + ${project.basedir}/../.lib/CoreProtect_2.12.0.jar + + + net.crankedpvp + Staff + + + com.earth2me.essentials + EssentialsX + 1.0 + system + ${project.basedir}/../.lib/EssentialsX-2.19.7.jar + + + \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/CrankedEnchants.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/CrankedEnchants.java new file mode 100644 index 0000000..2620092 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/CrankedEnchants.java @@ -0,0 +1,105 @@ +package net.crankedpvp.crankedenchants; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedenchants.commands.*; +import net.crankedpvp.crankedenchants.language.LanguageHandler; +import net.crankedpvp.crankedenchants.listeners.*; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.config.ConfigManager; +import net.crankedpvp.crankedenchants.struct.config.EnchantConfigManager; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.OrbBuilder; +import net.crankedpvp.crankedenchants.struct.souls.SoulManager; +import net.crankedpvp.crankedenchants.tasks.SoulDrainTask; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Locale; +import java.util.stream.Collectors; + +@Getter +public class CrankedEnchants extends JavaPlugin { + + @Getter + private static CrankedEnchants instance; + private EnchantRegister enchantRegister; + private CommandManager commandManager; + private EnchantConfigManager enchantConfigManager; + private SoulManager soulManager; + private LanguageHandler languageHandler; + private ConfigManager configManager; + + @Override + public void onEnable() { + instance = this; + + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + + this.soulManager = new SoulManager(); + + this.enchantRegister = new EnchantRegister(this); + this.enchantRegister.initialize(); + + this.configManager = new ConfigManager(this); + this.configManager.setupFiles(); + + this.commandManager = new CommandManager(this); + + this.registerListeners(); + + new SoulDrainTask(this).runTaskTimer(this, 0L, 10L); + + //So it runs after all plugins are loaded cause I register enchants in other plugins too + Bukkit.getScheduler().runTask(this, () -> { + this.enchantConfigManager = new EnchantConfigManager(this); + this.enchantConfigManager.setupFiles(); + + this.registerCommandParameters(); + this.registerCommandCompletion(); + + this.commandManager.register(new AdminEnchantsCommand(this), new EnchantsCommand(), new EnchanterCommand(), new ApplyCommand(), new SplitSoulsCommand(), new WithdrawSoulsCommand(), new DupeCommand(this)); + }); + } + + @Override + public void onDisable() { + instance = null; + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(Enchantment.class, argument -> { + Enchantment enchantment = this.enchantRegister.getEnchantmentFromID(String.valueOf(argument).toLowerCase(Locale.ROOT)); + return new TypeResult(enchantment, argument); + }); + + this.commandManager.getParameterHandler().register(EnchantTier.class, argument -> { + EnchantTier enchantTier = EnchantTier.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(enchantTier, argument); + }); + + this.commandManager.getParameterHandler().register(OrbBuilder.OrbType.class, argument -> { + OrbBuilder.OrbType orbType = OrbBuilder.OrbType.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(orbType, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#enchants", input -> this.enchantRegister.getEnchantments().stream().map(Enchantment::getID).collect(Collectors.toList())); + + } + + private void registerListeners() { + PluginManager pm = Bukkit.getPluginManager(); + pm.registerEvents(new BookListeners(this), this); + pm.registerEvents(new EnchantmentListener(), this); + pm.registerEvents(new ItemListener(this), this); + pm.registerEvents(new SoulListener(this), this); + pm.registerEvents(new ArmorSwapListener(this), this); + pm.registerEvents(new TinkererListeners(), this); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/CrankedEnchantsAPI.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/CrankedEnchantsAPI.java new file mode 100644 index 0000000..a81c4e6 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/CrankedEnchantsAPI.java @@ -0,0 +1,354 @@ +package net.crankedpvp.crankedenchants; + +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEquipEvent; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.EnchantmentCache; +import net.crankedpvp.crankedenchants.struct.cache.WeaponEnchantCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.NbtWrapper; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; +import java.util.Set; + +import static net.crankedpvp.crankedenchants.struct.NbtTags.ENCHANTS_TAG; + +public class CrankedEnchantsAPI { + + public static boolean isRandomEnchantBook(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.BOOK) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.BOOK_DATA_STRING); + } + + public static boolean itemHasEnchantment(ItemStack itemStack, @NotNull String enchantment) { + if (ItemUtils.isAirOrNull(itemStack)) return false; + return NbtWrapper.hasKeyInCompound(itemStack, ENCHANTS_TAG, enchantment); + } + + public static boolean itemHasEnchantment(ItemStack itemStack, @NotNull Enchantment enchantment) { + return itemHasEnchantment(itemStack, enchantment.getID()); + } + + public static int getEnchantmentLevelFromItem(@NotNull ItemStack itemStack, @NotNull String enchantment) { + return NbtWrapper.getIntegerFromCompound(itemStack, ENCHANTS_TAG, enchantment); + } + + public static int getEnchantmentLevelFromItem(@NotNull ItemStack itemStack, @NotNull Enchantment enchantment) { + return getEnchantmentLevelFromItem(itemStack, enchantment.getID()); + } + + public static EnchantTier getRandomEnchantBookTier(ItemStack itemStack) { + NBTItem nbtItem = new NBTItem(itemStack); + return EnchantTier.valueOf(nbtItem.getString(NbtTags.BOOK_TIER_DATA_STRING).toUpperCase(Locale.ROOT)); + } + + public static boolean isCustomItem(ItemStack itemStack) { + if (itemStack == null) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return (nbtItem.hasKey(NbtTags.DATA_STRING)); + } + + public static boolean isEnchantBook(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.BOOK) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.ENCHANT_BOOK_DATA_STRING); + } + + public static boolean isSoulTracker(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.PAPER) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.SOUL_TRACKER_DATA_STRING); + } + + public static boolean isSecretDust(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.FIREBALL) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.SECRET_DUST_DATA_STRING); + } + + public static boolean isEnchantmentOrb(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.EYE_OF_ENDER) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.ORB_DATA_STRING); + } + + public static boolean isSoulGem(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.EMERALD) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.SOUL_GEM_DATA_STRING); + } + + public static boolean isDust(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.SUGAR && itemStack.getType() != Material.GLOWSTONE_DUST) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.DUST_DATA_STRING); + } + + public static boolean isInfernalDust(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.REDSTONE) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.INFERNAL_DUST_DATA_STRING); + } + + public static boolean isBlackScroll(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.INK_SACK) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.BLACK_SCROLL_DATA_STRING); + } + + public static boolean isHeroicBlackScroll(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.INK_SACK) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.HEROIC_BLACK_SCROLL_DATA_STRING); + } + + public static boolean isOmniBlackScroll(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.INK_SACK) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.OMNI_BLACK_SCROLL_DATA_STRING); + } + public static boolean isWhiteScroll(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.EMPTY_MAP) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.WHITE_SCROLL_DATA_STRING); + } + + public static boolean isTransmogScroll(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.PAPER) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.TRANSMOG_SCROLL_DATA_STRING); + } + + public static boolean isRandomizationScroll(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.PAPER) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.RANDOMIZATION_SCROLL_DATA_STRING); + } + + public static boolean isSoulPearl(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.ENDER_PEARL) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.SOUL_PEARL_DATA_STRING); + } + + public static boolean isRenameTag(ItemStack itemStack) { + if (itemStack == null) return false; + if (itemStack.getType() != Material.NAME_TAG) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getString(NbtTags.DATA_STRING).equals(NbtTags.RENAME_TAG_DATA_STRING); + } + + public static Set getEnchantments(Player player) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.getEnchants(); + } + + public static void addEnchantmentToPlayer(Player player, Enchantment enchantment, int level) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + enchantmentCache.addEnchantment(enchantment, level); + } + + public static void removeEnchantmentFromPlayer(Player player, Enchantment enchantment, int level) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + enchantmentCache.removeEnchantment(enchantment, level); + } + + public static boolean hasEnchantment(Player player, Enchantment enchantment) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.hasEnchantment(enchantment); + } + + public static boolean hasEnchantment(Player player, String enchantmentID) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.hasEnchantment(enchantmentID); + } + + public static Integer getEnchantmentLevel(Player player, Enchantment enchantment) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.getEnchantInfo(enchantment).getLevel(); + } + + public static Integer getEnchantmentLevel(Player player, String enchantmentID) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.getEnchantInfo(enchantmentID).getLevel(); + } + + public static Integer getEnchantmentAmount(Player player, Enchantment enchantment) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.getEnchantInfo(enchantment).getAmount(); + } + + public static Integer getEnchantmentAmount(Player player, String enchantmentID) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.getEnchantInfo(enchantmentID).getAmount(); + } + + public static EnchantInfo getEnchantmentInfo(Player player, Enchantment enchantment) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.getEnchantInfo(enchantment); + } + + public static EnchantInfo getEnchantmentInfo(Player player, String enchantmentID) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + return enchantmentCache.getEnchantInfo(enchantmentID); + } + + private static EnchantmentCache getEnchantCache(Player player) { + EnchantmentCache enchantmentCache = (EnchantmentCache) CacheManager.getInstance().getCachedPlayer(player).getCache(NbtTags.ENCHANTMENT_CACHE_ID); + + if (enchantmentCache == null) { + enchantmentCache = (EnchantmentCache) CacheManager.getInstance().getCachedPlayer(player).registerCache(new EnchantmentCache()); + } + + return enchantmentCache; + } + + public static void clearEnchantsFromCache(Player player) { + EnchantmentCache enchantmentCache = getEnchantCache(player); + enchantmentCache.clearEnchantments(); + } + + public static void clearEnchantsFromCacheFromOneArmorItem(Player player, ItemStack itemStack) { + if (!ItemUtils.isArmor(itemStack)) return; + EnchantmentCache enchantmentCache = getEnchantCache(player); + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + enchantedItemBuilder.getEnchantments().forEach((enchantment, level) -> { + enchantmentCache.removeEnchantment(enchantment, level); + if (enchantment instanceof ArmorEquipEventEnchant) { + ArmorEquipEventEnchant equipEventEnchant = ((ArmorEquipEventEnchant) enchantment); + equipEventEnchant.runArmorUnEquipEvent(player, level); + } + }); + } + + public static void reprocEnchants(Player player) { + if (player == null || player.isDead()) return; + clearEnchantsFromCache(player); + PotionEffectUtils.clearPlayerEffects(player); + for (ItemStack itemStack : player.getInventory().getArmorContents()) { + if (!ItemUtils.isEnchantable(itemStack)) continue; + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + enchantedItemBuilder.getEnchantments().forEach((enchant, level) -> { + if (enchant instanceof ArmorEquipEventEnchant) { + EnchantProcEvent procEvent = new EnchantProcOnEquipEvent(player, enchant, level); + Bukkit.getPluginManager().callEvent(procEvent); + if(procEvent.isCancelled()) return; + ((ArmorEquipEventEnchant) enchant).runArmorEquipEvent(player, level); + } + addEnchantmentToPlayer(player, enchant, level); + }); + } + } + + public static void reprocEnchantsFromOneArmorItem(Player player, ItemStack itemStack) { + if (player == null || player.isDead()) return; + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + enchantedItemBuilder.getEnchantments().forEach((enchant, level) -> { + if (enchant instanceof ArmorEquipEventEnchant) { + EnchantProcEvent procEvent = new EnchantProcOnEquipEvent(player, enchant, level); + Bukkit.getPluginManager().callEvent(procEvent); + if(procEvent.isCancelled()) return; + ((ArmorEquipEventEnchant) enchant).runArmorEquipEvent(player, level); + } + addEnchantmentToPlayer(player, enchant, level); + }); + } + + public static WeaponEnchantCache getWeaponEnchantCache(Player player) { + WeaponEnchantCache enchantmentCache = (WeaponEnchantCache) CacheManager.getInstance().getCachedPlayer(player).getCache(NbtTags.WEAPON_ENCHANTMENT_CACHE_ID); + + if (enchantmentCache == null) { + enchantmentCache = (WeaponEnchantCache) CacheManager.getInstance().getCachedPlayer(player).registerCache(new WeaponEnchantCache()); + } + + return enchantmentCache; + } + + public static Set getWeaponEnchantments(Player player) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + return enchantmentCache.getEnchants(); + } + + public static void addWeaponEnchantmentToPlayer(Player player, Enchantment enchantment, int level) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + enchantmentCache.addEnchantment(enchantment, level); + } + + public static void removeEnchantmentFromPlayer(Player player, Enchantment enchantment) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + enchantmentCache.removeEnchantment(enchantment); + } + + public static boolean hasWeaponEnchantment(Player player, Enchantment enchantment) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + return enchantmentCache.hasEnchantment(enchantment); + } + + public static boolean hasWeaponEnchantment(Player player, String enchantmentID) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + return enchantmentCache.hasEnchantment(enchantmentID); + } + + public static Integer getWeaponEnchantmentLevel(Player player, Enchantment enchantment) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + return enchantmentCache.getEnchantLevel(enchantment); + } + + public static int getWeaponSlot(Player player) { + return getWeaponEnchantCache(player).getSwordSlot(); + } + + public static Integer getWeaponEnchantmentLevel(Player player, String enchantmentID) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + return enchantmentCache.getEnchantLevel(enchantmentID); + } + + public static void cacheWeaponEnchants(Player player, EnchantedItemBuilder enchantedItemBuilder) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + enchantmentCache.clearEnchantments(); + enchantedItemBuilder.getEnchantments().forEach(enchantmentCache::addEnchantment); + enchantmentCache.setSwordSlot(player.getInventory().getHeldItemSlot()); + enchantmentCache.updateTime(); + } + + public static void cacheWeaponEnchants(Player player, ItemStack itemStack) { + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(player); + enchantmentCache.clearEnchantments(); + + for (String enchantID : NbtWrapper.getKeysFromCompound(itemStack, ENCHANTS_TAG)) { + enchantmentCache.addEnchantment(enchantID, NbtWrapper.getIntegerFromCompound(itemStack, ENCHANTS_TAG, enchantID)); + } + + enchantmentCache.setSwordSlot(player.getInventory().getHeldItemSlot()); + enchantmentCache.updateTime(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/AdminEnchantsCommand.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/AdminEnchantsCommand.java new file mode 100644 index 0000000..e7fcbdf --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/AdminEnchantsCommand.java @@ -0,0 +1,473 @@ +package net.crankedpvp.crankedenchants.commands; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.inventories.EnchanterUI; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.language.LanguageHandler; +import net.crankedpvp.crankedenchants.struct.cache.SoulTrackerCache; +import net.crankedpvp.crankedenchants.struct.config.ConfigManager; +import net.crankedpvp.crankedenchants.struct.config.EnchantConfigManager; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.*; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import me.mattstudios.mf.annotations.*; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; +import xyz.xenondevs.particle.data.texture.BlockTexture; + +@Command("ce") +public class AdminEnchantsCommand extends CommandBase { + + private final ConfigManager configManager; + private final EnchantConfigManager enchantConfigManager; + private final LanguageHandler languageHandler; + + public AdminEnchantsCommand(CrankedEnchants plugin) { + this.enchantConfigManager = plugin.getEnchantConfigManager(); + this.languageHandler = plugin.getLanguageHandler(); + this.configManager = plugin.getConfigManager(); + } + + @Default + public void mainCommand(CommandSender sender) { + if (sender instanceof Player) { + Player player = (Player) sender; + + if (player.hasPermission("cranked.admin")) { + Language.NE_COMMAND_HELP.send(sender); + return; + } + + EnchanterUI enchanterUI = new EnchanterUI(); + enchanterUI.getEnchantersUI().open(player); + return; + } + + Language.NE_COMMAND_HELP.send(sender); + } + + @SubCommand("book") + @WrongUsage("&cUsage: /ce book [player]") + @Permission("cranked.admin") + public void bookCommand(CommandSender sender, @Completion("#enchants") Enchantment enchantment, Integer level, @Completion("#players") @Optional Player player) { + + if (enchantment == null) { + Language.INVALID_ENCHANTMENT_NAME.send(sender); + return; + } + + if (level == null || level < 1 || level > enchantment.getMax()) { + Language.INVALID_ENCHANTMENT_LEVEL.send(sender, s -> s.replace("{max}", String.valueOf(enchantment.getMax()))); + return; + } + + ItemStack itemStack = new BookBuilder(enchantment, level) + .setSuccessRate(100) + .setDestroyRate(0) + .build(); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("dust") + @WrongUsage("&cUsage: /ce dust [player]") + @Permission("cranked.admin") + public void dustCommand(CommandSender sender, @Completion("#enum") EnchantTier tier, @Completion("#range:1-15") Integer percent, @Completion("#players") @Optional Player player) { + if (tier == null) { + return; + } + + ItemStack itemStack = new DustBuilder(tier, percent).build(); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("idust") + @WrongUsage("&cUsage: /ce idust [player]") + @Permission("cranked.admin") + public void infernalDustCommand(CommandSender sender, @Completion("#enum") EnchantTier tier, @Completion("#players") @Optional Player player) { + if (tier == null) { + return; + } + + ItemStack itemStack = new InfernalDustBuilder(tier).build(); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("omniblackscroll") + @Alias("obscroll") + @WrongUsage("&cUsage: /ce omniblackscroll [player]") + @Permission("cranked.admin") + public void omniBlackScrollCommand(CommandSender sender, @Completion("#range:1-100") Integer percent, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new OmniBlackScrollBuilder(percent).build(); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("blackscroll") + @Alias("bscroll") + @WrongUsage("&cUsage: /ce blackscroll [player]") + @Permission("cranked.admin") + public void blackScrollCommand(CommandSender sender, @Completion("#range:1-100") Integer percent, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new BlackScrollBuilder(percent).build(); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("heroicblackscroll") + @Alias({"hbscroll", "hblackscroll", "heroicbs", "heroicbscroll"}) + @WrongUsage("&cUsage: /ce heroicbs [player]") + @Permission("cranked.admin") + public void heroicBlackScrollCommand(CommandSender sender, @Completion("#range:1-100") Integer percent, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new HeroicBlackScrollBuilder(percent).build(); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("soulgem") + @Alias("sgem") + @WrongUsage("&cUsage: /ce soulgem [player]") + @Permission("cranked.admin") + public void soulGemCommand(CommandSender sender, Integer souls, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new SoulGemBuilder(souls).build(); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("orb") + @Alias("eorb") + @WrongUsage("&cUsage: /ce orb [player]") + @Permission("cranked.admin") + public void orbCommand(CommandSender sender, @Completion("#range:10-16") Integer slots, @Completion("#range:1-100") Integer success, @Completion("#enum") OrbBuilder.OrbType type, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new OrbBuilder(type, slots, success).build(); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("whitescroll") + @Alias("wscroll") + @WrongUsage("&cUsage: /ce whitescroll [player]") + @Permission("cranked.admin") + public void whiteScrollCommand(CommandSender sender, @Completion("#range:1-64") Integer amount, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new WhiteScrollBuilder().build(); + + itemStack.setAmount(amount); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("transmogscroll") + @Alias({"tscroll", "transmog"}) + @WrongUsage("&cUsage: /ce transmogscroll [player]") + @Permission("cranked.admin") + public void transmogScrollCommand(CommandSender sender, @Completion("#range:1-64") Integer amount, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new TransmogScrollBuilder().build(); + + itemStack.setAmount(amount); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("randomizationscroll") + @Alias({"rscroll"}) + @WrongUsage("&cUsage: /ce randomizationscroll [player]") + @Permission("cranked.admin") + public void randomizationScrollCommand(CommandSender sender, @Completion("#range:1-64") Integer amount, @Completion("#enum") EnchantTier tier, @Completion("#players") @Optional Player player) { + if (tier == null) { + return; + } + + ItemStack itemStack = new RandomizationScrollBuilder(tier).build(); + + itemStack.setAmount(amount); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("nametag") + @Alias("renametag") + @WrongUsage("&cUsage: /ce nametag [player]") + @Permission("cranked.admin") + public void renameTagCommand(CommandSender sender, @Completion("#range:1-64") Integer amount, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new ItemRenameTagBuilder().build(); + + itemStack.setAmount(amount); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("soulpearl") + @WrongUsage("&cUsage: /ce soulpearl [player]") + @Permission("cranked.admin") + public void soulPearlCommand(CommandSender sender, @Completion("#range:1-64") Integer amount, @Completion("#players") @Optional Player player) { + ItemStack itemStack = new SoulPearlBuilder().build(); + + itemStack.setAmount(amount); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("soultracker") + @WrongUsage("&cUsage: /ce soultracker [player]") + @Permission("cranked.admin") + public void soulTrackerCommand(CommandSender sender, @Completion("#range:1-64") Integer amount, @Completion("#enum") EnchantTier tier, @Completion("#players") @Optional Player player) { + if (tier == null) { + return; + } + + ItemStack itemStack = new SoulTrackerBuilder(tier).build(); + + itemStack.setAmount(amount); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("rbook") + @Alias({"randombook", "randbook"}) + @WrongUsage("&cUsage: /ce rbook [player]") + @Permission("cranked.admin") + public void randomBookCommand(CommandSender sender, @Completion("#enum") EnchantTier tier, Integer amount, @Optional Player player) { + + if (amount == null) { + amount = 1; + } + + if (tier == null) { + return; + } + + ItemStack itemStack = EnchantTier.createMysteryBook(tier, amount); + + if (player != null) { + player.getInventory().addItem(itemStack); + return; + } + + if (sender instanceof Player) { + InventoryUtils.giveItemToPlayer(((Player) sender), itemStack); + } + } + + @SubCommand("enchant") + @Alias({"addenchant", "addenchantment"}) + @WrongUsage("&cUsage: /ce enchant [level]") + @Permission("cranked.admin") + public void enchantCommand(Player sender, @Completion("#enchants") Enchantment enchantment, @Optional Integer level) { + + if (enchantment == null) { + Language.INVALID_ENCHANTMENT_NAME.send(sender); + return; + } + + if (level == null) { + level = enchantment.getMax(); + } + + if (level < 1) { // || level > enchantment.getMax() + Language.INVALID_ENCHANTMENT_LEVEL.send(sender, s -> s.replace("{max}", String.valueOf(enchantment.getMax()))); + return; + } + + if (sender.getItemInHand() == null || sender.getItemInHand().getType() == Material.AIR) { + Language.EMPTY_HAND.send(sender); + return; + } + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(sender.getItemInHand()); + + if (enchantedItemBuilder.hasEnchantment(enchantment)) { + enchantedItemBuilder.removeEnchantment(enchantment); + } + + enchantedItemBuilder.addEnchantment(enchantment, level); + + sender.setItemInHand(enchantedItemBuilder.build()); + sender.updateInventory(); + } + + @SubCommand("unenchant") + @Alias({"removeenchant", "removeenchantment", "deenchant"}) + @WrongUsage("&cUsage: /ce unenchant ") + @Permission("cranked.admin") + public void unenchantCommand(Player sender, @Completion("#enchants") Enchantment enchantment) { + + if (sender.getItemInHand() == null || sender.getItemInHand().getType() == Material.AIR) { + Language.EMPTY_HAND.send(sender); + return; + } + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(sender.getItemInHand()); + + if (!enchantedItemBuilder.hasEnchantment(enchantment)) { + return; + } + + enchantedItemBuilder.removeEnchantment(enchantment); + + sender.setItemInHand(enchantedItemBuilder.build()); + sender.updateInventory(); + } + + @SubCommand("reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + this.configManager.reloadFiles(); + this.languageHandler.load(); + this.enchantConfigManager.reloadFiles(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } + + @SubCommand("debug") + @Permission("cranked.admin") + public void debugCommand(Player sender) { + for (Enchantment enchantment : CrankedEnchantsAPI.getEnchantments(sender)) { + System.out.println(enchantment.getName()); + } + } + + @SubCommand("particle") + @Permission("cranked.admin") + public void particleCommand(Player sender) { + ParticleBuilder particle1 = new ParticleBuilder(ParticleEffect.BLOCK_DUST) + .setParticleData(new BlockTexture(Material.DIAMOND_BLOCK)) + .setAmount(100) + .setOffsetY(1) + .setSpeed(0.15f); + + particle1.setLocation(sender.getLocation()).display(sender); + + SoulTrackerCache soulTrackerCache = CacheUtils.getSoulTrackerCache(sender); + + if (soulTrackerCache.isOnHarvestCooldown(sender)) { + Language.SOUL_HARVEST_COOLDOWN.send(sender, str -> str + .replace("{player}", sender.getName()) + .replace("{time}", TimeUtils.formatSeconds(soulTrackerCache.getSecondsLeftOnHarvestCooldown(sender))) + ); + return; + } + + soulTrackerCache.addHarvestCooldown(sender); + } + + @SubCommand("test") + @Permission("cranked.admin") + public void testCommand(Player sender) { + ItemStack itemStack = sender.getItemInHand(); + + System.out.println(CrankedEnchantsAPI.itemHasEnchantment(itemStack, "gears")); + System.out.println("level: " + CrankedEnchantsAPI.getEnchantmentLevelFromItem(itemStack, "gears")); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/ApplyCommand.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/ApplyCommand.java new file mode 100644 index 0000000..cf97873 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/ApplyCommand.java @@ -0,0 +1,18 @@ +package net.crankedpvp.crankedenchants.commands; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.entity.Player; + +@Command("apply") +@Alias("reapply") +public class ApplyCommand extends CommandBase { + + @Default + public void mainCommand(Player sender) { + CrankedEnchantsAPI.reprocEnchants(sender); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/DupeCommand.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/DupeCommand.java new file mode 100644 index 0000000..cfaac4b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/DupeCommand.java @@ -0,0 +1,68 @@ +package net.crankedpvp.crankedenchants.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.BookBuilder; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; + +@Command("dupe") +@Alias("duplicate") +public class DupeCommand extends CommandBase { + + private final List blockedTiers = Arrays.asList( + EnchantTier.HEROIC, EnchantTier.CURSED, EnchantTier.UNDERWORLD + ); + + private CrankedEnchants plugin; + public DupeCommand(CrankedEnchants plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + ItemStack itemStack = player.getItemInHand(); + if(!(CrankedEnchantsAPI.isRandomEnchantBook(itemStack) || CrankedEnchantsAPI.isEnchantBook(itemStack))) { + Language.CANNOT_DUPE_ITEM.send(player); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + return; + } + + EnchantTier enchantTier = null; + + if (CrankedEnchantsAPI.isRandomEnchantBook(itemStack)) { + enchantTier = CrankedEnchantsAPI.getRandomEnchantBookTier(itemStack); + } + + if (CrankedEnchantsAPI.isEnchantBook(itemStack)) { + enchantTier = new BookBuilder(itemStack).getBookEnchantment().getTier(); + } + + if (blockedTiers.contains(enchantTier)) { + Language.CANNOT_DUPE_TIER.send(player); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + return; + } + + if (itemStack.getAmount() >= 64) { + Language.CANNOT_DUPE_MORE.send(player); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + return; + } + + itemStack.setAmount(64); + player.setItemInHand(itemStack); + Language.DUPED_ITEM.send(player); + player.playSound(player.getLocation(), Sound.LEVEL_UP, 2.0f, 2.0f); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/EnchanterCommand.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/EnchanterCommand.java new file mode 100644 index 0000000..2721127 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/EnchanterCommand.java @@ -0,0 +1,17 @@ +package net.crankedpvp.crankedenchants.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedenchants.inventories.EnchanterUI; +import org.bukkit.entity.Player; + +@Command("enchanter") +public class EnchanterCommand extends CommandBase { + + @Default + public void mainCommand(Player sender) { + EnchanterUI enchanterUI = new EnchanterUI(); + enchanterUI.getEnchantersUI().open(sender); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/EnchantsCommand.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/EnchantsCommand.java new file mode 100644 index 0000000..971d846 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/EnchantsCommand.java @@ -0,0 +1,18 @@ +package net.crankedpvp.crankedenchants.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedenchants.inventories.MainEnchantsUI; +import org.bukkit.entity.Player; + +@Command("enchants") +@Alias("enchantslist") +public class EnchantsCommand extends CommandBase { + @Default + public void mainCommand(Player sender) { + MainEnchantsUI enchantsUI = new MainEnchantsUI(); + enchantsUI.getEnchantsGUI().open(sender); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/SplitSoulsCommand.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/SplitSoulsCommand.java new file mode 100644 index 0000000..75c9d0f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/SplitSoulsCommand.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedenchants.commands; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.items.SoulGemBuilder; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.entity.Player; + +@Command("splitsouls") +public class SplitSoulsCommand extends CommandBase { + + @Default + public void mainCommand(Player sender, Integer amount) { + if (!CrankedEnchantsAPI.isSoulGem(sender.getItemInHand())) return; + if (amount <= 0) return; + + if (!InventoryUtils.hasAvailableSlot(sender)) { + Language.FULL_INVENTORY.send(sender); + return; + } + + CrankedEnchants.getInstance().getSoulManager().disableSoulMode(sender); + + SoulGemBuilder soulGemBuilder = new SoulGemBuilder(sender.getItemInHand()); + + if (soulGemBuilder.getSouls() <= amount) return; + + soulGemBuilder.removeSouls(amount); + sender.setItemInHand(soulGemBuilder.build()); + sender.getInventory().addItem(new SoulGemBuilder(amount).build()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/WithdrawSoulsCommand.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/WithdrawSoulsCommand.java new file mode 100644 index 0000000..3df9b45 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/commands/WithdrawSoulsCommand.java @@ -0,0 +1,46 @@ +package net.crankedpvp.crankedenchants.commands; + +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.struct.items.SoulGemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +@Command("withdrawsouls") +public class WithdrawSoulsCommand extends CommandBase { + + @Default + public void mainCommand(Player sender, Integer amount) { + if (!ItemUtils.isWeapon(sender.getItemInHand())) return; + if (amount <= 0) return; + + if (!InventoryUtils.hasAvailableSlot(sender)) { + Language.FULL_INVENTORY.send(sender); + return; + } + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(sender.getItemInHand()); + + if (!enchantedItemBuilder.hasSoulTrackerAlreadyApplied()) { + Language.DOESNT_HAVE_SOUL_TRACKER.send(sender); + return; + } + + if (enchantedItemBuilder.getHarvestedSouls() < amount) { + Language.OUT_OF_SOULS.send(sender); + sender.playSound(sender.getLocation(), Sound.ITEM_BREAK, 0.7f, 0.4f); + return; + } + + enchantedItemBuilder.removeHarvestedSouls(amount); + enchantedItemBuilder.updateSoulsHarvested(); + sender.setItemInHand(enchantedItemBuilder.build()); + + sender.getInventory().addItem(new SoulGemBuilder(amount * enchantedItemBuilder.getSoulTrackerTier().getSoulValue()).build()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/Abyss.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/Abyss.java new file mode 100644 index 0000000..d810ff5 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/Abyss.java @@ -0,0 +1,76 @@ +package net.crankedpvp.crankedenchants.enchantments.cursed; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.AbyssCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class Abyss extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.075; + @ConfigValue + private int durationInSeconds = 3; + public Abyss() { + super("Abyss", EnchantTier.CURSED, false, 4, GearType.BOOTS, "When at low health, you have a chance", "to freeze enemies in a 6 block radius", "for a short amount of time."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance * enchantInfo.getLevel() && victim.getHealth() < enchantInfo.getLevel()*2) { + for (Player enemy : PVPUtils.getNearbyEnemyPlayersExceptPlayer(victim, 6)) { + if(StarItemsAPI.playerHasStarItem(enemy, "void")) { + enemy.sendMessage(CC.translate("&d&lVoid &8" + Arrow.arrow() + " &7You have bypassed &4" + victim.getName() + "'s &7abyss enchantment")); + } if(StarItemsAPI.playerHasStarItem(enemy, "santasbeard")) { + enemy.sendMessage(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7You have bypassed &4" + victim.getName() + "'s &7abyss enchantment")); + } else { + AbyssCache abyssCache = CacheUtils.getAbyssCache(enemy); + abyssCache.applyAbyssEffect(enemy, enchantInfo.getLevel()); + enemy.sendMessage(CC.translate("&4&lAbyss &8" + Arrow.arrow() + " &7You have been frozen by &4" + victim.getName() + "'s &7abyss enchantment")); + + } + } + super.registerCooldown(victim, 45); + } + } + + @EventHandler + public void onPlayerLeaveWhileAbyss(PlayerQuitEvent event) { + AbyssCache abyssCache = CacheUtils.getAbyssCache(event.getPlayer()); + if (abyssCache.isAffected()) { + abyssCache.removeAbyssEffect(event.getPlayer()); + } + } + + @EventHandler + public void onPlayerLeaveWhileAbyss(PlayerKickEvent event) { + AbyssCache abyssCache = CacheUtils.getAbyssCache(event.getPlayer()); + if (abyssCache.isAffected()) { + abyssCache.removeAbyssEffect(event.getPlayer()); + } + } + + @EventHandler + public void onPlayerDeathWhileAbyss(PlayerDeathEvent event) { + AbyssCache abyssCache = CacheUtils.getAbyssCache(event.getEntity()); + if (abyssCache.isAffected()) { + abyssCache.removeAbyssEffect(event.getEntity()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/AntiCactus.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/AntiCactus.java new file mode 100644 index 0000000..45aef1c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/AntiCactus.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedenchants.enchantments.cursed; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +public class AntiCactus extends ArmorIncomingPVPDamageEventEnchant { + + + public AntiCactus() { + super("Anti Cactus", EnchantTier.CURSED, false, 1, GearType.LEGGINGS, "Immune to enemy cactus enchant effect"); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/AntiLife.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/AntiLife.java new file mode 100644 index 0000000..7ffddc6 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/AntiLife.java @@ -0,0 +1,26 @@ +package net.crankedpvp.crankedenchants.enchantments.cursed; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorPlayerDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageEvent; + +public class AntiLife extends ArmorPlayerDamageEventEnchant { + @ConfigValue + private double procChance = 0.025; + + public AntiLife() { + super("Anti Life", EnchantTier.CURSED, false, 10, GearType.HELMET, "Wither and poison damage has a chance", "to heal the wearer"); + } + + @Override + public void runOnDamage(EntityDamageEvent event, Player player, EnchantInfo enchantInfo) { + if ((event.getCause() == EntityDamageEvent.DamageCause.POISON || event.getCause() == EntityDamageEvent.DamageCause.WITHER) && Math.random() < procChance*enchantInfo.getLevel()) { + event.setCancelled(true); + super.getDamageHandler().healEntity(player, Math.max(1, enchantInfo.getLevel()/2), "Anti Life"); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/Fat.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/Fat.java new file mode 100644 index 0000000..15f6d4e --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/cursed/Fat.java @@ -0,0 +1,32 @@ +package net.crankedpvp.crankedenchants.enchantments.cursed; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +public class Fat extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.075; + + public Fat() { + super("Fat", EnchantTier.CURSED, false, 6, GearType.CHESTPLATE, "Gain a chance to receive absorption", "hearts when under health boost hearts"); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if ((Math.random() < procChance * enchantInfo.getLevel()) && (victim.getMaxHealth() > 20) && (victim.getHealth() < 20)) { + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.ABSORPTION, enchantInfo.getLevel(),"FatEnchant", enchantInfo.getLevel()); + super.registerCooldown(victim, 75); + } + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/AntiGravity.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/AntiGravity.java new file mode 100644 index 0000000..8316609 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/AntiGravity.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class AntiGravity extends ArmorEquipEventEnchant { + + public AntiGravity() { + super("Anti Gravity", EnchantTier.ELITE, false, 1, GearType.BOOTS, "Added extreme jump boost when equipped."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.JUMP, level+2, "AntiGravityEnchant"); + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Jump Boost") + .replace("{effect-level}", RomanNumeral.convertToRoman(level+2)) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level+2)) + ); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + PotionEffectUtils.removePotionEffect(player, "AntiGravityEnchant"); + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Jump Boost") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level+2)) + ); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Blind.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Blind.java new file mode 100644 index 0000000..4958c96 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Blind.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.BowEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.BlindingEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Blind extends BowEventEnchant implements BlindingEnchant { + + @ConfigValue + private double procChance = 0.03; + + public Blind() { + super("Blind", EnchantTier.ELITE, 3, GearType.BOW, "Chance of causing blindness", "when attacking."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, Player victim, Player attacker, Arrow arrow, EnchantedItemBuilder enchantedItemBuilder) { + if (victim.hasPotionEffect(PotionEffectType.BLINDNESS)) return; + if (Math.random() <= procChance * enchantedItemBuilder.getEnchantmentLevel(this)) + victim.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, enchantedItemBuilder.getEnchantmentLevel(this) * 20, 0, true)); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Cactus.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Cactus.java new file mode 100644 index 0000000..d1879f9 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Cactus.java @@ -0,0 +1,42 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.RageStacksCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Silenceable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import org.bukkit.Effect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Cactus extends ArmorIncomingPVPDamageEventEnchant implements Silenceable { + + public Cactus() { + super("Cactus", EnchantTier.ELITE, false, 2, GearType.ARMOR, "Injures your attacker but does not", "affect your durability."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (!(attacker instanceof Player)) return; + Player attackerPlayer = ((Player) attacker); + + if (CrankedEnchantsAPI.hasEnchantment(attackerPlayer, "anticactus")) return; + if (CrankedMasksAPI.hasMaskEquipped(attackerPlayer, "coyote")) return; + + Location particleSpawnLocation = victim.getLocation(); + particleSpawnLocation.setY(particleSpawnLocation.getY() + 1); + attackerPlayer.playEffect(particleSpawnLocation, Effect.STEP_SOUND, Material.CACTUS); + + RageStacksCache attackerRageStack = CacheUtils.getRageStackCache(attackerPlayer); + if (attackerRageStack.getRageStack() > 0) { + attackerRageStack.resetRageStack(); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Demonforged.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Demonforged.java new file mode 100644 index 0000000..18cd041 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Demonforged.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +public class Demonforged extends WeaponDamageEventEnchant { + + public Demonforged() { + super("Demonforged", EnchantTier.ELITE, 4, GearType.SWORD, "Increases durability loss on your enemy's armor."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + Player playerVictim = ((Player) victim); + + for (ItemStack itemStack : playerVictim.getInventory().getArmorContents()) { + if (!ItemUtils.isArmor(itemStack)) continue; + itemStack.setDurability((short) (itemStack.getDurability() + 1)); + } + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Entangle.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Entangle.java new file mode 100644 index 0000000..735cb07 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Entangle.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.events.SlownessEnchantProcEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.BowEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Entangle extends BowEventEnchant { + + @ConfigValue + private double procChance = 0.005; + + public Entangle() { + super("Entangle", EnchantTier.ELITE, 4, GearType.BOW, "Chance to immobilize your target when", "they are hit."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, Player victim, Player attacker, Arrow arrow, EnchantedItemBuilder enchantedItemBuilder) { + if (Math.random() < procChance * enchantedItemBuilder.getEnchantmentLevel(this)) { + + SlownessEnchantProcEvent slownessEnchantProcEvent = new SlownessEnchantProcEvent(attacker, victim, this, enchantedItemBuilder.getEnchantmentLevel(this)); + Bukkit.getPluginManager().callEvent(slownessEnchantProcEvent); + + if (event.isCancelled()) return; + victim.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5, Integer.MAX_VALUE, true)); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Execute.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Execute.java new file mode 100644 index 0000000..a8f50c6 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Execute.java @@ -0,0 +1,60 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Effect; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; +import xyz.xenondevs.particle.data.texture.BlockTexture; + +public class Execute extends WeaponDamageEventEnchant implements Reloadable { + + @ConfigValue + public double procChance = 0.05; + @ConfigValue + public double damageBuff = 25; + @ConfigValue + private int requiredHealthForActivation = 14; + + public ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 50; + @ConfigValue + private double particleYoffset = 0.7; + @ConfigValue + private double particleSpeed = 0.1; + + public Execute() { + super("Execute", EnchantTier.ELITE, 7, GearType.SWORD, "Damage buff when your target is at low hp."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + if (victim.getHealth() > requiredHealthForActivation) return; + if (Math.random() < procChance * level) { + Player victimPlayer = (Player) victim; + super.getDamageHandler().increaseDamage(damageBuff, event, this.getName()); + victimPlayer.getWorld().playEffect(victimPlayer.getEyeLocation(), Effect.STEP_SOUND, Material.REDSTONE_WIRE); + this.particle.setLocation(victimPlayer.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victimPlayer, 20)); + } + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.BLOCK_DUST) + .setParticleData(new BlockTexture(Material.REDSTONE_WIRE)) + .setAmount(particleAmount) + .setOffsetY((float) particleYoffset) + .setSpeed((float) particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Frozen.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Frozen.java new file mode 100644 index 0000000..5ff6efe --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Frozen.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.events.SlownessEnchantProcEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SlownessEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Frozen extends ArmorIncomingPVPDamageEventEnchant implements SlownessEnchant { + + @ConfigValue + private double procChance = 0.003; + @ConfigValue + private int slownessLength = 5; + + public Frozen() { + super("Frozen", EnchantTier.ELITE, false, 3, GearType.ARMOR, "Can cause slowness to the attacker", "when attacked."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (Math.random() < procChance * enchantInfo.getLevel()) { + + SlownessEnchantProcEvent slownessEnchantProcEvent = new SlownessEnchantProcEvent(attacker, victim, this, enchantInfo.getLevel()); + Bukkit.getPluginManager().callEvent(slownessEnchantProcEvent); + + if (event.isCancelled()) return; + attacker.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, this.slownessLength, 0, true)); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Greatsword.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Greatsword.java new file mode 100644 index 0000000..2249ca4 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Greatsword.java @@ -0,0 +1,35 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Greatsword extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.4; + @ConfigValue + private double damageBuff = 20; + + public Greatsword() { + super("Greatsword", EnchantTier.ELITE, 5, GearType.SWORD, "Multiplies damage against players who are wielding a BOW", "at the time they are hit. "); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + Player playerVictim = ((Player) victim); + if (playerVictim.getItemInHand() == null) return; + if (playerVictim.getItemInHand().getType() != Material.BOW) return; + + if (Math.random() < procChance) { + super.getDamageHandler().increaseDamage(damageBuff, event, this.getName()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Hardened.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Hardened.java new file mode 100644 index 0000000..558ffd4 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Hardened.java @@ -0,0 +1,54 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +public class Hardened extends ArmorIncomingPVPDamageEventEnchant implements Reloadable { + + @ConfigValue + public double procChance = 0.2; + + public ParticleBuilder particle; + + @ConfigValue + public int particleAmount = 10; + @ConfigValue + public double particleYoffset = 0.3; + @ConfigValue + public double particleSpeed = 0.1; + + public Hardened() { + super("Hardened", EnchantTier.ELITE, false, 3, GearType.ARMOR, "Armor takes less durability damage."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (Math.random() < procChance * enchantInfo.getLevel()) { + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 30)); + for (ItemStack itemStack : victim.getInventory().getArmorContents()) { + if (!ItemUtils.isArmor(itemStack)) continue; + itemStack.setDurability((short) (itemStack.getDurability() - (enchantInfo.getLevel() + 2))); + } + } + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.SPELL_WITCH) + .setAmount(particleAmount) + .setOffsetY((float) particleYoffset) + .setSpeed((float) particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Haste.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Haste.java new file mode 100644 index 0000000..020610d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Haste.java @@ -0,0 +1,21 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.BlockBreakEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Haste extends BlockBreakEventEnchant { + + public Haste() { + super("Haste", EnchantTier.ELITE, 3, GearType.PICKAXE, "allows you to swing your tools faster."); + } + + @Override + public void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder) { + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 100, enchantedItemBuilder.getEnchantmentLevel(this) - 1, true)); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Paralyze.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Paralyze.java new file mode 100644 index 0000000..c797757 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Paralyze.java @@ -0,0 +1,48 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.events.SlownessEnchantProcEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SlownessEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Paralyze extends WeaponDamageEventEnchant implements SlownessEnchant { + + @ConfigValue + private double procChance = 0.05; + + @ConfigValue + private int slownessLength = 5; + + @ConfigValue + private int miningFatigueLength = 5; + + public Paralyze() { + super("Paralyze", EnchantTier.ELITE, 4, GearType.SWORD, "Gives lightning effect and a chance for slowness and slow swinging.", "Also inflicts direct damage on proc."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + if (Math.random() < procChance) { + + SlownessEnchantProcEvent slownessEnchantProcEvent = new SlownessEnchantProcEvent(attacker, victim, this, level); + Bukkit.getPluginManager().callEvent(slownessEnchantProcEvent); + + if (event.isCancelled()) return; + Player playerVictim = ((Player) victim); + playerVictim.getLocation().getWorld().strikeLightningEffect(playerVictim.getLocation()); + playerVictim.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, this.slownessLength, level > 2 ? 1 : 0)); + if (level == 4) { + playerVictim.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, this.miningFatigueLength, 1)); + } + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Poison.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Poison.java new file mode 100644 index 0000000..d8f62c3 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Poison.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Poison extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.002; + + public Poison() { + super("Poison", EnchantTier.ELITE, 3, GearType.SWORD, "A chance of giving the poison effect. "); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance * level) { + victim.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5, level - 1), true); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Poisoned.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Poisoned.java new file mode 100644 index 0000000..b9a5518 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Poisoned.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Poisoned extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.003; + + public Poisoned() { + super("Poisoned", EnchantTier.ELITE, false, 4, GearType.ARMOR, " Chance to give poison to your attacker."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (Math.random() < procChance * enchantInfo.getLevel()) { + attacker.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5, enchantInfo.getLevel() - 1), true); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Pummel.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Pummel.java new file mode 100644 index 0000000..2f8d173 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Pummel.java @@ -0,0 +1,58 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.events.SlownessEnchantProcEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SlownessEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Pummel extends WeaponDamageEventEnchant implements SlownessEnchant { + + @ConfigValue + private double procChance = 0.08; + @ConfigValue + private double range = 7.0; + @ConfigValue + private int slownessLevel = 1; + @ConfigValue + private int cooldown = 30; + + public Pummel() { + super("Pummel", EnchantTier.ELITE, 3, GearType.AXE, "Chance to slow nearby enemy players", "for a short period of time."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (super.isOnCooldown(attacker)) return; + if (Math.random() < procChance) { + SlownessEnchantProcEvent slownessEnchantProcEvent = new SlownessEnchantProcEvent(attacker, victim, this, level); + Bukkit.getPluginManager().callEvent(slownessEnchantProcEvent); + + if (event.isCancelled()) return; + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(attacker); + attacker.getNearbyEntities(range, range, range).forEach(entity -> { + if (!(entity instanceof Player)) return; + Player nearbyPlayer = (Player) entity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) return; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtLeast(Relation.TRUCE)) return; + nearbyPlayer.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, (level + 2) * 20, slownessLevel, true)); + }); + super.registerCooldown(attacker, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Reforged.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Reforged.java new file mode 100644 index 0000000..b561c10 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Reforged.java @@ -0,0 +1,45 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +public class Reforged extends WeaponDamageEventEnchant { + + public Reforged() { + super("Reforged", EnchantTier.ELITE,10, GearType.WEAPONS_AND_TOOLS, "Protects durability, items will take longer to break."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + ItemStack itemStack = attacker.getItemInHand(); + itemStack.setDurability((short) (itemStack.getDurability() - 2)); + attacker.setItemInHand(itemStack); + } + + + @EventHandler + public void blockBreakEvent(BlockBreakEvent event) { + if (event.isCancelled()) return; + + ItemStack itemStack = event.getPlayer().getItemInHand(); + + if (itemStack == null) return; + if (!this.getType().getItems().contains(itemStack.getType())) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + + itemStack.setDurability((short) (itemStack.getDurability() - 10)); + event.getPlayer().setItemInHand(itemStack); + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/RepairGuard.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/RepairGuard.java new file mode 100644 index 0000000..a61794c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/RepairGuard.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class RepairGuard extends ArmorEquipEventEnchant { + + @ConfigValue + private int cooldown = 60; + @ConfigValue + private int duration = 8; + + public RepairGuard() { + super("Repair Guard", EnchantTier.ELITE, false, 3, GearType.ARMOR, "Whenever you remove a low durability piece of armor to repair it,", "ou will get up to 10 absorption hearts (depending on level)", "while you are fixing it."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + if (super.isOnCooldown(player)) return; + player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, duration * 20, level + 1), true); + super.registerCooldown(player, cooldown); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/RocketEscape.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/RocketEscape.java new file mode 100644 index 0000000..d199f1d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/RocketEscape.java @@ -0,0 +1,101 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; +import xyz.xenondevs.particle.data.texture.BlockTexture; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class RocketEscape extends ArmorIncomingPVPDamageEventEnchant implements Reloadable { + + @ConfigValue + private double procChance = 0.2; + @ConfigValue + private int cooldown = 150; + @ConfigValue + private List message = Arrays.asList("&r ", "&a&l(!) &ayour Roecket Escape boots have activated, recover while they last!", "&r "); + + private ParticleBuilder particle; + @ConfigValue + private int particleAmount = 50; + @ConfigValue + private double particleYoffset = 0.7; + @ConfigValue + private double particleSpeed = 0.05; + + private final List noFallDamage; + + public RocketEscape() { + super("Rocket Escape", EnchantTier.ELITE, false, 3, GearType.BOOTS, "Chance to blast off into the air", "at low health."); + this.noFallDamage = new ArrayList<>(); + this.reloadValues(); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (victim.getHealth() - event.getFinalDamage() > 2) return; + if (super.isOnCooldown(victim)) return; + + if (Math.random() < this.procChance * enchantInfo.getLevel()) { + super.getDamageHandler().cancelDamage(event, this.getName()); + victim.setVelocity(new Vector(0, (enchantInfo.getLevel() + 2) * 3, 0)); + victim.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 20 * (enchantInfo.getLevel() + 2), 19, true, false)); + super.registerCooldown(victim, this.cooldown); + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 30)); + super.sendMessage(victim, this.message); + this.noFallDamage.add(victim); + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), () -> this.noFallDamage.remove(victim), 160L); + } + } + + @EventHandler + public void onFallDamageAfterRocketEscape(EntityDamageEvent event) { + if (event.getCause() != EntityDamageEvent.DamageCause.FALL) return; + if (event.getDamage() <= 0) return; + if (!(event.getEntity() instanceof Player)) return; + if (!this.noFallDamage.contains((Player) event.getEntity())) return; + event.setCancelled(true); + } + + @EventHandler + public void onLeaveWhileInNoFallDamageList(PlayerQuitEvent event) { + this.noFallDamage.remove(event.getPlayer()); + } + + @EventHandler + public void onLeaveWhileInNoFallDamageList(PlayerKickEvent event) { + this.noFallDamage.remove(event.getPlayer()); + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.BLOCK_DUST) + .setParticleData(new BlockTexture(Material.CACTUS)) + .setAmount(this.particleAmount) + .setOffsetY((float) this.particleYoffset) + .setSpeed((float) this.particleSpeed); + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Shockwave.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Shockwave.java new file mode 100644 index 0000000..f6bef25 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Shockwave.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Shockwave extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.004; + @ConfigValue + private int cooldown = 100; + @ConfigValue + private int range = 5; + + public Shockwave() { + super("Shockwave", EnchantTier.ELITE, false, 5, GearType.CHESTPLATE, "Chance of explosive knockback", "surrounding players when you are hit."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance * enchantInfo.getLevel()) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victim); + victim.getNearbyEntities(range, range, range).forEach(entity -> { + if (!(entity instanceof Player)) return; + Player nearbyPlayer = (Player) entity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) return; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtLeast(Relation.TRUCE)) return; + nearbyPlayer.setVelocity(victim.getLocation().toVector().subtract(nearbyPlayer.getLocation().toVector()).normalize().multiply(3)); + }); + victim.playSound(victim.getLocation(), Sound.FIREWORK_LAUNCH, 1.0f, 0.1f); + super.registerCooldown(victim, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/SmokeBomb.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/SmokeBomb.java new file mode 100644 index 0000000..12ac51d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/SmokeBomb.java @@ -0,0 +1,21 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class SmokeBomb extends ArmorIncomingPVPDamageEventEnchant { + + public SmokeBomb() { + super("Smoke Bomb", EnchantTier.ELITE, false, 8, GearType.HELMET, "When you are near death, you will spawn a smoke bomb", "to distract your enemies."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + //TODO: smoke bomb effect + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Solitude.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Solitude.java new file mode 100644 index 0000000..e322855 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Solitude.java @@ -0,0 +1,12 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; + +public class Solitude extends Enchantment { + + public Solitude() { + super("Solitude", EnchantTier.ELITE, false, 3, GearType.WEAPON, "Increases chance and length of the Silence enchantment", "procing on enemy players by up to 3X. "); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/SpiritLink.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/SpiritLink.java new file mode 100644 index 0000000..ab0643c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/SpiritLink.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class SpiritLink extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.004; + @ConfigValue + private int cooldown = 100; + @ConfigValue + private int range = 5; + @ConfigValue + private int healAmount = 5; + + public SpiritLink() { + super("Spirit Link", EnchantTier.ELITE, false, 5, GearType.CHESTPLATE, "Heals nearby faction/allies when you are damaged."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance * enchantInfo.getLevel()) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victim); + for (Entity nearbyEntity : victim.getNearbyEntities(range, range, range)) { + if (!(nearbyEntity instanceof Player)) continue; + Player nearbyPlayer = (Player) nearbyEntity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) continue; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) continue; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtMost(Relation.NEUTRAL)) continue; + super.getDamageHandler().healEntity(nearbyPlayer, healAmount, this.getName()); + } + super.registerCooldown(victim, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Springs.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Springs.java new file mode 100644 index 0000000..7a7b627 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Springs.java @@ -0,0 +1,41 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + + +public class Springs extends ArmorEquipEventEnchant { + + public Springs() { + super("Springs", EnchantTier.ELITE, false, 2, GearType.BOOTS, "Added extreme jump boost when equipped."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.JUMP, level, "SpringsEnchant"); + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Jump Boost") + .replace("{effect-level}", RomanNumeral.convertToRoman(level)) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + PotionEffectUtils.removePotionEffect(player, "SpringsEnchant"); + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Jump Boost") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Stormcaller.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Stormcaller.java new file mode 100644 index 0000000..af735c7 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Stormcaller.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Stormcaller extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.01; + + public Stormcaller() { + super("Stormcaller", EnchantTier.ELITE, false, 4, GearType.ARMOR, "Strikes lightning on attacking players. "); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (Math.random() < procChance * enchantInfo.getLevel()) { + attacker.getLocation().getWorld().strikeLightningEffect(attacker.getLocation()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Teleportation.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Teleportation.java new file mode 100644 index 0000000..b662392 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Teleportation.java @@ -0,0 +1,59 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; + +public class Teleportation extends Enchantment { + + public Teleportation() { + super("Teleportation", EnchantTier.ELITE, false, 5, GearType.BOW, "When an ally or faction member is hit", "with your arrow, you teleport to them."); + } + + @EventHandler + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { + if (!(event.getEntity() instanceof Player) || !(event.getDamager() instanceof Arrow)) return; + + Arrow arrow = (Arrow) event.getDamager(); + + if (!(arrow.getShooter() instanceof Player)) return; + + Player victim = (Player) event.getEntity(); + Player attacker = (Player) arrow.getShooter(); + + ItemStack itemStack = attacker.getItemInHand(); + + if (!ItemUtils.isEnchantable(itemStack)) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + + EnchantProcEvent procEvent = new EnchantProcOnEntityEvent(victim, attacker, this, enchantedItemBuilder.getEnchantmentLevel(this)); + Bukkit.getPluginManager().callEvent(procEvent); + + if (procEvent.isCancelled()) return; + + FPlayer fPlayerVictim = FPlayers.getInstance().getByPlayer(victim); + FPlayer fPlayerAttacker = FPlayers.getInstance().getByPlayer(attacker); + Relation relation = fPlayerVictim.getRelationTo(fPlayerAttacker); + + if (!relation.isAlly() && !relation.isTruce() && !relation.isMember()) return; + + attacker.teleport(victim.getLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Trap.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Trap.java new file mode 100644 index 0000000..6e7cec0 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Trap.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.events.SlownessEnchantProcEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SlownessEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Trap extends WeaponDamageEventEnchant implements SlownessEnchant { + + @ConfigValue + private double procChance = 0.003; + @ConfigValue + private int slownessAmplifier = 1; + @ConfigValue + private int slownessTime = 4; + + public Trap() { + super("Trap", EnchantTier.ELITE, 3, GearType.SWORD, "A chance of causing the slowness", "effect to your enemy."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance * level) { + SlownessEnchantProcEvent slownessEnchantProcEvent = new SlownessEnchantProcEvent(attacker, victim, this, level); + Bukkit.getPluginManager().callEvent(slownessEnchantProcEvent); + + if (event.isCancelled()) return; + + victim.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, this.slownessTime, this.slownessAmplifier, true)); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Trickster.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Trickster.java new file mode 100644 index 0000000..73ef61d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Trickster.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.HashSet; + +public class Trickster extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.0125; + + public Trickster() { + super("Trickster", EnchantTier.ELITE, false, 8, GearType.ARMOR, "When hit you have a chance to teleport directly behind", "your opponent and take them by surprise."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (Math.random() < procChance * enchantInfo.getLevel()) { + Location l1 = victim.getLocation().add(0.0, 1.0, 0.0); + Location l2 = victim.getTargetBlock((HashSet) null, 4).getLocation().add(0.0, 1.0, 0.0).setDirection(attacker.getLocation().getDirection()); + if (l2.getBlock().getType() == Material.AIR && l2.getBlock().getLocation().subtract(0.0, 1.0, 0.0).getBlock().getType() == Material.AIR) { + victim.teleport(l2, PlayerTeleportEvent.TeleportCause.PLUGIN); + victim.getWorld().playSound(l1, Sound.PORTAL_TRIGGER, 0.8f, 1.4f); + } + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/UndeadRuse.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/UndeadRuse.java new file mode 100644 index 0000000..ee82614 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/UndeadRuse.java @@ -0,0 +1,48 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class UndeadRuse extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.005; + @ConfigValue + private int cooldown = 200; + + public UndeadRuse() { + super("Undead Ruse", EnchantTier.ELITE, false, 10, GearType.ARMOR, "When hit you have a chance to spawn zombie hordes", "to distract and disorient your opponents."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (!(attacker instanceof Player)) return; +/* if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance * enchantInfo.getLevel()) { + Player target = (Player) attacker; + Entity entity = EntityTypes.spawnEntity(new UndeadRuseZombie(victim.getWorld(), victim, target), victim.getLocation()); + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), entity::remove, 400L); + super.registerCooldown(victim, cooldown); + }*/ + } + + /* + @EventHandler + public void onEntityTargetPlayer(EntityTargetLivingEntityEvent event) { + if (event.getEntityType() != EntityType.ZOMBIE) return; + if (!(event.getTarget() instanceof Player)) return; + if (!event.getEntity().hasMetadata("zombie-target")) return; + String uuid = String.valueOf(event.getEntity().getMetadata("zombie-target").get(0).asString()); + if (!uuid.equals(event.getTarget().getUniqueId().toString())) event.setCancelled(true); + } + + */ + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Vampire.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Vampire.java new file mode 100644 index 0000000..3745881 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Vampire.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Vampire extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.01; + @ConfigValue + private int cooldown = 20; + + public Vampire() { + super("Vampire", EnchantTier.ELITE, 3, GearType.SWORD, "A chance to heal you for up to 3hp", "a few seconds after you strike."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (super.isOnCooldown(attacker)) return; + + if (Math.random() < procChance * level) { + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), () -> { + super.getDamageHandler().healEntity(attacker, level, this.getName()); + }, 30L); + attacker.playSound(attacker.getLocation(), Sound.FIREWORK_LAUNCH, 0.75f, 2.0f); + super.registerCooldown(attacker, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Voodoo.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Voodoo.java new file mode 100644 index 0000000..012ca50 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Voodoo.java @@ -0,0 +1,59 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorOutgoingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +public class Voodoo extends ArmorOutgoingPVPDamageEventEnchant implements Reloadable { + + @ConfigValue + private double procChance = 0.01; + @ConfigValue + private int duration = 3; + @ConfigValue + private int weaknessAmplifier = 0; + + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 300; + @ConfigValue + private double particleYoffset = 1.8; + @ConfigValue + private double particleSpeed = 0.1; + + public Voodoo() { + super("Voodoo", EnchantTier.ELITE, false, 6, GearType.ARMOR, "Has a chance to deal weakness to", "your enemy."); + } + + @Override + public void runOutgoingDamageEvent(EntityDamageByEntityEvent event, Player attacker, LivingEntity victim, EnchantInfo enchantInfo) { + if (!(victim instanceof Player)) return; + if (event.getDamage() <= 0) return; + if (Math.random() < this.procChance * enchantInfo.getLevel()) { + Player victimPlayer = ((Player) victim); + victim.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, this.duration * 20, this.weaknessAmplifier, true)); + this.particle.setLocation(victimPlayer.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victimPlayer, 20)); + } + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.SPELL_MOB) + .setAmount(this.particleAmount) + .setOffsetY((float) this.particleYoffset) + .setSpeed((float) this.particleSpeed); + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Wither.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Wither.java new file mode 100644 index 0000000..f609321 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/elite/Wither.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedenchants.enchantments.elite; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Wither extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.008; + @ConfigValue + private int duration = 3; + @ConfigValue + private int witherAmplifier = 0; + + public Wither() { + super("Wither", EnchantTier.ELITE, false, 5, GearType.ARMOR, "A chance to give the wither effect."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (Math.random() < procChance * enchantInfo.getLevel()) { + attacker.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, duration * 20, witherAmplifier, true)); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/AtomicDetonate.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/AtomicDetonate.java new file mode 100644 index 0000000..b88abd1 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/AtomicDetonate.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.BlockBreakEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.utils.DetonateUtils; +import org.bukkit.Material; +import org.bukkit.event.block.BlockBreakEvent; + +import java.util.Arrays; +import java.util.List; + +public class AtomicDetonate extends BlockBreakEventEnchant implements HeroicEnchantment { + + public static List trenchBlackListedBlocks = Arrays.asList(Material.AIR, Material.BEDROCK, Material.MOB_SPAWNER, Material.WATER, + Material.LAVA, Material.STATIONARY_WATER, + Material.STATIONARY_LAVA, Material.SIGN, Material.GLOWSTONE, Material.LADDER, Material.WALL_SIGN, Material.SIGN_POST, Material.SPONGE, Material.CHEST, Material.ENDER_CHEST, + Material.TRAPPED_CHEST, Material.PISTON_BASE, Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE, Material.PISTON_STICKY_BASE, Material.DISPENSER, Material.ENDER_PORTAL_FRAME, + Material.ENDER_PORTAL, Material.PORTAL, Material.SUGAR_CANE, Material.SUGAR_CANE_BLOCK, Material.JUKEBOX, Material.ENCHANTMENT_TABLE); + + public AtomicDetonate() { + super("Atomic Detonate", EnchantTier.HEROIC, 2, GearType.TOOL, "Mine blocks in a very large radius."); + } + + @Override + public void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder) { + if (event.isCancelled()) return; + int level = enchantedItemBuilder.getEnchantmentLevel(this); + DetonateUtils.trenchEffect(event.getBlock(), 5 + level, event.getPlayer(), trenchBlackListedBlocks); + } + + @Override + public String getBaseEnchantment() { + return "detonate"; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/DeepBleed.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/DeepBleed.java new file mode 100644 index 0000000..6cef7b1 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/DeepBleed.java @@ -0,0 +1,82 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.enchantments.ultimate.Bleed; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.BleedStacksCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Effect; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class DeepBleed extends WeaponDamageEventEnchant implements HeroicEnchantment { + + private Bleed baseEnchantment; + + public DeepBleed() { + super("Deep Bleed", EnchantTier.HEROIC, 6, GearType.AXE, "Applies bleed stacks to enemies that", "decrease their movement speed."); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Bleed) this.baseEnchantment = (Bleed) enchantment; + + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if(!(victim instanceof Player)) return; + int deepWoundsLevel = CrankedEnchantsAPI.hasEnchantment(attacker, "deepwounds") ? CrankedEnchantsAPI.getEnchantmentLevel(attacker, "deepwounds") : 0; + if(Math.random() < (this.baseEnchantment.procChance * ((this.baseEnchantment.getMax() + level) + deepWoundsLevel))) { + Player victimPlayer = (Player) victim; + BleedStacksCache victimBleedStack = CacheUtils.getBleedStackCache(victimPlayer); + + if(victimBleedStack.getLastBleedStackTime() + 30000 < System.currentTimeMillis()) { + victimBleedStack.updateLastBleedStackTime(); + victimBleedStack.resetBleedStack(); + return; + } + + victim.addPotionEffect( + new PotionEffect(PotionEffectType.SLOW, + (victimBleedStack.getBleedStack() + 1) * 20, + Math.min(victimBleedStack.getBleedStack() - 1, 1)), + true + ); + + victim.getWorld().playEffect(victim.getEyeLocation(), Effect.STEP_SOUND, Material.REDSTONE_BLOCK); + victimBleedStack.incrementBleedStack(); + victimBleedStack.updateLastBleedStackTime(); + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victimPlayer); + for(Entity entity : victim.getNearbyEntities(7, 7, 7)) { + if(!(entity instanceof Player)) continue; + Player nearbyPlayer = (Player) entity; + if(nearbyPlayer.getGameMode() != GameMode.SURVIVAL) continue; + if(!PVPUtils.canPvPInRegion(nearbyPlayer)) continue; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if(fPlayer.getRelationTo(fPlayerNearby).isAtLeast(Relation.TRUCE)) continue; + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID("bloodlust"); + if(CrankedEnchantsAPI.hasEnchantment(nearbyPlayer, enchantment)) + super.getDamageHandler().healEntity(nearbyPlayer, 2, "Blood Lust"); + } + } + } + + @Override + public String getBaseEnchantment() { + return "bleed"; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/DivineEnlighted.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/DivineEnlighted.java new file mode 100644 index 0000000..bffade2 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/DivineEnlighted.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.enchantments.legendary.Enlighted; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class DivineEnlighted extends ArmorIncomingPVPDamageEventEnchant implements HeroicEnchantment { + + private Enlighted baseEnchantment; + + public DivineEnlighted() { + super("Divine Enlighted", EnchantTier.HEROIC, true, 3, GearType.ARMOR, "Has a chance to heal you", "while taking damage"); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Enlighted) this.baseEnchantment = (Enlighted) enchantment; + + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if (Math.random() < this.baseEnchantment.procChance * (baseEnchantment.getMax() + enchantInfo.getLevel())) { + super.getDamageHandler().healEntity(victim, enchantInfo.getAmount() * (1 + ((double) enchantInfo.getLevel() /10)), this.getName()); + super.registerCooldown(victim, this.baseEnchantment.cooldown); + } + } + + @Override + public String getBaseEnchantment() { + return "enlighted"; + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/EtherealDodge.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/EtherealDodge.java new file mode 100644 index 0000000..8dfb9f0 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/EtherealDodge.java @@ -0,0 +1,57 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.enchantments.ultimate.Dodge; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class EtherealDodge extends ArmorIncomingPVPDamageEventEnchant implements Reloadable, HeroicEnchantment { + + @ConfigValue + private String message = "&d&l** ETHEREAL DODGED **"; + + + private Dodge baseEnchantment; + + public EtherealDodge() { + super("Ethereal Dodge", EnchantTier.HEROIC, false, 1, GearType.ARMOR, "Has a chance to dodge physical", "attacks, increased chance when sneaking."); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Dodge) this.baseEnchantment = (Dodge) enchantment; + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (this.isOnCooldown(victim)) return; + + double chance = victim.isSneaking() ? this.baseEnchantment.procChanceWhenSneaking * (baseEnchantment.getMax() + 1) : this.baseEnchantment.procChance * (baseEnchantment.getMax() + 1); + + if (Math.random() < chance) { + super.getDamageHandler().cancelDamage(event, this.getName()); + super.sendMessage(victim, this.message); + victim.getWorld().playSound(victim.getLocation(), Sound.BAT_TAKEOFF, 1.0f, 0.75f); + this.baseEnchantment.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 30)); + super.registerCooldown(victim, this.baseEnchantment.cooldown); + } + } + + @Override + public String getBaseEnchantment() { + return "dodge"; + } + + @Override + public void reloadValues() { + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/GodlyOverload.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/GodlyOverload.java new file mode 100644 index 0000000..06e2e3f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/GodlyOverload.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.enchantments.legendary.Overload; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class GodlyOverload extends ArmorEquipEventEnchant implements HeroicEnchantment { + + private Overload baseEnchantment; + + public GodlyOverload() { + super("Godly Overload", EnchantTier.HEROIC, false, 1, GearType.ARMOR, "Increases the wearer's total health."); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Overload) this.baseEnchantment = (Overload) enchantment; + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.HEALTH_BOOST, baseEnchantment.getMax()+level, "GodlyOverloadEnchant"); + + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Health Boost") + .replace("{effect-level}", RomanNumeral.convertToRoman(baseEnchantment.getMax()+level)) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + PotionEffectUtils.removePotionEffect(player, "GodlyOverloadEnchant"); + + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Health Boost") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + @Override + public String getBaseEnchantment() { + return "overload"; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PermanentExecute.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PermanentExecute.java new file mode 100644 index 0000000..1122648 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PermanentExecute.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.enchantments.elite.Execute; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Effect; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class PermanentExecute extends WeaponDamageEventEnchant implements HeroicEnchantment { + + @ConfigValue + private double damageBuffPerLevel = 5; + + private Execute baseEnchantment; + + public PermanentExecute() { + super("Permanent Execute", EnchantTier.HEROIC, 3, GearType.SWORD, "Constant damage buff, regardless of", "your opponents current health"); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Execute) this.baseEnchantment = (Execute) enchantment; + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + if (Math.random() < this.baseEnchantment.procChance * (7+(level*2))) { + Player victimPlayer = (Player) victim; + super.getDamageHandler().increaseDamage((this.damageBuffPerLevel * level), event, this.getName()); + victimPlayer.getWorld().playEffect(victimPlayer.getEyeLocation(), Effect.STEP_SOUND, Material.REDSTONE_WIRE); + this.baseEnchantment.particle.setLocation(victimPlayer.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victimPlayer, 20)); + } + } + + @Override + public String getBaseEnchantment() { + return "execute"; + } + + + + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PlanetaryDeathbringer.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PlanetaryDeathbringer.java new file mode 100644 index 0000000..9faeb9a --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PlanetaryDeathbringer.java @@ -0,0 +1,43 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.enchantments.legendary.Deathbringer; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.cooldowns.DoubleDamageCooldown; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorOutgoingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class PlanetaryDeathbringer extends ArmorOutgoingPVPDamageEventEnchant implements HeroicEnchantment { + + + private Deathbringer baseEnchantment; + + public PlanetaryDeathbringer() { + super("Planetary Deathbringer", EnchantTier.HEROIC, false, 3, GearType.ARMOR, "Has a chance to deal 2.5x damage", "to your target."); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Deathbringer) this.baseEnchantment = (Deathbringer) enchantment; + } + + @Override + public void runOutgoingDamageEvent(EntityDamageByEntityEvent event, Player attacker, LivingEntity victim, EnchantInfo enchantInfo) { + if (Math.random() < this.baseEnchantment.procChance * (this.baseEnchantment.getMax() + enchantInfo.getLevel())) { + if (CooldownUtils.isCooldownActive(attacker, "doubleDamageCooldown")) return; + CooldownUtils.registerCooldown(attacker, new DoubleDamageCooldown("doubleDamageCooldown", this.baseEnchantment.cooldown)); + super.getDamageHandler().increaseDamage(this.baseEnchantment.damageBuff, event, this.getName()); + attacker.sendMessage(CC.translate("&d&l** PLANETARY DEATHBRINGER **")); + } + } + + @Override + public String getBaseEnchantment() { + return "deathbringer"; + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PolymorphicMetaphysical.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PolymorphicMetaphysical.java new file mode 100644 index 0000000..ddfc439 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/PolymorphicMetaphysical.java @@ -0,0 +1,43 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.enchantments.ultimate.Metaphysical; +import net.crankedpvp.crankedenchants.events.SlownessEnchantProcEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +public class PolymorphicMetaphysical extends Enchantment implements HeroicEnchantment { + + @ConfigValue + private String message = "&d&l** POLYMORPHIC METAPHYSICAL (&8{blocked-enchantment} blocked&d&l) **"; + + private Metaphysical baseEnchantment; + + public PolymorphicMetaphysical() { + super("Polymorphic Metaphysical", EnchantTier.HEROIC, false, 4, GearType.BOOTS, "A chance to resist the slowness given by enemy Trap, Snare, and Pummel enchantments.", "At max level, you will only be affected approx. 10% of the time."); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Metaphysical) this.baseEnchantment = (Metaphysical) enchantment; + } + + @EventHandler + public void runEnchantDamageProcEvent(SlownessEnchantProcEvent event) { + if (!(event.getVictim() instanceof Player)) return; + if (CrankedEnchantsAPI.hasEnchantment(((Player) event.getVictim()), this)) { + if (Math.random() < this.baseEnchantment.procChance * (this.baseEnchantment.getMax() + CrankedEnchantsAPI.getEnchantmentLevel((Player) event.getVictim(), this))) { + event.setCancelled(true); + super.sendMessage(event.getVictim(), this.message, str -> str.replace("{blocked-enchantment}", event.getEnchantment().getName())); + } + } + } + + @Override + public String getBaseEnchantment() { + return "metaphysical"; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/ShadowAssassin.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/ShadowAssassin.java new file mode 100644 index 0000000..cd99906 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/ShadowAssassin.java @@ -0,0 +1,56 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.enchantments.ultimate.Assassin; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class ShadowAssassin extends WeaponDamageEventEnchant implements HeroicEnchantment { + + private Assassin baseEnchantment; + + public ShadowAssassin() { + super("Shadow Assassin", EnchantTier.HEROIC, 5, GearType.SWORD, "The closer you are to your enemy,", "the more damage you deal (up to 1.5x).", "However, if you are more than 2 blocks away,", "you will deal LESS damage than normal."); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Assassin) this.baseEnchantment = (Assassin) enchantment; + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if(!(victim instanceof Player)) return; + final double distance = victim.getLocation().distance(attacker.getLocation()); + + if (distance < 0.25) { + super.getDamageHandler().increaseDamage(this.baseEnchantment.getOneQuarterBlocksPerLevel() * level * 2, event, this.getName()); + return; + } + if (distance < 0.5) { + super.getDamageHandler().increaseDamage(this.baseEnchantment.getOneHalfBlocksPerLevel() * level * 2, event, this.getName()); + return; + } + if (distance < 0.75) { + super.getDamageHandler().increaseDamage(this.baseEnchantment.getThreeQuartersBlocksPerLevel() * level * 2, event, this.getName()); + return; + } + if (distance < 1.0) { + super.getDamageHandler().increaseDamage(this.baseEnchantment.getOneBlockPerLevel() * level * 2, event, this.getName()); + return; + } + if (distance < 2.0) { + super.getDamageHandler().increaseDamage(this.baseEnchantment.getTwoBlocksPerLevel() * level * 2, event, this.getName()); + } + } + + + @Override + public String getBaseEnchantment() { + return "assassin"; + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/SoulHardened.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/SoulHardened.java new file mode 100644 index 0000000..5da6904 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/heroic/SoulHardened.java @@ -0,0 +1,48 @@ +package net.crankedpvp.crankedenchants.enchantments.heroic; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.enchantments.elite.Hardened; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +public class SoulHardened extends ArmorIncomingPVPDamageEventEnchant implements Reloadable, HeroicEnchantment { + + private Hardened baseEnchantment; + + public SoulHardened() { + super("Soul Hardened", EnchantTier.HEROIC, false, 3, GearType.ARMOR, "Armor takes less durability damage."); + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID(this.getBaseEnchantment()); + if(enchantment instanceof Hardened) this.baseEnchantment = (Hardened) enchantment; + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (Math.random() < this.baseEnchantment.procChance * enchantInfo.getLevel()) { + this.baseEnchantment.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 30)); + for (ItemStack itemStack : victim.getInventory().getArmorContents()) { + if (!ItemUtils.isArmor(itemStack)) continue; + itemStack.setDurability((short) (itemStack.getDurability() - (this.baseEnchantment.getMax() + enchantInfo.getLevel() + 2))); + } + } + } + + @Override + public void reloadValues() { + } + + @Override + public String getBaseEnchantment() { + return "hardened"; + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Aegis.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Aegis.java new file mode 100644 index 0000000..63a8f4f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Aegis.java @@ -0,0 +1,45 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.AegisCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Aegis extends ArmorIncomingPVPDamageEventEnchant { + + public Aegis() { + super("Aegis", EnchantTier.LEGENDARY, false, 6, GearType.CHESTPLATE, "If you are taking damage from more than (8-level) enemies in a short period,", "the damage from any additional players beyond that initial group", "will be halved."); + } + + @ConfigValue + private double damageReduction = 2; + + + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (!(attacker instanceof Player)) return; + + Player attackerPlayer = ((Player) attacker); + AegisCache aegisCache = CacheUtils.getAegisCache(victim); + + aegisCache.addPlayerToList(attackerPlayer); + + if (!aegisCache.isStillActive()) { + aegisCache.updateHitTime(); + aegisCache.clearPlayers(); + return; + } + + if (aegisCache.getAmountOfPlayers() >= 4) { + //super.getDamageHandler().reduceDamage(aegisCache.getAmountOfPlayers() * damageReduction, event, this.getName()); + super.getDamageHandler().reduceDamage(damageReduction, event, this.getName()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/AntiGank.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/AntiGank.java new file mode 100644 index 0000000..8eaa237 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/AntiGank.java @@ -0,0 +1,41 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.AntiGankCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class AntiGank extends WeaponDamageEventEnchant { + + public AntiGank() { + super("Anti Gank", EnchantTier.LEGENDARY, 4, GearType.AXE, "If more than (6-level) enemies hit you in a short period,", "your outgoing damage will be multiplied by up to 1.5x", "depending on the amount of enemies nearby."); + } + + @ConfigValue + private double damageAddition = 5; + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + + Player victimPlayer = ((Player) victim); + AntiGankCache antiGankCache = CacheUtils.getAntiGankCache(attacker); + + antiGankCache.addPlayerToList(victimPlayer); + + if (!antiGankCache.isStillActive()) { + antiGankCache.updateHitTime(); + antiGankCache.clearPlayers(); + return; + } + + if (antiGankCache.getAmountOfPlayers() >= 6 - level) { + super.getDamageHandler().increaseDamage(damageAddition * antiGankCache.getAmountOfPlayers(), event, this.getName()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Armored.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Armored.java new file mode 100644 index 0000000..8591f70 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Armored.java @@ -0,0 +1,59 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Silenceable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Effect; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; +import xyz.xenondevs.particle.data.texture.BlockTexture; + +public class Armored extends ArmorIncomingPVPDamageEventEnchant implements Silenceable, Reloadable { + + @ConfigValue + private double damageNegationMultiplier = 1.85; + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 1000; + @ConfigValue + private double particleYoffset = 0.7; + @ConfigValue + private double particleSpeed = 0.05; + + public Armored() { + super("Armored", EnchantTier.LEGENDARY, true, 4, GearType.ARMOR, "Decreases damage from enemy swords by", "x1.85 per level"); + this.reloadValues(); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (!(attacker instanceof Player)) return; + if (((Player) attacker).getItemInHand() == null) return; + if (!ItemUtils.isSword(((Player) attacker).getItemInHand())) return; + + double damageNegation = enchantInfo.getLevel() * damageNegationMultiplier; + super.getDamageHandler().reduceDamage(damageNegation, event, this.getName()); + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 20)); + victim.playEffect(victim.getLocation(), Effect.STEP_SOUND, Material.DIAMOND_BLOCK); + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.BLOCK_DUST) + .setParticleData(new BlockTexture(Material.DIAMOND_BLOCK)) + .setAmount(particleAmount) + .setOffsetY((float) particleYoffset) + .setSpeed((float) particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Barbarian.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Barbarian.java new file mode 100644 index 0000000..1e8a276 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Barbarian.java @@ -0,0 +1,34 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Barbarian extends WeaponDamageEventEnchant { + + @ConfigValue + private int damageBuff = 20; + + public Barbarian() { + super("Barbarian", EnchantTier.LEGENDARY, 4, GearType.AXE, "Multiplies damage against players who are wielding an AXE", " at the time they are hit."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + + Player playerVictim = ((Player) victim); + + if (playerVictim.getItemInHand() == null || playerVictim.getItemInHand().getType() == Material.AIR) return; + if (!ItemUtils.isAxe(playerVictim.getItemInHand())) return; + + super.getDamageHandler().increaseDamage(damageBuff, event, this.getName()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Blacksmith.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Blacksmith.java new file mode 100644 index 0000000..3d5d193 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Blacksmith.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +public class Blacksmith extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.06; + + public Blacksmith() { + super("Blacksmith", EnchantTier.LEGENDARY, 5, GearType.AXE, "Chance to heal your most damaged piece of armor", "by 1-2 durability whenever you hit a player,", " but when it procs your attack will", "only deal 50% of the normal damage."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance * level) { + for (ItemStack itemStack : attacker.getInventory().getArmorContents()) { + if (!ItemUtils.isArmor(itemStack)) continue; + itemStack.setDurability((short) (itemStack.getDurability() - 2)); + } + super.getDamageHandler().reduceDamage(50, event, this.getName()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BloodLink.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BloodLink.java new file mode 100644 index 0000000..dc5cb12 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BloodLink.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.entity.IronGolem; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class BloodLink extends Enchantment { + + public BloodLink() { + super("Blood Link", EnchantTier.LEGENDARY, false, 5, GearType.ARMOR, "A chance to heal you for 1-2hp whenever", "your Guardians take damage."); + } + + @EventHandler + public void onDamageGuardian(EntityDamageByEntityEvent event) { + if (!(event.getEntity() instanceof IronGolem)) return; + if (!(event.getDamager() instanceof Player)) return; + + Entity entity = event.getEntity(); + + if (entity.isDead()) return; + if (!entity.hasMetadata("guardian-owner")) return; + + Player golemOwner = Bukkit.getPlayer(String.valueOf(entity.getMetadata("guardian-owner"))); + + if (golemOwner == null) return; + + if (CrankedEnchantsAPI.hasEnchantment(golemOwner, this)) { + super.getDamageHandler().healEntity(golemOwner, 2, this.getName()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BloodLust.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BloodLust.java new file mode 100644 index 0000000..eae0a8c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BloodLust.java @@ -0,0 +1,12 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; + +public class BloodLust extends Enchantment { + + public BloodLust() { + super("Blood Lust", EnchantTier.LEGENDARY, false, 6, GearType.CHESTPLATE, "A chance to heal you whenever an enemy", "player within 7x7 blocks is damaged", "by the Bleed enchantment. "); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BossSlayer.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BossSlayer.java new file mode 100644 index 0000000..49a6d2c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/BossSlayer.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + + +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class BossSlayer extends WeaponDamageEventEnchant { + + private double percent = 20; + + public BossSlayer() { + super("Boss Slayer", EnchantTier.LEGENDARY, 5, GearType.WEAPON, "Deal significantly more damage to bosses"); + } + + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if(victim instanceof Player) return; + super.getDamageHandler().increaseDamage(percent * level, event, "Boss Slayer"); + } + + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Clarity.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Clarity.java new file mode 100644 index 0000000..4fe551f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Clarity.java @@ -0,0 +1,26 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.BlindingEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +public class Clarity extends Enchantment { + + public Clarity() { + super("Clarity", EnchantTier.LEGENDARY, false, 3, GearType.ARMOR, "Immune to Blindness up to level of clarity enchantment."); + } + + @EventHandler + public void runEnchantDamageProcEvent(EnchantProcOnEntityEvent event) { + if (!(event.getEnchantment() instanceof BlindingEnchant)) return; + if (!(event.getVictim() instanceof Player)) return; + if (CrankedEnchantsAPI.hasEnchantment((Player) event.getVictim(), this)) { + event.setCancelled(true); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/DeathGod.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/DeathGod.java new file mode 100644 index 0000000..cc661e4 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/DeathGod.java @@ -0,0 +1,35 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class DeathGod extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.07; + @ConfigValue + private int cooldown = 30; + @ConfigValue + private String message = "&6&l* DEATH GOD [&6{heal-amount} HP&l] *"; + + public DeathGod() { + super("Death God", EnchantTier.LEGENDARY, false, 3, GearType.HELMET, "Attacks that bring your HP to (level+4) hearts or lower", "have a chance to heal you for (level+5) hearts instead."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + if (victim.getHealth() > enchantInfo.getLevel() + 4) return; + if (Math.random() < procChance * enchantInfo.getLevel()) { + super.getDamageHandler().healEntity(victim, enchantInfo.getLevel() + 5, this.getName()); + super.registerCooldown(victim, cooldown); + super.sendMessage(victim, message, str -> str.replace("{heal-amount}", String.valueOf(enchantInfo.getLevel() + 5))); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Deathbringer.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Deathbringer.java new file mode 100644 index 0000000..245fa74 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Deathbringer.java @@ -0,0 +1,37 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.cooldowns.DoubleDamageCooldown; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorOutgoingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Deathbringer extends ArmorOutgoingPVPDamageEventEnchant { + + @ConfigValue + public double procChance = 0.03; + @ConfigValue + public double damageBuff = 25; + @ConfigValue + public int cooldown = 5; + + public Deathbringer() { + super("Deathbringer", EnchantTier.LEGENDARY, false, 3, GearType.ARMOR, "Has a chance to deal double damage", "to your target."); + } + + @Override + public void runOutgoingDamageEvent(EntityDamageByEntityEvent event, Player attacker, LivingEntity victim, EnchantInfo enchantInfo) { + if (Math.random() < procChance * enchantInfo.getLevel()) { + if (CooldownUtils.isCooldownActive(attacker, "doubleDamageCooldown")) return; + CooldownUtils.registerCooldown(attacker, new DoubleDamageCooldown("doubleDamageCooldown", cooldown)); + super.getDamageHandler().increaseDamage(damageBuff, event, this.getName()); + attacker.sendMessage(CC.translate("&6&l** DEATHBRINGER **")); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Destruction.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Destruction.java new file mode 100644 index 0000000..0801bf6 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Destruction.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Destruction extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.08; + @ConfigValue + private double range = 7.0; + @ConfigValue + private int witherLevel = 1; + @ConfigValue + private int cooldown = 30; + + public Destruction() { + super("Destruction", EnchantTier.LEGENDARY, false, 5, GearType.HELMET, "Automatically damages and debuffs all nearby enemies."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + if (Math.random() < procChance) { + int level = enchantInfo.getLevel(); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victim); + victim.getNearbyEntities(range, range, range).forEach(entity -> { + if (!(entity instanceof Player)) return; + Player nearbyPlayer = (Player) entity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) return; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtLeast(Relation.TRUCE)) return; + super.getDamageHandler().damage(nearbyPlayer, level > 4 ? 2 : 1, this.getName()); + if (enchantInfo.getLevel() > 4 && Math.random() < 0.55) { + nearbyPlayer.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, enchantInfo.getLevel() * 20, witherLevel, true)); + } + }); + super.registerCooldown(victim, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Devour.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Devour.java new file mode 100644 index 0000000..0639dd1 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Devour.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.BleedStacksCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; +import xyz.xenondevs.particle.data.texture.BlockTexture; + +public class Devour extends WeaponDamageEventEnchant implements Reloadable { + + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 50; + @ConfigValue + private double particleYoffset = 0.7; + @ConfigValue + private double particleSpeed = 0.1; + + public Devour() { + super("Devour", EnchantTier.LEGENDARY, 4, GearType.AXE, "Multiplies damage dealt to players with active bleed stacks", "from the Bleed enchantment."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + + Player victimPlayer = ((Player) victim); + BleedStacksCache victimBleedStack = CacheUtils.getBleedStackCache(victimPlayer); + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victimPlayer, 20)); + super.getDamageHandler().increaseDamage(victimBleedStack.getBleedStack() * 10, event, this.getName()); + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.BLOCK_DUST) + .setParticleData(new BlockTexture(Material.MYCEL)) + .setAmount(particleAmount) + .setOffsetY((float) particleYoffset) + .setSpeed((float) particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Diminish.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Diminish.java new file mode 100644 index 0000000..4402e1c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Diminish.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.DiminishCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; + +import java.text.DecimalFormat; + +public class Diminish extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.0015; + @ConfigValue + private String message = "&e&l* DIMINISH [&eDMG {damage}&l] *"; + private DecimalFormat df; + + public Diminish() { + super("Diminish", EnchantTier.LEGENDARY, false, 6, GearType.CHESTPLATE, "When this effect procs, the next", "attack dealt to you cannot deal more", "than the total amount of damage / 2", "you took from the previous attack."); + this.df = new DecimalFormat("#.##"); + } + + //TODO: finish message + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + DiminishCache diminishCache = CacheUtils.getDiminishLastAttackCache(victim); + + if (diminishCache.getLastDamage() != -1.0) { + final double maxDmg = diminishCache.getLastDamage() / 2; + if (event.getDamage() > maxDmg) { + super.getDamageHandler().setDamage(event, maxDmg, super.getName()); + diminishCache.setLastDamage(-1.0); + return; + } + } + + if (Math.random() < this.procChance * enchantInfo.getLevel()) { + diminishCache.setLastDamage(event.getDamage(EntityDamageEvent.DamageModifier.BASE)); + super.sendMessage(victim, this.message, str -> str.replace("{damage}", String.valueOf(this.df.format(Math.max(0.0, event.getFinalDamage()))))); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/DoubleStrike.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/DoubleStrike.java new file mode 100644 index 0000000..6904a28 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/DoubleStrike.java @@ -0,0 +1,42 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.cooldowns.DoubleDamageCooldown; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class DoubleStrike extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.04; + + @ConfigValue + private int cooldown = 5; + + public DoubleStrike() { + super("Double Strike", EnchantTier.LEGENDARY, 3, GearType.SWORD, "Has a chance to attack twice in one swing.", "All your enchants can re-proc on", "this second attack, and it occurs", "instantly"); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if(victim instanceof Player) { + if(Math.random() < procChance * level) { + if (CooldownUtils.isCooldownActive(attacker, "doubleDamageCooldown")) return; + CooldownUtils.registerCooldown(attacker, new DoubleDamageCooldown("doubleDamageCooldown", cooldown)); + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), () -> { + if(victim.isDead()) return; + super.getDamageHandler().damage(victim, event.getFinalDamage(), "Double Strike"); + attacker.sendMessage(CC.translate("&6&l** DOUBLE STRIKE **")); + }, 2L); + } + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Drunk.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Drunk.java new file mode 100644 index 0000000..814a3f7 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Drunk.java @@ -0,0 +1,73 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class Drunk extends ArmorEquipEventEnchant { + + public Drunk() { + super("Drunk", EnchantTier.LEGENDARY, false, 4, GearType.HELMET, "Slowness and slow swing with", "buffed strength."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.INCREASE_DAMAGE, Math.min(level, 3), "DrunkStrength"); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SLOW, Math.min(level, 3), "DrunkSlow"); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SLOW_DIGGING, Math.min(level, 3), "DrunkSlowDigging"); + + + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Strength") + .replace("{effect-level}", RomanNumeral.convertToRoman(Math.min(level, 3))) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Slowness") + .replace("{effect-level}", RomanNumeral.convertToRoman(Math.min(level, 3))) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Mining Fatigue") + .replace("{effect-level}", RomanNumeral.convertToRoman(3)) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + PotionEffectUtils.removePotionEffect(player, "DrunkStrength"); + PotionEffectUtils.removePotionEffect(player, "DrunkSlow"); + PotionEffectUtils.removePotionEffect(player, "DrunkSlowDigging"); + + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Strength") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Slowness") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Mining Fatigue") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Enlighted.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Enlighted.java new file mode 100644 index 0000000..1541bc5 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Enlighted.java @@ -0,0 +1,32 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Enlighted extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + public double procChance = 0.075; + @ConfigValue + public int cooldown = 20; + + public Enlighted() { + super("Enlighted", EnchantTier.LEGENDARY, true, 3, GearType.ARMOR, "Has a chance to heal you", "while taking damage"); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance * enchantInfo.getLevel()) { + super.getDamageHandler().healEntity(victim, enchantInfo.getAmount(), this.getName()); + super.registerCooldown(victim, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Gears.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Gears.java new file mode 100644 index 0000000..826e61c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Gears.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class Gears extends ArmorEquipEventEnchant { + + public Gears() { + super("Gears", EnchantTier.LEGENDARY, false, 3, GearType.BOOTS, "Added speed when equipped."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, level, "GearsEnchant"); + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Speed") + .replace("{effect-level}", RomanNumeral.convertToRoman(level)) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + PotionEffectUtils.removePotionEffect(player, "GearsEnchant"); + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Speed") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Inquisitive.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Inquisitive.java new file mode 100644 index 0000000..4603bde --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Inquisitive.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDeathEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDeathEvent; + +public class Inquisitive extends WeaponDeathEventEnchant { + + @ConfigValue + private int expMultiplier = 2; + + public Inquisitive() { + super("Inquisitive", EnchantTier.LEGENDARY, 4, GearType.SWORD, "Increases EXP drops from mobs."); + } + + @Override + public void runEntityDeathEvent(EntityDeathEvent event, Player killer, LivingEntity victim, int level) { + event.setDroppedExp((event.getDroppedExp() * level) * expMultiplier); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Insanity.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Insanity.java new file mode 100644 index 0000000..0a39d1b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Insanity.java @@ -0,0 +1,41 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +public class Insanity extends WeaponDamageEventEnchant { + + @ConfigValue + private double hookBuff = 1; + + @ConfigValue + private double axeBuff = 4.5; + + public Insanity() { + super("Insanity", EnchantTier.LEGENDARY, 8, GearType.AXE, "Multiplies damage against players who", "are wielding a sword at the time", "they are hit"); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + Player playerVictim = (Player) victim; + if (playerVictim.getItemInHand() == null) return; + if (attacker.getItemInHand() == null) return; + if (!GearType.SWORD.getItems().contains(playerVictim.getItemInHand().getType())) return; + + double damageBuff = isActuallyAnAxe(attacker.getItemInHand()) ? this.axeBuff : this.hookBuff; + super.getDamageHandler().increaseDamage(damageBuff * level, event, this.getName()); + } + + private boolean isActuallyAnAxe(ItemStack itemStack) { + return (!ItemUtils.isAirOrNull(itemStack) && itemStack + .getType().name().contains("_AXE")); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Inversion.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Inversion.java new file mode 100644 index 0000000..81e0f45 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Inversion.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponIncomingDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.concurrent.ThreadLocalRandom; + +public class Inversion extends WeaponIncomingDamageEventEnchant { + + @ConfigValue + private double procChance = 0.035; + + public Inversion() { + super("Inversion", EnchantTier.LEGENDARY, 4, GearType.SWORD, "Damage dealt to you has a % chance to be blocked", "and heal you for 1-3 HP instead."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, int level) { + if (Math.random() < procChance * level) { + super.getDamageHandler().cancelDamage(event, this.getName()); + super.getDamageHandler().healEntity(victim, ThreadLocalRandom.current().nextInt(1, 4), this.getName()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Judgement.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Judgement.java new file mode 100644 index 0000000..d7eb039 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Judgement.java @@ -0,0 +1,34 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +public class Judgement extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.01; + @ConfigValue + private int durationInSeconds = 2; + public Judgement() { + super("Judgement", EnchantTier.LEGENDARY, false, 5, GearType.ARMOR, "Chance of adding regeneration to", "yourself when being attacked"); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + int level = enchantInfo.getLevel() <= 3 ? 0 : enchantInfo.getLevel() - 3; + if (Math.random() < procChance * enchantInfo.getLevel()) { + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.REGENERATION, level, "JudgementEnchant", durationInSeconds); + super.registerCooldown(victim, 30); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Leadership.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Leadership.java new file mode 100644 index 0000000..9f4f505 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Leadership.java @@ -0,0 +1,48 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorOutgoingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Leadership extends ArmorOutgoingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.06; + @ConfigValue + private int range = 12; + + public Leadership() { + super("Leadership", EnchantTier.LEGENDARY, false, 5, GearType.ARMOR, "The more allies near you, the more damage you deal."); + } + + @Override + public void runOutgoingDamageEvent(EntityDamageByEntityEvent event, Player attacker, LivingEntity victim, EnchantInfo enchantInfo) { + if (Math.random() < this.procChance * enchantInfo.getLevel()) { + + int counter = 0; + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(attacker); + for (Entity nearbyEntity : attacker.getNearbyEntities(this.range, this.range, this.range)) { + if (!(nearbyEntity instanceof Player)) return; + Player nearbyPlayer = (Player) nearbyEntity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) return; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtMost(Relation.NEUTRAL)) return; + counter++; + } + + super.getDamageHandler().increaseDamage(Math.max(counter, 5) * 4, event, this.getName()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Lifesteal.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Lifesteal.java new file mode 100644 index 0000000..b6551fa --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Lifesteal.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Lifesteal extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.01; + @ConfigValue + private double healAmount = 5.0; + @ConfigValue + private int cooldown = 15; + + public Lifesteal() { + super("Lifesteal", EnchantTier.LEGENDARY, 5, GearType.SWORD, "Has a chance of regaining health when", "attacking a player"); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + if (super.isOnCooldown(attacker)) return; + if (CrankedMasksAPI.hasMaskEquipped((Player) victim, CrankedMasks.getInstance().getMasksRegister().getMaskFromID("vampire"))) { + return; + } + if (Math.random() < this.procChance * level) { + super.getDamageHandler().healEntity(attacker, this.healAmount, this.getName()); + super.getDamageHandler().removeHealth(attacker, this.healAmount, this.getName()); + super.registerCooldown(attacker, this.cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Overload.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Overload.java new file mode 100644 index 0000000..1dcbc0d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Overload.java @@ -0,0 +1,42 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +public class Overload extends ArmorEquipEventEnchant { + + public Overload() { + super("Overload", EnchantTier.LEGENDARY, false, 3, GearType.ARMOR, "Increases the wearer's total health."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.HEALTH_BOOST, level, "OverloadEnchant"); + + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Health Boost") + .replace("{effect-level}", RomanNumeral.convertToRoman(level)) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + PotionEffectUtils.removePotionEffect(player, "OverloadEnchant"); + + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Health Boost") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Platemail.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Platemail.java new file mode 100644 index 0000000..9086fc2 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Platemail.java @@ -0,0 +1,68 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; + +public class Platemail extends ArmorEquipEventEnchant { + + public Platemail() { + super("Platemail", EnchantTier.LEGENDARY, false, 2, GearType.ARMOR, "This enchant is currently disabled"); + //"Gain damage resistance at the tradeoff", "of slowness." + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + + } + /* + + @Override + public void runArmorEquipEvent(Player player, int level) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.DAMAGE_RESISTANCE, level, "PlatemailEnchantRes"); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SLOW, level, "PlatemailEnchantSlow"); + + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Resistance") + .replace("{effect-level}", RomanNumeral.convertToRoman(level)) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Slowness") + .replace("{effect-level}", RomanNumeral.convertToRoman(level)) + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + PotionEffectUtils.removePotionEffect(player, "PlatemailEnchantRes"); + PotionEffectUtils.removePotionEffect(player, "PlatemailEnchantSlow"); + + player.removePotionEffect(PotionEffectType.SLOW); + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Resistance") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Slowness") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + */ +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Protection.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Protection.java new file mode 100644 index 0000000..bf06536 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Protection.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Protection extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.08; + @ConfigValue + private double range = 7.0; + @ConfigValue + private int regenerationLevel = 1; + @ConfigValue + private int cooldown = 20; + + public Protection() { + super("Protection", EnchantTier.LEGENDARY, false, 5, GearType.ARMOR, "Automatically heals and buffs all nearby faction allies."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + if (Math.random() < procChance) { + int level = enchantInfo.getLevel(); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victim); + victim.getNearbyEntities(range, range, range).forEach(entity -> { + if (!(entity instanceof Player)) return; + Player nearbyPlayer = (Player) entity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) return; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtMost(Relation.NEUTRAL)) return; + super.getDamageHandler().healEntity(nearbyPlayer, level > 4 ? 2 : 1, this.getName()); + if (enchantInfo.getLevel() > 3 && Math.random() < 0.5) { + nearbyPlayer.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, enchantInfo.getLevel() * 20, regenerationLevel, true)); + } + }); + super.registerCooldown(victim, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Rage.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Rage.java new file mode 100644 index 0000000..ca2fad7 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Rage.java @@ -0,0 +1,95 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.RageStacksCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.objecthunter.exp4j.Expression; +import net.objecthunter.exp4j.ExpressionBuilder; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; +import xyz.xenondevs.particle.data.texture.BlockTexture; + +public class Rage extends WeaponDamageEventEnchant implements Reloadable { + + @ConfigValue + private String damageFormula = "(level * rageStack) * 2"; + private Expression damageExpression; + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 1000; + @ConfigValue + private double particleYoffset = 1.2; + @ConfigValue + private double particleSpeed = 0.05; + + public Rage() { + super("Rage", EnchantTier.LEGENDARY, 6, GearType.WEAPON, "More consecutive hits cause more", "damage to be dealt."); + this.reloadValues(); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + + Player victimPlayer = (Player) victim; + RageStacksCache rageStacksCache = CacheUtils.getRageStackCache(attacker); + + if (rageStacksCache.getLastRageStackTime() + 30000 < System.currentTimeMillis() || !rageStacksCache.isSameVictim(victimPlayer)) { + rageStacksCache.updateLastRageStackTime(); + rageStacksCache.resetRageStack(); + rageStacksCache.updateVictim(victimPlayer); + return; + } + + double rageDamage = this.damageExpression + .setVariable("level", level) + .setVariable("rageStack", rageStacksCache.getRageStack()) + .evaluate(); + //if(AdminWeaponsAPI.hasAdminWeaponEquipped(attacker, "nanoblackreaper")) rageDamage *= 1.075; + //if(AdminWeaponsAPI.hasAdminWeaponEquipped(attacker, "elementalexcalibur")) rageDamage *= 1.035; + if(StarItemsAPI.playerHasStarItem(attacker, "combo")) rageDamage*=1.25; + super.getDamageHandler().increaseDamage(rageDamage, event, this.getName()); + + if (rageStacksCache.getRageStack() > 1) { + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victimPlayer, 20)); + } + + rageStacksCache.incrementRageStack(); + rageStacksCache.updateLastRageStackTime(); + rageStacksCache.updateVictim(victimPlayer); + } + + @EventHandler + public void onDamage(EntityDamageByEntityEvent event) { + if (event.getEntity() instanceof Player && event.getDamager() instanceof Player) { + Player player = (Player) event.getEntity(); + RageStacksCache victimRageStack = CacheUtils.getRageStackCache(player); + if (victimRageStack.getRageStack() > 0) { + victimRageStack.resetRageStack(); + } + + } + } + + @Override + public void reloadValues() { + this.damageExpression = new ExpressionBuilder(this.damageFormula).variable("level").variable("rageStack").build(); + this.particle = new ParticleBuilder(ParticleEffect.BLOCK_DUST) + .setParticleData(new BlockTexture(Material.REDSTONE_BLOCK)) + .setAmount(this.particleAmount) + .setOffsetY((float) this.particleYoffset) + .setSpeed((float) this.particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Silence.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Silence.java new file mode 100644 index 0000000..97d5eae --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Silence.java @@ -0,0 +1,133 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.cooldowns.DragonReflectSilenceCooldown; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.SilenceCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Silenceable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.concurrent.ThreadLocalRandom; + +public class Silence extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.05; + @ConfigValue + private int cooldown = 30; + @ConfigValue + private String messageAttacker = "&5&l* SILENCE &7[{duration}s]&5&l *"; + @ConfigValue + private String messageVictim = "&5&l* SILENCED &7[{duration}s]&5&l *"; + + @ConfigValue + private int dragonSetReflectSilenceCooldown = 15; + + @ConfigValue + private int dragonSetReflectSilenceChance = 20; + + @ConfigValue + private String dragonSetReflectSilenceMessage = "&d&lDragon &8➥ &7You have reflected your opponents &6silence &7enchant"; + + public Silence() { + super("Silence", EnchantTier.LEGENDARY, 4, GearType.SWORD, "Chance to stop activation of your enemies enchants."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victimEntity, Player attacker, int level) { + if (!(victimEntity instanceof Player)) return; + if (super.isOnCooldown(attacker)) return; + + + Player victimPlayer = (Player) victimEntity; + + double extraProcChance = 0; + if(AdminWeaponsAPI.hasAdminWeaponEquipped(attacker, "yorukazu")) { + extraProcChance+=15; + } + if (Math.random() < (this.procChance * level) * (1+(extraProcChance/100))) { + + + SilenceCache silenceCache = CacheUtils.getSilenceCache(victimPlayer); + if (silenceCache.isSilenced()) return; + + + ArmorSet armorSet = CrankedArmorAPI.getCurrentArmorSet(victimPlayer); + if(armorSet!= null && armorSet.getID().equals("dragon") && ThreadLocalRandom.current().nextInt(101) < (this.dragonSetReflectSilenceChance)) { + if(!CooldownUtils.isCooldownActive(victimPlayer, "dragonreflectsilence")) { + CooldownUtils.registerCooldown(victimPlayer, new DragonReflectSilenceCooldown("dragonreflectsilence", this.dragonSetReflectSilenceCooldown)); + this.runEntityDamageByEntityEvent(event, attacker, victimPlayer, level); + victimPlayer.sendMessage(CC.translate(this.dragonSetReflectSilenceMessage)); + } + } + + if(CrankedMasksAPI.hasMaskEquipped(victimPlayer, "antisilence") && Math.random() <= 0.1) { + victimPlayer.sendMessage(CC.translate("&f&l* ANTI SILENCE &7[BLOCKED SILENCE]&f&l *")); + return; + } + silenceCache.setSilenced(true); + int silenceTime = level; + + if (CrankedEnchantsAPI.hasWeaponEnchantment(attacker, "solitude")) { + silenceTime += CrankedEnchantsAPI.getWeaponEnchantmentLevel(attacker, "solitude"); + } + + + if(StarItemsAPI.playerHasStarItemInCache(victimPlayer)) { + if (StarItemsAPI.getStarItemFromCache(attacker).contains(StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID("blackoutblindfold"))) { + silenceTime*=1.35; + } + if (StarItemsAPI.getStarItemFromCache(victimPlayer).contains(StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID("absence"))) { + silenceTime*=0.75; + } + } + + + if(AdminWeaponsAPI.hasAdminWeaponEquipped(attacker, "kazeshini")) { + silenceTime*=1.125; + } + if(AdminWeaponsAPI.hasAdminWeaponEquipped(attacker, "yorukazu")) { + silenceTime*=1.25; + } + + + if(CrankedMasksAPI.hasMaskEquipped(victimPlayer, "antisilence")) { + silenceTime*=0.85; + } + + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), () -> silenceCache.setSilenced(false), silenceTime * 20L); + super.registerCooldown(attacker, this.cooldown); + int finalSilenceTime = silenceTime; + super.sendMessage(attacker, this.messageAttacker, str -> str.replace("{duration}", String.valueOf(finalSilenceTime))); + super.sendMessage(victimEntity, this.messageVictim, str -> str.replace("{duration}", String.valueOf(finalSilenceTime))); + victimEntity.getWorld().playSound(victimEntity.getLocation(), Sound.WITHER_HURT, 1.0f, 0.25f); + } + } + + @EventHandler + public void runEnchantDamageProcEvent(EnchantProcOnEntityEvent event) { + if (!(event.getEnchantment() instanceof Silenceable)) return; + if (!(event.getVictim() instanceof Player)) return; + + if (CacheUtils.getSilenceCache((Player) event.getVictim()).isSilenced()) event.setCancelled(true); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Tray.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Tray.java new file mode 100644 index 0000000..90af837 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/legendary/Tray.java @@ -0,0 +1,76 @@ +package net.crankedpvp.crankedenchants.enchantments.legendary; + +import com.massivecraft.factions.*; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.BlockBreakEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.BlockUtil; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.block.BlockBreakEvent; + +import java.util.Arrays; +import java.util.List; + +public class Tray extends BlockBreakEventEnchant { + private final Board board = Board.getInstance(); + private final FPlayers fPlayers = FPlayers.getInstance(); + + public Tray() { + super("Tray", EnchantTier.LEGENDARY, 1, GearType.PICKAXE, "Mine netherrack blocks in a large radius."); + } + + public static List trayWhiteListedBlocks = Arrays.asList(Material.NETHERRACK); + + @ConfigValue + private int radius = 6; + + @Override + public void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder) { + if (event.isCancelled()) return; + trayEffect(event.getBlock(), radius, event.getPlayer()); + + } + + public void trayEffect(Block block, int r, Player p) { + FPlayer fplayer = fPlayers.getByPlayer(p); + Block target; + Faction locFac; + + double borderRadius = block.getWorld().getWorldBorder().getSize() / 2; + + final World world = block.getWorld(); + final int startX = block.getX(); + final int startY = block.getY(); + final int startZ = block.getZ(); + for (int x = -r; x <= r; x++) { + for (int z = -r; z <= r; z++) { + if (Math.abs(getAccurateCoord(startX + x)) >= borderRadius || Math.abs(getAccurateCoord(startZ + z)) >= borderRadius) continue; + + target = world.getBlockAt(startX + x, startY, startZ + z); + locFac = board.getFactionAt(new FLocation(target.getLocation())); + + if (!fplayer.getFaction().equals(locFac) && !locFac.isWilderness()) continue; + + Material type = target.getType(); + if (trayWhiteListedBlocks.contains(type)) { + BlockUtil.setAir(world, startX + x, startY, startZ + z, false); + } + if (type == Material.WATER || type == Material.STATIONARY_WATER || type == Material.NETHERRACK) { + BlockUtil.updatePhysics(world, startX + x, startY, startZ + z); + } + } + } + } + + private double getAccurateCoord(double coord) { + if (coord < 0) return coord + 1.0; + return coord; + } + + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Aquatic.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Aquatic.java new file mode 100644 index 0000000..f64299d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Aquatic.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Aquatic extends ArmorEquipEventEnchant { + + public Aquatic() { + super("Aquatic", EnchantTier.SIMPLE, false,1, GearType.HELMET, "Added water breathing when equipped."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + player.addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, Integer.MAX_VALUE, level - 1), true); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + player.removePotionEffect(PotionEffectType.WATER_BREATHING); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/AutoSmelt.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/AutoSmelt.java new file mode 100644 index 0000000..07ae3ef --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/AutoSmelt.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.BlockBreakEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.inventory.ItemStack; + +public class AutoSmelt extends BlockBreakEventEnchant { + + public AutoSmelt() { + super("Auto Smelt", EnchantTier.SIMPLE, 1, GearType.PICKAXE, "Smelts mined ores into ingots."); + } + + @Override + public void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder) { + Location location = event.getBlock().getLocation().add(0.5, 0.5, 0.5); + + switch (event.getBlock().getType()) { + case IRON_ORE: + location.getWorld().dropItem(location, new ItemStack(Material.IRON_INGOT)); + break; + case GOLD_ORE: + location.getWorld().dropItem(location, new ItemStack(Material.GOLD_INGOT)); + break; + default: + return; + } + + event.setCancelled(true); + event.getBlock().setType(Material.AIR); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Confusion.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Confusion.java new file mode 100644 index 0000000..6d0cf66 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Confusion.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Confusion extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.006; + + public Confusion() { + super("Insomnia", EnchantTier.SIMPLE, 7, GearType.AXE, "Chance to deal nausea to your victim. "); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance * level) { + victim.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 80, 0, true)); + } + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Decapitation.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Decapitation.java new file mode 100644 index 0000000..7d6148e --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Decapitation.java @@ -0,0 +1,23 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDeathEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDeathEvent; + +public class Decapitation extends WeaponDeathEventEnchant { + + public Decapitation() { + super("Decapitation", EnchantTier.SIMPLE, 3, GearType.AXE, "Victims have a chance of dropping their head on death."); + } + + @Override + public void runEntityDeathEvent(EntityDeathEvent event, Player killer, LivingEntity victim, int level) { + if (!(victim instanceof Player)) return; + killer.getInventory().addItem(SkullUtils.getSkullFromPlayer(((Player) victim))); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Epicness.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Epicness.java new file mode 100644 index 0000000..86050fd --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Epicness.java @@ -0,0 +1,21 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Epicness extends WeaponDamageEventEnchant { + + public Epicness() { + super("Epicness", EnchantTier.SIMPLE, 3, GearType.SWORD, "Gives particles and sound effects."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Experience.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Experience.java new file mode 100644 index 0000000..86713b4 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Experience.java @@ -0,0 +1,26 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.BlockBreakEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.EntityType; +import org.bukkit.event.block.BlockBreakEvent; + +public class Experience extends BlockBreakEventEnchant { + + @ConfigValue + private double procChance = 0.05; + + public Experience() { + super("Experience", EnchantTier.SIMPLE, 5, GearType.TOOL, "Gives more exp when mining blocks. "); + } + + @Override + public void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder) { + if (Math.random() < procChance * enchantedItemBuilder.getEnchantmentLevel(this)) { + event.getBlock().getWorld().spawnEntity(event.getBlock().getLocation(), EntityType.EXPERIENCE_ORB); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Glowing.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Glowing.java new file mode 100644 index 0000000..8815d96 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Glowing.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Glowing extends ArmorEquipEventEnchant { + + public Glowing() { + super("Glowing", EnchantTier.SIMPLE, false,1, GearType.HELMET, "Added Night Vision when equipped."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, level - 1), true); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + player.removePotionEffect(PotionEffectType.NIGHT_VISION); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Headless.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Headless.java new file mode 100644 index 0000000..64e5aca --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Headless.java @@ -0,0 +1,23 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDeathEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDeathEvent; + +public class Headless extends WeaponDeathEventEnchant { + + public Headless() { + super("Headless", EnchantTier.SIMPLE, 3, GearType.SWORD, "Victims have a chance of dropping their head on death."); + } + + @Override + public void runEntityDeathEvent(EntityDeathEvent event, Player killer, LivingEntity victim, int level) { + if (!(victim instanceof Player)) return; + killer.getInventory().addItem(SkullUtils.getSkullFromPlayer(((Player) victim))); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Insomnia.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Insomnia.java new file mode 100644 index 0000000..b22251b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Insomnia.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SlownessEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +public class Insomnia extends WeaponDamageEventEnchant implements SlownessEnchant { + + @ConfigValue + private double procChance = 0.006; + + public Insomnia() { + super("Insomnia", EnchantTier.SIMPLE, 7, GearType.SWORD, "Chance to proc slowness, mining fatigue", "and confusion against other", "players."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if(!(victim instanceof Player))return; + if (Math.random() < procChance * level) { + Player victim2 = (Player) victim; + PotionEffectUtils.addPotionEffect(victim2, PotionEffectType.SLOW, 0, "insomnia_slow", 80); + PotionEffectUtils.addPotionEffect(victim2, PotionEffectType.SLOW, 0, "insomnia_slowdigging", 80); + PotionEffectUtils.addPotionEffect(victim2, PotionEffectType.SLOW, 0, "insomnia_confusion", 80); + + //victim.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 80, 0, true)); + //victim.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, 80, 0, true)); + //victim.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 80, 0, true)); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Obliterate.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Obliterate.java new file mode 100644 index 0000000..a931173 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Obliterate.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Obliterate extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.1; + + public Obliterate() { + super("Obliterate", EnchantTier.SIMPLE, 5, GearType.AXE, "Chance to give extreme knockback", "to your enemy."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance * level) { + victim.setVelocity(attacker.getLocation().getDirection().multiply(6)); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Oxygenate.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Oxygenate.java new file mode 100644 index 0000000..a51a932 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/Oxygenate.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.BlockBreakEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.event.block.BlockBreakEvent; + +public class Oxygenate extends BlockBreakEventEnchant { + + public Oxygenate() { + super("Oxygenate", EnchantTier.SIMPLE, 1, GearType.TOOL, "Refills oxygen levels when breaking blocks under water."); + } + + @Override + public void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder) { + event.getPlayer().setRemainingAir(event.getPlayer().getMaximumAir()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/ThunderingBlow.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/ThunderingBlow.java new file mode 100644 index 0000000..f6de0b8 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/simple/ThunderingBlow.java @@ -0,0 +1,28 @@ +package net.crankedpvp.crankedenchants.enchantments.simple; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class ThunderingBlow extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.06; + + public ThunderingBlow() { + super("Thundering Blow", EnchantTier.SIMPLE, 3, GearType.SWORD, "Chance to smite ur victim", "during combat."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance) { + victim.getWorld().strikeLightningEffect(victim.getLocation()); + victim.setHealth(victim.getHealth() - level); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/DivineImmolation.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/DivineImmolation.java new file mode 100644 index 0000000..cd0a75d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/DivineImmolation.java @@ -0,0 +1,112 @@ +package net.crankedpvp.crankedenchants.enchantments.soul; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.DrainSoulEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staritems.StarItemsAPI; +import net.objecthunter.exp4j.Expression; +import net.objecthunter.exp4j.ExpressionBuilder; +import org.bukkit.GameMode; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +import java.util.List; + +public class DivineImmolation extends WeaponDamageEventEnchant implements DrainSoulEnchant, Reloadable { + + @ConfigValue + private String damageFormula = "level * 1.1"; + @ConfigValue + private String message = "&c&l** DIVINE IMMOLATION **"; + private Expression damageExpression; + private ParticleBuilder particle; + private Essentials essentials; + + public DivineImmolation() { + super("Divine Immolation", EnchantTier.SOUL, 4, GearType.SWORD, "Active soul enchant. Your weapons are imbued with divine fire,", "turning all your physical attacks into Area of Effect spells", "and igniting divine fire upon all nearby enemies."); + this.reloadValues(); + this.essentials = EssentialsUtils.getEssentials(); + this.particle = new ParticleBuilder(ParticleEffect.LAVA) + .setAmount(50) + .setOffsetY(1) + .setSpeed(0.15f); + + + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(attacker); + + List nearbyPlayers = victim.getNearbyEntities(level, level, level); + nearbyPlayers.add(victim); + + for (Entity nearbyEntity : nearbyPlayers) { + if (nearbyEntity.equals(attacker)) continue; + if (!(nearbyEntity instanceof Player)) continue; + Player nearbyPlayer = ((Player) nearbyEntity); + User user = this.essentials.getUser(nearbyPlayer); + if (user.isGodModeEnabled() || user.isVanished()) continue; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) continue; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) continue; + if (StaffPlugin.getInstance().getFreezeManager().getFrozenPlayers().containsKey(nearbyPlayer)) continue; + if (StarItemsAPI.playerHasStarItemInCache(nearbyPlayer) && StarItemsAPI.playerHasStarItem(nearbyPlayer, "frostbite")) + continue; + + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + + if (fPlayer.getRelationTo(fPlayerNearby).isAtLeast(Relation.TRUCE)) continue; + //nearbyPlayer.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 60, 1, true, false)); + nearbyPlayer.playSound(nearbyEntity.getLocation(), Sound.FIREWORK_BLAST, 1.0f, 0.3f); + nearbyPlayer.playSound(nearbyEntity.getLocation(), Sound.ZOMBIE_PIG_ANGRY, 0.8f, 0.5f); + CacheUtils.getDivineCache(nearbyPlayer).updateLastProcTime(); + + super.getDamageHandler().damage(nearbyPlayer, this.damageExpression.setVariable("level", level).evaluate(), "&c&lDivine Tick"); + super.sendMessage(nearbyPlayer, this.message); + } + } + +/* @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onEntityDamage(EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (event.getCause() != EntityDamageEvent.DamageCause.WITHER) return; + + Player player = ((Player) event.getEntity()); + + if (CacheUtils.getDivineCache(player).isDivineActive()) { + if(StarItemsAPI.playerHasStarItemInCache(player) && StarItemsAPI.playerHasStarItem(player, "frostbite")) return; + super.getDamageHandler().damage(player, this.damageExpression.setVariable("level", 4).evaluate(), "&c&lDivine Tick"); + player.playSound(player.getLocation(), Sound.ZOMBIE_PIG_ANGRY, 0.8f, 0.5f); + super.sendMessage(player, this.message); + this.particle.setLocation(player.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(player, 30)); + } + }*/ + + @Override + public int getSoulCost() { + return 5; + } + + @Override + public void reloadValues() { + this.damageExpression = new ExpressionBuilder(this.damageFormula).variable("level").build(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Immortal.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Immortal.java new file mode 100644 index 0000000..7c36454 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Immortal.java @@ -0,0 +1,21 @@ +package net.crankedpvp.crankedenchants.enchantments.soul; + +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Immortal extends ArmorIncomingPVPDamageEventEnchant { + + public Immortal() { + super("Immortal", EnchantTier.SOUL, false, 4, GearType.ARMOR, "Prevents your armor from taking durability damage in exchange for souls."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/NaturesWrath.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/NaturesWrath.java new file mode 100644 index 0000000..8c067f0 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/NaturesWrath.java @@ -0,0 +1,169 @@ +package net.crankedpvp.crankedenchants.enchantments.soul; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.SoulModeCache; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.NaturesWrathCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SoulEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.souls.SoulManager; +import net.crankedpvp.crankedenchants.tasks.NaturesWrathTask; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class NaturesWrath extends ArmorIncomingPVPDamageEventEnchant implements SoulEnchant { + + @ConfigValue + private double procChance = 0.02; + @ConfigValue + private int cooldown = 200; + @ConfigValue + private List procMessage = Arrays.asList("&r ", "&c&l** NATURE'S WRATH **", "&c&l- 75 Soul Gems", "&7&n{souls-left}&7 souls left.", "&r "); + @ConfigValue + private String zeusBlockedMessage = "&b&l* ZEUS MASK [&7Blocked Natures Wrath&b&l] *"; + private String luciferSetBlockedMessage = "&5&l* LUCIFER SET [&7Blocked Natures Wrath&5&l] *"; + private final SoulManager soulManager; + + private final ParticleBuilder spellParticle; + private final ParticleBuilder explosionParticle; + private final ParticleBuilder lavaParticle; + + public NaturesWrath() { + super("Natures Wrath", EnchantTier.SOUL, false, 4, GearType.ARMOR, "Passive Soul Enchantment. Temporarily freeze all enemies in a massive area around you,", "pushing them back and dealing massive nature damage."); + this.soulManager = CrankedEnchants.getInstance().getSoulManager(); + this.explosionParticle = new ParticleBuilder(ParticleEffect.EXPLOSION_LARGE) + .setAmount(5) + .setOffsetY(0.5f) + .setSpeed(0.15f); + this.spellParticle = new ParticleBuilder(ParticleEffect.SPELL) + .setAmount(50) + .setOffsetY(0.5f) + .setSpeed(0.15f); + + this.lavaParticle = new ParticleBuilder(ParticleEffect.LAVA) + .setAmount(30) + .setOffsetY(0.5f) + .setSpeed(0.15f); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (!(attacker instanceof Player)) return; + if (event.getCause() != EntityDamageEvent.DamageCause.ENTITY_ATTACK && event.getCause() != EntityDamageEvent.DamageCause.PROJECTILE) return; + if (super.isOnCooldown(victim)) return; + if (Math.random() < this.procChance) { + SoulModeCache soulModeCache = this.soulManager.getSoulModeCache(victim); + + if (!soulModeCache.hasEnoughSouls(this.getSoulCost())) { + this.lavaParticle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayers(victim, 30)); + victim.playSound(victim.getLocation(), Sound.ITEM_BREAK, 0.7f, 0.4f); + Language.OUT_OF_SOULS.send(victim); + super.registerCooldown(victim, this.cooldown); + return; + } + + soulModeCache.getSoulGemBuilder().removeSouls(this.getSoulCost()); + soulModeCache.updateSoulGem(); + + super.sendMessage(victim, this.procMessage, str -> str.replace("{souls-left}", String.valueOf(soulModeCache.getSouls()))); + + int level = enchantInfo.getLevel(); + //int radius = 8 + level * 5; + int radius = level * 3; + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victim); + List affectedPlayers = new ArrayList<>(); + + for (Entity nearbyEntity : victim.getNearbyEntities(radius, radius, radius)) { + if (!(nearbyEntity instanceof Player)) continue; + Player nearbyPlayer = ((Player) nearbyEntity); + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) continue; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) continue; + + + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + + if (fPlayer.getRelationTo(fPlayerNearby).isAtLeast(Relation.TRUCE)) continue; + if (CrankedMasksAPI.hasMaskEquipped( fPlayerNearby.getPlayer(), CrankedMasks.getInstance().getMasksRegister().getMaskFromID("zeus"))) { + fPlayerNearby.getPlayer().sendMessage(zeusBlockedMessage); + continue; + } + + if (Objects.equals(CrankedArmorAPI.getCurrentArmorSet(fPlayerNearby.getPlayer()), CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID("lucifer"))) { + fPlayerNearby.getPlayer().sendMessage(luciferSetBlockedMessage); + continue; + } + + affectedPlayers.add(nearbyPlayer); + this.spellParticle.setLocation(nearbyPlayer.getLocation()).display(PVPUtils.getNearbyPlayers(nearbyPlayer, 30)); + this.explosionParticle.setLocation(nearbyPlayer.getLocation()).display(PVPUtils.getNearbyPlayers(nearbyPlayer, 30)); + CacheUtils.getNaturesWrathCache(nearbyPlayer).applyNaturesWrathEffect(nearbyPlayer, level); + } + + + + NaturesWrathTask naturesWrathTask = new NaturesWrathTask(affectedPlayers, level); + naturesWrathTask.runTaskTimer(CrankedEnchants.getInstance(), 20L, 20L); + + super.registerCooldown(victim, this.cooldown); + } + } + + @EventHandler + public void onPlayerLeaveWhileNatured(PlayerQuitEvent event) { + NaturesWrathCache naturesWrathCache = CacheUtils.getNaturesWrathCache(event.getPlayer()); + if (naturesWrathCache.isAffected()) { + naturesWrathCache.removeNaturesWrathEffect(event.getPlayer()); + } + } + + @EventHandler + public void onPlayerDeathWhileNatured(PlayerDeathEvent event) { + NaturesWrathCache naturesWrathCache = CacheUtils.getNaturesWrathCache(event.getEntity()); + if (naturesWrathCache.isAffected()) { + naturesWrathCache.removeNaturesWrathEffect(event.getEntity()); + } + } + + @EventHandler + public void onPlayerLeaveWhileNatured(PlayerKickEvent event) { + NaturesWrathCache naturesWrathCache = CacheUtils.getNaturesWrathCache(event.getPlayer()); + if (naturesWrathCache.isAffected()) { + naturesWrathCache.removeNaturesWrathEffect(event.getPlayer()); + } + } + + @Override + public int getSoulCost() { + return 75; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Paradox.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Paradox.java new file mode 100644 index 0000000..13b4678 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Paradox.java @@ -0,0 +1,127 @@ +package net.crankedpvp.crankedenchants.enchantments.soul; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.SoulModeCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SoulEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.souls.SoulManager; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +public class Paradox extends ArmorIncomingPVPDamageEventEnchant implements SoulEnchant { + + @ConfigValue + private double procChance = 0.06; + @ConfigValue + private int cooldown = 80; + @ConfigValue + private String message = "&2&l** PARADOX [{healer}] (+{amount}HP) **]"; + private final SoulManager soulManager; + + private ParticleBuilder particle1; + private ParticleBuilder particle2; + private ParticleBuilder particle3; + private ParticleBuilder particle4; + private ParticleBuilder lavaParticle; + + public Paradox() { + super("Paradox", EnchantTier.SOUL, false, 5, GearType.ARMOR, "Passive soul enchantment. Heals all nearby allies in a massive area", "around you for a portion of all damage dealt to you."); + this.soulManager = CrankedEnchants.getInstance().getSoulManager(); + this.initParticles(); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + if (Math.random() < procChance) { + SoulModeCache soulModeCache = soulManager.getSoulModeCache(victim); + + if (!soulModeCache.hasEnoughSouls(this.getSoulCost())) { + this.lavaParticle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayers(victim, 30)); + victim.playSound(victim.getLocation(), Sound.ITEM_BREAK, 0.7f, 0.4f); + Language.OUT_OF_SOULS.send(victim); + super.registerCooldown(victim, cooldown); + return; + } + + int level = enchantInfo.getLevel(); + int radius = 8 + level * 4; + double amountToHeal = event.getDamage() * (double)(level / 10); + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victim); + + soulModeCache.getSoulGemBuilder().removeSouls(5); + soulModeCache.updateSoulGem(); + + for (Entity nearbyEntity : victim.getNearbyEntities(radius, radius, radius)) { + if (nearbyEntity.equals(victim)) continue; + if (!(nearbyEntity instanceof Player)) continue; + Player nearbyPlayer = ((Player) nearbyEntity); + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) continue; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + + if (fPlayer.getRelationTo(fPlayerNearby).isAtMost(Relation.NEUTRAL)) continue; + this.particle1.setLocation(nearbyPlayer.getLocation()).display(PVPUtils.getNearbyPlayers(nearbyPlayer, 30)); + this.particle2.setLocation(nearbyPlayer.getLocation()).display(PVPUtils.getNearbyPlayers(nearbyPlayer, 30)); + this.particle3.setLocation(nearbyPlayer.getLocation()).display(PVPUtils.getNearbyPlayers(nearbyPlayer, 30)); + this.particle4.setLocation(nearbyPlayer.getLocation()).display(PVPUtils.getNearbyPlayers(nearbyPlayer, 30)); + super.sendMessage(nearbyPlayer, message, str -> str.replace("{healer}", victim.getName()).replace("{amount}", String.valueOf(amountToHeal))); + super.getDamageHandler().healEntity(nearbyPlayer, amountToHeal, this.getName()); + } + super.registerCooldown(victim, cooldown); + } + } + + @Override + public int getSoulCost() { + return 5; + } + + private void initParticles() { + this.particle1 = new ParticleBuilder(ParticleEffect.VILLAGER_HAPPY) + .setAmount(20) + .setOffsetY(1.5f) + .setOffsetX(0.8f) + .setOffsetZ(0.8f) + .setSpeed(0.4f); + this.particle2 = new ParticleBuilder(ParticleEffect.VILLAGER_HAPPY) + .setAmount(20) + .setOffsetY(1.5f) + .setOffsetX(-0.8f) + .setOffsetZ(0.8f) + .setSpeed(0.4f); + this.particle3 = new ParticleBuilder(ParticleEffect.VILLAGER_HAPPY) + .setAmount(20) + .setOffsetY(1.5f) + .setOffsetX(0.8f) + .setOffsetZ(-0.8f) + .setSpeed(0.4f); + this.particle4 = new ParticleBuilder(ParticleEffect.VILLAGER_HAPPY) + .setAmount(20) + .setOffsetY(1.5f) + .setOffsetX(-0.8f) + .setOffsetZ(-0.8f) + .setSpeed(0.4f); + this.lavaParticle = new ParticleBuilder(ParticleEffect.LAVA) + .setAmount(30) + .setOffsetY(0.5f) + .setSpeed(0.15f); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Phoenix.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Phoenix.java new file mode 100644 index 0000000..f9c6aff --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Phoenix.java @@ -0,0 +1,95 @@ +package net.crankedpvp.crankedenchants.enchantments.soul; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.cache.SoulModeCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SoulEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.souls.SoulManager; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class Phoenix extends ArmorIncomingPVPDamageEventEnchant implements SoulEnchant { + + @ConfigValue + private int cooldown = 160; + @ConfigValue + private String titleMessage = "&c&l** PHOENIX **"; + @ConfigValue + private String nearbyPlayersMessage = "&c&l*** PHOENIX SOUL (&7{player}, -{soul-cost} souls&c&l) ***"; + @ConfigValue + private String subTitleMessage = "&7You have &n{souls-left}&7 souls left."; + @ConfigValue + private String outOfSoulsMessage = "&c&l** OUT OF SOULS **"; + @ConfigValue + private List procMessage = Arrays.asList("&r ", "&6&l***&r &nPHOENIX SOUL&r &6&l***", "&c&l- {soul-cost} Soul Gems", "&7&n{souls-left}&7 souls left.", "&r "); + private final SoulManager soulManager; + private final ParticleBuilder particle; + + + + public Phoenix() { + super("Phoenix", EnchantTier.SOUL, false, 3, GearType.BOOTS, "Passive soul enchantment. An attack that would normally kill", "you will instead heal you to full HP. Can only be activated", "once every couple minutes."); + this.soulManager = CrankedEnchants.getInstance().getSoulManager(); + this.particle = new ParticleBuilder(ParticleEffect.FLAME) + .setAmount(50) + .setOffsetY(2) + .setSpeed(0.1f); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (victim.isDead()) return; + if (victim.getHealth() <= 0) return; + if (victim.getHealth() - event.getFinalDamage() > 0.0) return; + if (super.isOnCooldown(victim)) return; + + int soulCost = this.getSoulCost(); + SoulModeCache soulModeCache = this.soulManager.getSoulModeCache(victim); + + if (!soulModeCache.hasEnoughSouls(soulCost)) { + super.sendMessage(victim, this.outOfSoulsMessage); + return; + } + + soulModeCache.getSoulGemBuilder().removeSouls(soulCost); + soulModeCache.updateSoulGem(); + super.getDamageHandler().healEntity(victim, victim.getMaxHealth(), this.getName()); + + super.sendMessage(victim, this.procMessage, str -> str.replace("{soul-cost}", String.valueOf(soulCost)).replace("{souls-left}", String.valueOf(soulModeCache.getSouls()))); + TitleUtils.sendTitle(victim, CC.translate(this.titleMessage), CC.translate(this.subTitleMessage.replace("{souls-left}", String.valueOf(soulModeCache.getSouls()))), 3, 30, 3); + victim.playSound(victim.getLocation(), Sound.ENDERDRAGON_GROWL, 1.0f, 1.25f); + + for (Entity nearbyEntity : victim.getNearbyEntities(48.0, 48.0, 48.0)) { + if (!(nearbyEntity instanceof Player)) continue; + Player nearbyPlayer = (Player) nearbyEntity; + super.sendMessage(nearbyPlayer, this.nearbyPlayersMessage, str -> str.replace("{player}", victim.getName()).replace("{soul-cost}", String.valueOf(soulCost))); + nearbyPlayer.playSound(victim.getLocation(), Sound.ENDERDRAGON_GROWL, 1.0f, 1.25f); + } + + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayers(victim, 30)); + + super.registerCooldown(victim, this.cooldown); + + } + + @Override + public int getSoulCost() { + return ThreadLocalRandom.current().nextInt(500, 8000); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Teleblock.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Teleblock.java new file mode 100644 index 0000000..16466ce --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/soul/Teleblock.java @@ -0,0 +1,102 @@ +package net.crankedpvp.crankedenchants.enchantments.soul; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.SoulModeCache; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.TeleblockCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.BowEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SoulEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.struct.souls.SoulManager; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.objecthunter.exp4j.Expression; +import net.objecthunter.exp4j.ExpressionBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; + +public class Teleblock extends BowEventEnchant implements Reloadable, SoulEnchant { + + @ConfigValue + private String soulCostFormula = "level * 6"; + private Expression soulCostExpression; + private final SoulManager soulManager; + + public Teleblock() { + super("Teleblock", EnchantTier.SOUL, 5, GearType.BOW, "Active soul enchant. Your bow is enchanted with enderpearl blocking magic,", "damaged players will be unable to use enderpearls for up to 20 seconds,", "and will lose up to 15 enderpearls from their inventory."); + this.reloadValues(); + this.soulManager = CrankedEnchants.getInstance().getSoulManager(); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, Player victim, Player attacker, Arrow arrow, EnchantedItemBuilder enchantedItemBuilder) { + if (!this.soulManager.isInSoulMode(attacker)) return; + + int level = enchantedItemBuilder.getEnchantmentLevel(this); + int soulCost = (int) this.soulCostExpression.setVariable("level", level).evaluate(); + SoulModeCache soulModeCache = this.soulManager.getSoulModeCache(attacker); + + if (!soulModeCache.hasEnoughSouls(soulCost)) return; + + TeleblockCache teleblockCache = CacheUtils.getTeleblockCache(victim); + + if (teleblockCache.isTeleblockActive()) return; + + soulModeCache.getSoulGemBuilder().removeSouls(soulCost); + soulModeCache.updateSoulGem(); + teleblockCache.procTeleblock(level); + PlayerInventory victimInventory = victim.getInventory(); + + int pearlsToDestroy = level * 3; + for (int i = 0; i < victimInventory.getSize(); ++i) { + if (!(victimInventory.getItem(i) == null || victimInventory.getItem(i).getType() != Material.ENDER_PEARL || victimInventory.getItem(i).hasItemMeta() && victimInventory.getItem(i).getItemMeta().hasDisplayName())) { + int amount = victimInventory.getItem(i).getAmount(); + if (amount <= pearlsToDestroy) { + pearlsToDestroy -= amount; + victimInventory.setItem(i, new ItemStack(Material.AIR)); + } else { + ItemStack invPearl = victimInventory.getItem(i); + invPearl.setAmount(invPearl.getAmount() - pearlsToDestroy); + victimInventory.setItem(i, invPearl); + pearlsToDestroy = 0; + } + } + if (pearlsToDestroy <= 0) break; + } + } + + @EventHandler + public void onEnderpearlThrow(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (!event.hasItem()) return; + if (event.getItem().getType() != Material.ENDER_PEARL) return; + + TeleblockCache teleblockCache = CacheUtils.getTeleblockCache(event.getPlayer()); + + if (!teleblockCache.isTeleblockActive()) return; + + event.setCancelled(true); + event.setUseItemInHand(Event.Result.DENY); + event.getPlayer().setItemInHand(event.getItem()); + } + + @Override + public void reloadValues() { + this.soulCostExpression = new ExpressionBuilder(this.soulCostFormula).variable("level").build(); + } + + @Override + public int getSoulCost() { + return 6; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Angelic.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Angelic.java new file mode 100644 index 0000000..a69950d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Angelic.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.tasks.AngelicTask; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Angelic extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.004; + @ConfigValue + private int cooldown = 25; + @ConfigValue + private int healAmount = 1; + @ConfigValue + private long timesItHeals = 4; + + public Angelic() { + super("Angelic", EnchantTier.ULTIMATE, true, 5, GearType.ARMOR, "Heals health over time whenever", "damaged by an enemy."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance * enchantInfo.getLevel()) { + new AngelicTask(victim, this.healAmount, this.timesItHeals).runTaskTimer(CrankedEnchants.getInstance(), 0L, 20L); + super.registerCooldown(victim, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ArrowBreak.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ArrowBreak.java new file mode 100644 index 0000000..4ce34d9 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ArrowBreak.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +public class ArrowBreak extends Enchantment { + + public ArrowBreak(String name, EnchantTier tier, boolean stackable, int max, GearType type, String... description) { + super(name, tier, stackable, max, type, description); + } + + @EventHandler + public void onIncomingArrowDamage(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getDamage() <= 0) return; + if (!(event.getEntity() instanceof Player) || !(event.getDamager() instanceof Arrow)) return; + + Player victim = (Player) event.getEntity(); + ItemStack itemStack = victim.getItemInHand(); + + if (itemStack == null) return; + if (!this.getType().getItems().contains(itemStack.getType())) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + + if (super.isOnCooldown(victim)) return; + event.setCancelled(true); + super.registerCooldown(victim, 20); + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ArrowDeflect.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ArrowDeflect.java new file mode 100644 index 0000000..e44e035 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ArrowDeflect.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Sound; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +public class ArrowDeflect extends Enchantment implements Reloadable { + + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 100; + @ConfigValue + private double particleYoffset = 1.0; + @ConfigValue + private double particleSpeed = 0.1; + + public ArrowDeflect() { + super("Arrow Deflect", EnchantTier.ULTIMATE, false, 4, GearType.ARMOR, "Prevents you from being damaged by enemy arrows", "more often than once every level x 400 milliseconds."); + } + + @EventHandler + public void onIncomingArrowDamage(EntityDamageByEntityEvent event) { + if (!(event.getDamager() instanceof Arrow)) return; + if (!(event.getEntity() instanceof Player)) return; + + Player victim = ((Player) event.getEntity()); + + if (!CrankedEnchantsAPI.hasEnchantment(victim, this)) return; + if (super.isOnCooldown(victim)) return; + event.setCancelled(true); + super.registerCooldown(victim, 20); + victim.playSound(victim.getLocation(), Sound.ITEM_BREAK, 0.7f, 0.2f); + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 30)); + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.SPELL) + .setAmount(particleAmount) + .setOffsetY((float) particleYoffset) + .setSpeed((float) particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Assassin.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Assassin.java new file mode 100644 index 0000000..ae99f17 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Assassin.java @@ -0,0 +1,58 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import lombok.Getter; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +@Getter +public class Assassin extends WeaponDamageEventEnchant { + + @ConfigValue + private double twoBlocksPerLevel = 1.0; + + @ConfigValue + private double oneBlockPerLevel = 1.6; + + @ConfigValue + private double threeQuartersBlocksPerLevel = 2.0; + + @ConfigValue + private double oneHalfBlocksPerLevel = 3.0; + + @ConfigValue + private double oneQuarterBlocksPerLevel = 5.0; + + public Assassin() { + super("Assassin", EnchantTier.ULTIMATE, 5, GearType.SWORD, "The closer you are to your enemy,", "the more damage you deal (up to 1.25x).", "However, if you are more than 2 blocks away,", "you will deal LESS damage than normal."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + final double distance = victim.getLocation().distance(attacker.getLocation()); + + if (distance < 0.25) { + super.getDamageHandler().increaseDamage(oneQuarterBlocksPerLevel * level, event, this.getName()); + return; + } + if (distance < 0.5) { + super.getDamageHandler().increaseDamage(oneHalfBlocksPerLevel * level, event, this.getName()); + return; + } + if (distance < 0.75) { + super.getDamageHandler().increaseDamage(oneQuarterBlocksPerLevel * level, event, this.getName()); + return; + } + if (distance < 1.0) { + super.getDamageHandler().increaseDamage(oneBlockPerLevel * level, event, this.getName()); + return; + } + if (distance < 2.0) { + super.getDamageHandler().increaseDamage(twoBlocksPerLevel * level, event, this.getName()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Bleed.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Bleed.java new file mode 100644 index 0000000..969abd8 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Bleed.java @@ -0,0 +1,74 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.BleedStacksCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Effect; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class Bleed extends WeaponDamageEventEnchant { + + @ConfigValue + public double procChance = 0.006; + + public Bleed() { + super("Bleed", EnchantTier.ULTIMATE, 6, GearType.AXE, "Applies bleed stacks to enemies that", "decrease their movement speed."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + int deepWoundsLevel = CrankedEnchantsAPI.hasEnchantment(attacker, "deepwounds") ? CrankedEnchantsAPI.getEnchantmentLevel(attacker, "deepwounds") : 0; + if (Math.random() < (this.procChance * (level + deepWoundsLevel))) { + Player victimPlayer = (Player) victim; + BleedStacksCache victimBleedStack = CacheUtils.getBleedStackCache(victimPlayer); + + if (victimBleedStack.getLastBleedStackTime() + 30000 < System.currentTimeMillis()) { + victimBleedStack.updateLastBleedStackTime(); + victimBleedStack.resetBleedStack(); + return; + } + + victim.addPotionEffect( + new PotionEffect(PotionEffectType.SLOW, + (victimBleedStack.getBleedStack() + 1) * 20, + Math.min(victimBleedStack.getBleedStack() - 1, 1)), + true + ); + + victim.getWorld().playEffect(victim.getEyeLocation(), Effect.STEP_SOUND, Material.REDSTONE_BLOCK); + victimBleedStack.incrementBleedStack(); + victimBleedStack.updateLastBleedStackTime(); + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victimPlayer); + for (Entity entity : victim.getNearbyEntities(7, 7, 7)) { + if (!(entity instanceof Player)) continue; + Player nearbyPlayer = (Player) entity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) continue; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) continue; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtLeast(Relation.TRUCE)) continue; + Enchantment enchantment = CrankedEnchants.getInstance().getEnchantRegister().getEnchantmentFromID("bloodlust"); + if (CrankedEnchantsAPI.hasEnchantment(nearbyPlayer, enchantment)) + super.getDamageHandler().healEntity(nearbyPlayer, 2, "Blood Lust"); + } + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Blessed.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Blessed.java new file mode 100644 index 0000000..1058a95 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Blessed.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Blessed extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.2; + @ConfigValue + private String message = "&e&l** BLESSED **"; + + public Blessed() { + super("Blessed", EnchantTier.ULTIMATE, 4, GearType.AXE, "Has a chance of removing debuffs."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < (this.procChance * level)) { + super.sendMessage(attacker, this.message); + attacker.playSound(attacker.getLocation(), Sound.SPLASH, 1.2f, 2.0f); + PotionEffectUtils.bless(attacker); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Block.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Block.java new file mode 100644 index 0000000..3fa772d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Block.java @@ -0,0 +1,32 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponIncomingDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Block extends WeaponIncomingDamageEventEnchant { + + @ConfigValue + private double procChance = 0.045; + @ConfigValue + private int cooldown = 10; + + public Block() { + super("Block", EnchantTier.ULTIMATE, 3, GearType.SWORD, "A chance to increase damage and redirect an attack."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, int level) { + if (super.isOnCooldown(victim)) return; + + if (Math.random() < this.procChance * level) { + //super.getDamageHandler().damage(attacker, event.getDamage(EntityDamageEvent.DamageModifier.BASE), this.getName()); + super.getDamageHandler().cancelDamage(event, this.getName()); + super.registerCooldown(victim, this.cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Cleave.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Cleave.java new file mode 100644 index 0000000..7f7464a --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Cleave.java @@ -0,0 +1,44 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Cleave extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.05; + @ConfigValue + private int damageAmount = 3; + + public Cleave() { + super("Cleave", EnchantTier.ULTIMATE, 7, GearType.AXE, "Damages players within a radius that", "increases with the level of enchant."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(attacker); + attacker.getNearbyEntities(level, 10.0, level).forEach(entity -> { + if (!(entity instanceof Player)) return; + Player nearbyPlayer = (Player) entity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) return; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtLeast(Relation.TRUCE)) return; + super.getDamageHandler().damage(nearbyPlayer, damageAmount, this.getName()); + }); + + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/CreeperArmor.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/CreeperArmor.java new file mode 100644 index 0000000..cb2f9f9 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/CreeperArmor.java @@ -0,0 +1,22 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorPlayerDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageEvent; + +public class CreeperArmor extends ArmorPlayerDamageEventEnchant { + + public CreeperArmor() { + super("Creeper Armor", EnchantTier.ULTIMATE, false,1, GearType.ARMOR, "Wearer gains immunity to explosions."); + } + + + @Override + public void runOnDamage(EntityDamageEvent event, Player player, EnchantInfo enchantInfo) { + if (event.getCause() != EntityDamageEvent.DamageCause.BLOCK_EXPLOSION && event.getCause() != EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) return; + event.setCancelled(true); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Detonate.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Detonate.java new file mode 100644 index 0000000..fe4b89c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Detonate.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.BlockBreakEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.utils.DetonateUtils; +import org.bukkit.Material; +import org.bukkit.event.block.BlockBreakEvent; + +import java.util.Arrays; +import java.util.List; + +public class Detonate extends BlockBreakEventEnchant { + + public static List trenchBlackListedBlocks = Arrays.asList(Material.AIR, Material.BEDROCK, Material.MOB_SPAWNER, Material.WATER, + Material.LAVA, Material.STATIONARY_WATER, + Material.STATIONARY_LAVA, Material.SIGN, Material.GLOWSTONE, Material.LADDER, Material.WALL_SIGN, Material.SIGN_POST, Material.SPONGE, Material.CHEST, Material.ENDER_CHEST, + Material.TRAPPED_CHEST, Material.PISTON_BASE, Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE, Material.PISTON_STICKY_BASE, Material.DISPENSER, Material.ENDER_PORTAL_FRAME, + Material.ENDER_PORTAL, Material.PORTAL, Material.SUGAR_CANE, Material.SUGAR_CANE_BLOCK, Material.JUKEBOX, Material.ENCHANTMENT_TABLE, Material.COBBLESTONE, Material.OBSIDIAN); + + public Detonate() { + super("Detonate", EnchantTier.ULTIMATE, 5, GearType.PICKAXE_SHOVEL, "Mine blocks in a large radius."); + } + + + @Override + public void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder) { + if (event.isCancelled()) return; + int level = enchantedItemBuilder.getEnchantmentLevel(this); + DetonateUtils.trenchEffect(event.getBlock(), level, event.getPlayer(), trenchBlackListedBlocks); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Disintegrate.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Disintegrate.java new file mode 100644 index 0000000..8ed46de --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Disintegrate.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +public class Disintegrate extends WeaponDamageEventEnchant { + + public Disintegrate() { + super("Disintegrate", EnchantTier.ULTIMATE, 4, GearType.SWORD, "Chance to deal double durability damage to all enemy armor", "with every attack."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + Player playerVictim = ((Player) victim); + + for (ItemStack itemStack : playerVictim.getInventory().getArmorContents()) { + if (!ItemUtils.isArmor(itemStack)) continue; + itemStack.setDurability((short) (itemStack.getDurability() + 1)); + } + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Dodge.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Dodge.java new file mode 100644 index 0000000..4a19e8d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Dodge.java @@ -0,0 +1,64 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +public class Dodge extends ArmorIncomingPVPDamageEventEnchant implements Reloadable { + + @ConfigValue + public double procChance = 0.0008; + @ConfigValue + public double procChanceWhenSneaking = 0.002; + @ConfigValue + public int cooldown = 5; + @ConfigValue + private String message = "&e*DODGED*"; + + public ParticleBuilder particle; + + @ConfigValue + public int particleAmount = 50; + @ConfigValue + public double particleYoffset = 1.0; + @ConfigValue + public double particleSpeed = 0.1; + + public Dodge() { + super("Dodge", EnchantTier.ULTIMATE, false, 5, GearType.ARMOR, "Has a chance to dodge physical", "attacks, increased chance when sneaking."); + this.reloadValues(); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (this.isOnCooldown(victim)) return; + + double chance = victim.isSneaking() ? this.procChanceWhenSneaking * enchantInfo.getLevel() : this.procChance * enchantInfo.getLevel(); + + if (Math.random() < chance) { + super.getDamageHandler().cancelDamage(event, this.getName()); + super.sendMessage(victim, this.message); + victim.getWorld().playSound(victim.getLocation(), Sound.BAT_TAKEOFF, 1.0f, 0.75f); + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 30)); + super.registerCooldown(victim, this.cooldown); + } + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.CLOUD) + .setAmount(this.particleAmount) + .setOffsetY((float) this.particleYoffset) + .setSpeed((float) this.particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Dominate.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Dominate.java new file mode 100644 index 0000000..d728857 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Dominate.java @@ -0,0 +1,75 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.DominateCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +public class Dominate extends WeaponDamageEventEnchant implements Reloadable { + + @ConfigValue + private double procChance = 0.04; + @ConfigValue + private int cooldown = 30; + @ConfigValue + private String message = "&c&l* DOMINATED [-{dmg-reduction}% DMG for {time}s] *"; + + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 50; + @ConfigValue + private double particleYoffset = 0.7; + @ConfigValue + private double particleSpeed = 0.1; + + public Dominate() { + super("Dominate", EnchantTier.ULTIMATE, 4, GearType.SWORD, "Chance to weaken enemy players on hit, causing them", "to deal (level x 5%) less damage for (level x 2) seconds."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (super.isOnCooldown(attacker)) return; + if (Math.random() < this.procChance) { + if (!(victim instanceof Player)) return; + Player victimPlayer = ((Player) victim); + DominateCache dominateCache = CacheUtils.getDominateCache(victimPlayer); + dominateCache.procDominate(level); + super.sendMessage(victim, this.message, str -> str + .replace("{dmg-reduction}", String.valueOf(dominateCache.getDamageReduction())) + .replace("{time}", String.valueOf(dominateCache.getDuration())) + ); + this.particle.setLocation(victimPlayer.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victimPlayer, 30)); + super.registerCooldown(attacker, this.cooldown); + } + } + + @EventHandler + public void onDamageWhileDominated(EntityDamageByEntityEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!(event.getDamager() instanceof Player)) return; + Player damager = ((Player) event.getDamager()); + DominateCache dominateCache = CacheUtils.getDominateCache(damager); + if (!dominateCache.isDominateActive()) return; + super.getDamageHandler().reduceDamage(dominateCache.getDamageReduction(), event, this.getName()); + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.ENCHANTMENT_TABLE) + .setAmount(this.particleAmount) + .setOffsetY((float) this.particleYoffset) + .setSpeed((float) this.particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/EnderWalker.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/EnderWalker.java new file mode 100644 index 0000000..fa05737 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/EnderWalker.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageEvent; + +public class EnderWalker extends Enchantment { + + public EnderWalker() { + super("Ender Walker", EnchantTier.ULTIMATE, false, 5, GearType.BOOTS, "Wither and Poison do not injur and have a chance", "to heal at high levels. "); + } + + @EventHandler + public void onDamageByPoisonAndWither(EntityDamageEvent event) { + if (event.getCause() != EntityDamageEvent.DamageCause.WITHER && event.getCause() != EntityDamageEvent.DamageCause.POISON) return; + if (!(event.getEntity() instanceof Player)) return; + + Player player = ((Player) event.getEntity()); + + if (!player.isValid()) return; + if (!CrankedEnchantsAPI.hasEnchantment(player, this)) return; + + super.getDamageHandler().cancelDamage(event, this.getName()); + + if (CrankedEnchantsAPI.getEnchantmentLevel(player, this) < 4) return; + + super.getDamageHandler().healEntity(player, 1, this.getName()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Enrage.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Enrage.java new file mode 100644 index 0000000..671fffc --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Enrage.java @@ -0,0 +1,49 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Enrage extends WeaponDamageEventEnchant { + + @ConfigValue + private double hpPercent75 = 10; + @ConfigValue + private double hpPercent50 = 10; + @ConfigValue + private double hpPercent25 = 10; + + + public Enrage() { + super("Enrage", EnchantTier.ULTIMATE, 3, GearType.SWORD, "The lower your HP is, the more damage you deal."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + double hpPercent = attacker.getHealth() / attacker.getMaxHealth(); + double multi = 0; + if (hpPercent <= 0.75D) + multi += this.hpPercent75; + if (hpPercent <= 0.5D) + multi += this.hpPercent50; + if (hpPercent <= 0.25D) + multi += this.hpPercent25; + + /* + if (hpPercent <= 0.75D) + multi += 10; + if (hpPercent <= 0.5D) + multi += 10; + if (hpPercent <= 0.25D) + multi += 10; + + */ + + if (multi == 0) return; + super.getDamageHandler().increaseDamage(multi, event, this.getName()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Ghost.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Ghost.java new file mode 100644 index 0000000..224f367 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Ghost.java @@ -0,0 +1,12 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; + +public class Ghost extends Enchantment { + + public Ghost() { + super("Ghost", EnchantTier.ULTIMATE, false, 1, GearType.ARMOR, "Invisible to /near lookups"); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Guardians.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Guardians.java new file mode 100644 index 0000000..f1f6cc9 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Guardians.java @@ -0,0 +1,76 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.custommobs.EntityTypes; +import net.crankedpvp.crankedenchants.struct.custommobs.GuardiansIronGolem; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityTargetLivingEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +public class Guardians extends ArmorIncomingPVPDamageEventEnchant implements Reloadable { + + @ConfigValue + private double procChance = 0.005; + @ConfigValue + private int cooldown = 200; + + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 50; + @ConfigValue + private double particleYoffset = 1.0; + @ConfigValue + private double particleSpeed = 0.1; + + public Guardians() { + super("Guardians", EnchantTier.ULTIMATE, false, 10, GearType.ARMOR, "Chance to spawn iron golems to assist", "you in combat and watch over you."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (!(attacker instanceof Player)) return; + if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance * enchantInfo.getLevel()) { + Player target = (Player) attacker; + Entity entity = EntityTypes.spawnEntity(new GuardiansIronGolem(victim.getWorld(), victim, target), victim.getLocation()); + victim.playSound(victim.getLocation(), Sound.IRONGOLEM_DEATH, 1.0F, 0.55F); + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 30)); + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), entity::remove, 400L); + super.registerCooldown(victim, cooldown); + } + } + + @EventHandler + public void onEntityTargetPlayer(EntityTargetLivingEntityEvent event) { + if (event.getEntityType() != EntityType.IRON_GOLEM) return; + if (!(event.getTarget() instanceof Player)) return; + if (!event.getEntity().hasMetadata("guardian-target")) return; + String uuid = String.valueOf(event.getEntity().getMetadata("guardian-target").get(0).asString()); + if (!uuid.equals(event.getTarget().getUniqueId().toString())) event.setCancelled(true); + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.SPELL_WITCH) + .setAmount(particleAmount) + .setOffsetY((float) particleYoffset) + .setSpeed((float) particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Heavy.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Heavy.java new file mode 100644 index 0000000..16206f2 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Heavy.java @@ -0,0 +1,22 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Heavy extends ArmorIncomingPVPDamageEventEnchant { + + public Heavy() { + super("Heavy", EnchantTier.ULTIMATE, true, 5, GearType.ARMOR, "Decreases damage from enemy bows by 2% per level."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + //TODO: this won't work, needs fixing + //super.getDamageHandler().reduceDamage(enchantInfo.getLevel() * 2, event, this.getName()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/IceAspect.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/IceAspect.java new file mode 100644 index 0000000..d7e5b4b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/IceAspect.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.events.SlownessEnchantProcEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SlownessEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class IceAspect extends WeaponDamageEventEnchant implements SlownessEnchant { + + @ConfigValue + private double procChance = 0.003; + @ConfigValue + private int slownessAmplifier = 1; + + public IceAspect() { + super("Ice Aspect", EnchantTier.ELITE, 3, GearType.SWORD, "A chance of causing the slowness", "effect to your enemy."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance * level) { + + SlownessEnchantProcEvent slownessEnchantProcEvent = new SlownessEnchantProcEvent(attacker, victim, this, level); + Bukkit.getPluginManager().callEvent(slownessEnchantProcEvent); + + if (event.isCancelled()) return; + victim.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 60, slownessAmplifier, true)); + } + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Implants.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Implants.java new file mode 100644 index 0000000..e30a818 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Implants.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.FoodLevelChangeEvent; + +public class Implants extends ArmorEquipEventEnchant { + + public Implants() { + super("Implants", EnchantTier.ULTIMATE, false, 3, GearType.HELMET, "Restores the wearer's health and", "hunger while moving."); + } + + @EventHandler + public void onFoodLoss(FoodLevelChangeEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (!CrankedEnchantsAPI.hasEnchantment(player, this)) return; + event.setCancelled(true); + player.setFoodLevel(20); + player.setSaturation((float) 5.0); + super.getDamageHandler().healEntity(player, 1.0, this.getName()); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + player.setFoodLevel(20); + player.setSaturation((float) 5.0); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Lucky.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Lucky.java new file mode 100644 index 0000000..e6bb406 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Lucky.java @@ -0,0 +1,21 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Lucky extends ArmorIncomingPVPDamageEventEnchant { + + public Lucky() { + super("Lucky", EnchantTier.ULTIMATE, true, 10, GearType.ARMOR, "You will find yourself more lucky in all situations."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Metaphysical.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Metaphysical.java new file mode 100644 index 0000000..6cdd0fa --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Metaphysical.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.SlownessEnchantProcEvent; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +public class Metaphysical extends Enchantment { + + @ConfigValue + public double procChance = 0.23; + @ConfigValue + private String message = "&8&l** METAPHYSICAL (&8{blocked-enchantment} blocked&l) **"; + + public Metaphysical() { + super("Metaphysical", EnchantTier.ULTIMATE, false, 4, GearType.BOOTS, "A chance to resist the slowness given by enemy Trap, Snare, and Pummel enchantments.", "At max level, you will only be affected approx. 10% of the time."); + } + + @EventHandler + public void runEnchantDamageProcEvent(SlownessEnchantProcEvent event) { + if (!(event.getVictim() instanceof Player)) return; + if (CrankedEnchantsAPI.hasEnchantment(((Player) event.getVictim()), this)) { + if (Math.random() < procChance * CrankedEnchantsAPI.getEnchantmentLevel((Player) event.getVictim(), this)) { + event.setCancelled(true); + super.sendMessage(event.getVictim(), message, str -> str.replace("{blocked-enchantment}", event.getEnchantment().getName())); + } + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ObsidianShield.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ObsidianShield.java new file mode 100644 index 0000000..a765007 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/ObsidianShield.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class ObsidianShield extends ArmorEquipEventEnchant { + + public ObsidianShield() { + super("Obsidian Shield", EnchantTier.ULTIMATE, false, 1, GearType.ARMOR, "Gives permanent fire resistance."); + } + + @Override + public void runArmorEquipEvent(Player player, int level) { + player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 0), true); + Language.EQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Fire Resistance") + .replace("{effect-level}", "I") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } + + @Override + public void runArmorUnEquipEvent(Player player, int level) { + player.removePotionEffect(PotionEffectType.FIRE_RESISTANCE); + Language.UNEQUIP_POTION_ENCHANT.send(player, + str -> str + .replace("{effect}", "Fire Resistance") + .replace("{enchant}", this.getName()) + .replace("{enchant-level}", RomanNumeral.convertToRoman(level)) + ); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Spirits.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Spirits.java new file mode 100644 index 0000000..3965b75 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Spirits.java @@ -0,0 +1,54 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Sound; +import org.bukkit.entity.Creature; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityTargetLivingEntityEvent; +import org.bukkit.metadata.FixedMetadataValue; + +public class Spirits extends ArmorIncomingPVPDamageEventEnchant { + + public Spirits() { + super("Spirits", EnchantTier.ULTIMATE,false, 10, GearType.ARMOR, "Chance to spawn blazes that attack", "your target."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if (!(attacker instanceof Player)) return; + + if (Math.random() < 0.03) { + victim.playSound(victim.getLocation(), Sound.BLAZE_BREATH, 1.0F, 0.5F); + Player attackerPlayer = ((Player) attacker); + + for (int i = 0; i < 3; i++) { + Creature blaze = (Creature) victim.getWorld().spawnEntity(victim.getLocation(), EntityType.BLAZE); + blaze.setTarget(attacker); + blaze.setCustomName(CC.translate("&e" + victim.getName() + "'s Blaze")); + blaze.setMetadata("spirits-target", new FixedMetadataValue(CrankedEnchants.getInstance(), attackerPlayer.getUniqueId())); + } + + super.registerCooldown(victim, 200); + } + } + + @EventHandler + public void onEntityTargetPlayer(EntityTargetLivingEntityEvent event) { + if (event.getEntityType() != EntityType.BLAZE) return; + if (!(event.getTarget() instanceof Player)) return; + if (!event.getEntity().hasMetadata("spirits-target")) return; + String uuid = String.valueOf(event.getEntity().getMetadata("spirits-target").get(0).asString()); + if (!uuid.equals(event.getTarget().getUniqueId().toString())) event.setCancelled(true); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Tank.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Tank.java new file mode 100644 index 0000000..722a0b0 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Tank.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Tank extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double damageNegation = 1.85; + + public Tank() { + super("Tank", EnchantTier.ULTIMATE, true, 4, GearType.ARMOR, "Decreases damage from enemy axes by", "x1.85 per level"); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (!(attacker instanceof Player)) return; + if (((Player) attacker).getItemInHand() == null) return; + if (!ItemUtils.isAxe(((Player) attacker).getItemInHand())) return; + super.getDamageHandler().reduceDamage(damageNegation * enchantInfo.getLevel(), event, this.getName()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Valor.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Valor.java new file mode 100644 index 0000000..7d461fb --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/ultimate/Valor.java @@ -0,0 +1,58 @@ +package net.crankedpvp.crankedenchants.enchantments.ultimate; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Silenceable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Effect; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; +import xyz.xenondevs.particle.data.texture.BlockTexture; + +public class Valor extends ArmorIncomingPVPDamageEventEnchant implements Silenceable, Reloadable { + + @ConfigValue + private double damageNegation = 1.125; + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 1000; + @ConfigValue + private double particleYoffset = 0.7; + @ConfigValue + private double particleSpeed = 0.05; + + public Valor() { + super("Valor", EnchantTier.ULTIMATE, true, 5, GearType.ARMOR, "Reduces incoming damage from enemies that", "are wielding a sword by up to 22.5%"); + this.reloadValues(); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (!(attacker instanceof Player)) return; + Player attackerPlayer = ((Player) attacker); + if (attackerPlayer.getItemInHand() == null) return; + if (!ItemUtils.isSword(attackerPlayer.getItemInHand())) return; + super.getDamageHandler().reduceDamage(damageNegation * enchantInfo.getLevel(), event, this.getName()); + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 20)); + victim.playEffect(victim.getLocation(), Effect.STEP_SOUND, Material.GOLD_BLOCK); + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.BLOCK_DUST) + .setParticleData(new BlockTexture(Material.GOLD_BLOCK)) + .setAmount(particleAmount) + .setOffsetY((float) particleYoffset) + .setSpeed((float) particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Berserk.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Berserk.java new file mode 100644 index 0000000..f1a5722 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Berserk.java @@ -0,0 +1,33 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +public class Berserk extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.03; + + public Berserk() { + super("Berserk", EnchantTier.UNIQUE, 5, GearType.AXE, "A chance of strength and mining fatigue."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + if (Math.random() < procChance * level) { + if (!attacker.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) + PotionEffectUtils.addPotionEffect(attacker, PotionEffectType.INCREASE_DAMAGE, 1, "berserk", level * 20); + + //attacker.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, level * 20, 1)); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Commander.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Commander.java new file mode 100644 index 0000000..2219012 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Commander.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.GameMode; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +public class Commander extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.04; + @ConfigValue + private int cooldown = 20; + @ConfigValue + private int range = 6; + + public Commander() { + super("Commander", EnchantTier.UNIQUE, false, 5, GearType.ARMOR, "Nearby allies are given haste."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance * enchantInfo.getLevel()) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victim); + victim.getNearbyEntities(range, range, range).forEach(entity -> { + if (!(entity instanceof Player)) return; + Player nearbyPlayer = (Player) entity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) return; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtMost(Relation.NEUTRAL)) return; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.FAST_DIGGING, 1, "commander_haste", enchantInfo.getLevel() * 20); + //nearbyPlayer.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 80, 1, true)); + }); + super.registerCooldown(victim, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Curse.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Curse.java new file mode 100644 index 0000000..ab82ae4 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Curse.java @@ -0,0 +1,37 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +public class Curse extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.4; + @ConfigValue + private int cooldown = 50; + + public Curse() { + super("Curse", EnchantTier.UNIQUE, false, 5, GearType.CHESTPLATE, "Gives strength, slowness and resistance at low hp."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (victim.getHealth() > 6.0) return; + if (super.isOnCooldown(victim)) return; + if (Math.random() < procChance) { + if (victim.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.INCREASE_DAMAGE, 2, "Curse", enchantInfo.getLevel()); + if (!victim.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.DAMAGE_RESISTANCE, 2, "Curse", enchantInfo.getLevel()); + super.registerCooldown(victim, cooldown); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/DeepWounds.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/DeepWounds.java new file mode 100644 index 0000000..1276a9a --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/DeepWounds.java @@ -0,0 +1,12 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; + +public class DeepWounds extends Enchantment { + + public DeepWounds() { + super("Deep Wounds", EnchantTier.UNIQUE, false, 3, GearType.WEAPON, "Increases the chance of you giving the bleed effect."); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/EnderShift.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/EnderShift.java new file mode 100644 index 0000000..c1235dc --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/EnderShift.java @@ -0,0 +1,69 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.Effect; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +public class EnderShift extends ArmorIncomingPVPDamageEventEnchant implements Reloadable { + + @ConfigValue + private double procChance = 0.4; + @ConfigValue + private int cooldown = 70; + @ConfigValue + private String message = "&d&l(!) &dYou were about to die so you entered the Ender dimension, escape to safety!"; + + private ParticleBuilder particle; + + @ConfigValue + private int particleAmount = 50; + @ConfigValue + private double particleYoffset = 1.0; + @ConfigValue + private double particleSpeed = 0.1; + + public EnderShift() { + super("Ender Shift", EnchantTier.UNIQUE, false, 3, GearType.BOOTS_AND_HELMET, "Gives speed and health boost when on low health", "for a temporary amount of time."); + this.reloadValues(); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (victim.getHealth() - event.getFinalDamage() > 3) return; + if (super.isOnCooldown(victim)) return; + + if (Math.random() < procChance) { + victim.sendMessage(CC.translate(message)); + super.getDamageHandler().cancelDamage(event, this.getName()); + victim.playSound(victim.getLocation(), Sound.ENDERDRAGON_GROWL, 1.0F, 0.5F); + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.SPEED, enchantInfo.getLevel() + 1, "endershift_speed", (enchantInfo.getLevel() + 1) * 20); + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.ABSORPTION, enchantInfo.getLevel() + 1, "endershift_absorption", enchantInfo.getLevel() * 20); + super.registerCooldown(victim, cooldown); + this.particle.setLocation(victim.getLocation()).display(PVPUtils.getNearbyPlayersExceptPlayer(victim, 30)); + victim.playEffect(victim.getLocation(), Effect.STEP_SOUND, Material.ICE); + } + } + + @Override + public void reloadValues() { + this.particle = new ParticleBuilder(ParticleEffect.SPELL_WITCH) + .setAmount(particleAmount) + .setOffsetY((float) particleYoffset) + .setSpeed((float) particleSpeed); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/FeatherWeight.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/FeatherWeight.java new file mode 100644 index 0000000..141b1a4 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/FeatherWeight.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +public class FeatherWeight extends WeaponDamageEventEnchant { + + + public FeatherWeight() { + super("Feather Weight", EnchantTier.UNIQUE, 3, GearType.SWORD, "Has a chance to give a burst of haste"); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (attacker.hasPotionEffect(PotionEffectType.FAST_DIGGING)) return; + + if (Math.random() <= level * 0.2) { + PotionEffectUtils.addPotionEffect(attacker, PotionEffectType.FAST_DIGGING, level - 1, "featherweight", level* 20); + //attacker.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, level* 20, level - 1), true); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Lifebloom.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Lifebloom.java new file mode 100644 index 0000000..5648ba9 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Lifebloom.java @@ -0,0 +1,43 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorPlayerDeathEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.PlayerDeathEvent; + +public class Lifebloom extends ArmorPlayerDeathEventEnchant { + + @ConfigValue + private int cooldown = 100; + @ConfigValue + private int range = 20; + + public Lifebloom() { + super("Lifebloom", EnchantTier.UNIQUE, false, 5, GearType.LEGGINGS, "Completely heals allies and truces on your death."); + } + + @Override + public void runEntityDeathEvent(PlayerDeathEvent event, Player killer, Player victim, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(victim); + victim.getNearbyEntities(range, range, range).forEach(entity -> { + if (!(entity instanceof Player)) return; + Player nearbyPlayer = (Player) entity; + if (nearbyPlayer.getGameMode() != GameMode.SURVIVAL) return; + if (!PVPUtils.canPvPInRegion(nearbyPlayer)) return; + FPlayer fPlayerNearby = FPlayers.getInstance().getByPlayer(nearbyPlayer); + if (fPlayer.getRelationTo(fPlayerNearby).isAtMost(Relation.NEUTRAL)) return; + super.getDamageHandler().healEntity(nearbyPlayer, 100, this.getName()); + }); + super.registerCooldown(victim, cooldown); + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Molten.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Molten.java new file mode 100644 index 0000000..0aad8db --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Molten.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Molten extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.06; + + public Molten() { + super("Molten", EnchantTier.UNIQUE, false, 4, GearType.ARMOR, "Chance of setting your attacker ablaze."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (Math.random() < procChance) { + attacker.setFireTicks(20 * enchantInfo.getLevel()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/ObsidianDestroyer.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/ObsidianDestroyer.java new file mode 100644 index 0000000..31133ec --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/ObsidianDestroyer.java @@ -0,0 +1,54 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import com.massivecraft.factions.*; +import net.coreprotect.CoreProtect; +import net.coreprotect.CoreProtectAPI; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class ObsidianDestroyer extends Enchantment { + + private final CoreProtectAPI coreProtectAPI; + + public ObsidianDestroyer() { + super("Obsidian Destroyer", EnchantTier.UNIQUE, false, 5, GearType.PICKAXE, "Chance to automatically break obsidian", "on swing."); + this.coreProtectAPI = CoreProtect.getInstance().getAPI(); + } + + @EventHandler + public void procObsidianBreaker(PlayerInteractEvent event) { + if (event.isCancelled()) return; + if (event.getAction() == Action.LEFT_CLICK_BLOCK && event.hasBlock() && event.getClickedBlock().getType() == Material.OBSIDIAN) { + + ItemStack itemStack = event.getPlayer().getItemInHand(); + + if (itemStack == null) return; + if (!this.getType().getItems().contains(itemStack.getType())) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + FLocation breakLoc = new FLocation(event.getClickedBlock().getLocation()); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + Faction faction = fPlayer.getFaction(); + + if (faction.equals(Board.getInstance().getFactionAt(breakLoc)) || Board.getInstance().getFactionAt(breakLoc).isWilderness()) { + if (faction.doesLocationHaveOwnersSet(breakLoc)) { + if (!faction.isPlayerInOwnerList(fPlayer, breakLoc)) { + return; + } + } + this.coreProtectAPI.logRemoval(event.getPlayer().getName(), event.getClickedBlock().getLocation(), event.getClickedBlock().getType(), event.getClickedBlock().getData()); + event.getClickedBlock().setTypeIdAndData(0, (byte) 0, true); + event.getPlayer().getWorld().dropItem(event.getClickedBlock().getLocation(), new ItemStack(Material.OBSIDIAN)); + } + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/PlagueCarrier.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/PlagueCarrier.java new file mode 100644 index 0000000..80bb360 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/PlagueCarrier.java @@ -0,0 +1,111 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; + +public class PlagueCarrier extends ArmorIncomingPVPDamageEventEnchant { + + public PlagueCarrier() { + super("Plague Carrier", EnchantTier.UNIQUE, false, 8, GearType.LEGGINGS, "When near death summons creepers and debuffs to avenge you."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + double dmg = event.getFinalDamage(); + if (victim.getHealth() - dmg <= 0.0) { + int radius = Math.round((float) enchantInfo.getLevel() * 1.5f); + ArrayList victims = new ArrayList<>(); + FPlayer fp = FPlayers.getInstance().getByPlayer(victim); + for (Entity ent : victim.getNearbyEntities(radius, radius, radius)) { + if (!(ent instanceof LivingEntity) || ent instanceof Player && FPlayers.getInstance().getByPlayer((Player) ent).getRelationTo(fp).isAtLeast(Relation.TRUCE)) + continue; + victims.add((LivingEntity) ent); + } + + victim.getWorld().playSound(victim.getLocation(), Sound.CREEPER_HISS, 2.0f, 0.75f); + for (LivingEntity livingEntity : victims) { + if (!(livingEntity instanceof Player)) continue; + livingEntity.getWorld().playSound(livingEntity.getLocation(), Sound.CREEPER_HISS, 1.6f, 0.75f); + PotionEffectUtils.addPotionEffect((Player) livingEntity, PotionEffectType.POISON, enchantInfo.getLevel() >= 7 ? 1 : 0, "plague_carrier_poison_death", (2 + enchantInfo.getLevel())); + //livingEntity.addPotionEffect(new PotionEffect(PotionEffectType.POISON, (2 + enchantInfo.getLevel()) * 20, enchantInfo.getLevel() >= 7 ? 1 : 0)); + } + for (int plagueCarriers = radius / 2; plagueCarriers > 0; --plagueCarriers) { + this.spawnPlagueCreeper(victim.getLocation().add(0.0, 1.0, 0.0), enchantInfo.getLevel()); + } + + } + } + + @EventHandler + public void onEntityExplode(EntityExplodeEvent event) { + if (event.getEntity() != null && event.getEntity().hasMetadata("plagueCarrier")) { + event.setYield(0.0f); + int level = event.getEntity().getMetadata("plagueCarrier").get(0).asInt(); + Location loc = event.getLocation(); + loc.getWorld().playSound(loc, Sound.EXPLODE, 1.0f, 1.0f); + + for (Entity ent : event.getEntity().getNearbyEntities(5.0, 4.0, 5.0)) { + if (!(ent instanceof LivingEntity)) continue; + LivingEntity le = (LivingEntity)ent; + if(!(le instanceof Player))continue; + Player nearbyPlayer = (Player)le; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.POISON, level == 8 ? 2 : (level >= 4 ? 1 : 0), "plague_carrier_poison", level * 2); + //le.addPotionEffect(new PotionEffect(PotionEffectType.POISON, level * 2 * 20, level == 8 ? 2 : (level >= 4 ? 1 : 0))); + if (level >= 3) { + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.BLINDNESS, level == 8 ? 2 : (level >= 4 ? 1 : 0), "plague_carrier_blindness", level * 2); + //le.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, level * 2 * 20, level == 8 ? 2 : (level >= 4 ? 1 : 0))); + } + if (level >= 6) { + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.WEAKNESS, level == 8 ? 2 : 1, "plague_carrier_weakness", level * 2); + //le.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, level * 2 * 20, level == 8 ? 2 : 1)); + } + if (level != 8) continue; + PotionEffectUtils.addPotionEffect(nearbyPlayer, PotionEffectType.SLOW, 2, "plague_carrier_slow", level * 2); + //le.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, level * 2 * 20, 2)); + } + event.getEntity().remove(); + } + } + + @EventHandler + public void onEntityDeath(EntityDeathEvent e) { + if (e.getEntity().hasMetadata("plagueCarrier")) { + e.setDroppedExp(0); + e.getDrops().clear(); + e.getEntity().remove(); + } + } + + private void spawnPlagueCreeper(Location location, int level) { + Creeper creeper = (Creeper) location.getWorld().spawnEntity(location, EntityType.CREEPER); + creeper.setMetadata("plagueCarrier", new FixedMetadataValue(CrankedEnchants.getInstance(), level)); + creeper.setCustomName(ChatColor.LIGHT_PURPLE + "Plague Carrier"); + creeper.setCanPickupItems(false); + creeper.setCustomNameVisible(true); + creeper.setPowered(true); + + if (!creeper.isDead()) { + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), creeper::remove, 600L); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Ragdoll.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Ragdoll.java new file mode 100644 index 0000000..d9ff183 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Ragdoll.java @@ -0,0 +1,44 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.IronGolem; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.util.Vector; + +public class Ragdoll extends ArmorIncomingPVPDamageEventEnchant { + + @ConfigValue + private double procChance = 0.05; + + public Ragdoll() { + super("Ragdoll", EnchantTier.UNIQUE, false, 4, GearType.ARMOR, "Whenever you take damage you are pushed far back."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (attacker instanceof IronGolem) return; + if (Math.random() < procChance * enchantInfo.getLevel()) { + pushAwayEntity(attacker, victim, 1.5 + 0.5 * enchantInfo.getLevel()); + } + } + + public void pushAwayEntity(final LivingEntity center, final Entity entity, final double speed) { + pushAwayEntity(center.getLocation(), entity, speed); + } + + public void pushAwayEntity(final Location center, final Entity entity, final double speed) { + final Vector unitVector = entity.getLocation().toVector().subtract(center.toVector()); + if (unitVector.length() != 0.0) { + unitVector.normalize(); + } + entity.setVelocity(unitVector.multiply(speed)); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Ravenous.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Ravenous.java new file mode 100644 index 0000000..ee4e892 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Ravenous.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class Ravenous extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.05; + + public Ravenous() { + super("Ravenous", EnchantTier.UNIQUE, 4, GearType.AXE, "A chance to regain hunger."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (Math.random() < procChance * level && attacker.getFoodLevel() < 20) { + attacker.setFoodLevel(attacker.getFoodLevel() + 1); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/SelfDestruct.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/SelfDestruct.java new file mode 100644 index 0000000..c67b766 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/SelfDestruct.java @@ -0,0 +1,99 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorIncomingPVPDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.util.Vector; + +import java.util.Random; + +public class SelfDestruct extends ArmorIncomingPVPDamageEventEnchant { + + public SelfDestruct() { + super("Self Destruct", EnchantTier.UNIQUE, false, 3, GearType.ARMOR, "When close to death buffed TnT spawns around you."); + } + + @Override + public void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo) { + if (super.isOnCooldown(victim)) return; + if (victim.getHealth() - event.getFinalDamage() <= 0.0) { + super.registerCooldown(victim, 200); + victim.getWorld().playSound(victim.getLocation(), Sound.EXPLODE, 2.0f, 0.75f); + int fuseTicks = 120 - enchantInfo.getLevel() * 20; + for (int tntAmount = enchantInfo.getLevel() * 2; tntAmount > 0; --tntAmount) { + this.spawnExplosion(victim, this.getNearbyLocation(victim.getLocation(), 3, 1), fuseTicks); + } + } + } + + @EventHandler(priority= EventPriority.LOWEST) + public void onBlockExplode(EntityExplodeEvent event) { + if (event.getEntity() != null && event.getEntity().hasMetadata("SelfDestructTNT")) { + event.setYield(0.0f); + event.blockList().clear(); + event.setCancelled(true); + if (!PVPUtils.canPvPInRegion(event.getLocation())) return; + Location loc = event.getLocation(); + loc.getWorld().playSound(loc, Sound.EXPLODE, 1.0f, 1.0f); + + String exploder = event.getEntity().getMetadata("SelfDestructTNT").get(0).asString(); + Player pExploder = Bukkit.getPlayer(exploder); + FPlayer fp = pExploder != null ? FPlayers.getInstance().getByPlayer(pExploder) : null; + for (Entity ent : event.getEntity().getNearbyEntities(4, 4, 4)) { + if (!(ent instanceof LivingEntity) || ent instanceof Player && fp != null && fp.getRelationTo(FPlayers.getInstance().getByPlayer((Player) ent)).isAtLeast(Relation.TRUCE) || !PVPUtils.canPvPInRegion(ent.getLocation())) continue; + ((LivingEntity)ent).damage(16.0); + ent.setFireTicks(40); + this.pushAwayEntity((LivingEntity)ent, event.getEntity(), 1.7f); + } + event.getEntity().remove(); + } + } + + private void spawnExplosion(Player exploder, Location location, int fuseTicks) { + if (location.getBlock().getType().isSolid()) { + return; + } + TNTPrimed tnt = (TNTPrimed)location.getWorld().spawnEntity(location, EntityType.PRIMED_TNT); + tnt.setFuseTicks(fuseTicks); + tnt.setMetadata("SelfDestructTNT", new FixedMetadataValue(CrankedEnchants.getInstance(), (Object)exploder.getName())); + } + + private Location getNearbyLocation(Location location, int radius, int y_boost) { + Random rand = new Random(); + Location rand_loc = location.clone(); + rand_loc.add((rand.nextBoolean() ? 1 : -1) * (rand.nextInt(radius) + 1), 0.0, (rand.nextBoolean() ? 1 : -1) * (rand.nextInt(radius) + 1)); + rand_loc.add(0.5, y_boost, 0.5); + while ((rand_loc.getBlock().getType() != Material.AIR || rand_loc.getBlock().getLocation().subtract(0.0, 1.0, 0.0).getBlock().getType() != Material.AIR) && rand_loc.getY() < 255.0) { + rand_loc = rand_loc.add(0.0, 1.0, 0.0); + } + return rand_loc; + } + + public void pushAwayEntity(final LivingEntity center, final Entity entity, final double speed) { + pushAwayEntity(center.getLocation(), entity, speed); + } + + public void pushAwayEntity(final Location center, final Entity entity, final double speed) { + final Vector unitVector = entity.getLocation().toVector().subtract(center.toVector()); + if (unitVector.length() != 0.0) { + unitVector.normalize(); + } + entity.setVelocity(unitVector.multiply(speed)); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/SkillSwipe.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/SkillSwipe.java new file mode 100644 index 0000000..273508d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/SkillSwipe.java @@ -0,0 +1,43 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.WeaponDamageEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.XPUtils; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class SkillSwipe extends WeaponDamageEventEnchant { + + @ConfigValue + private double procChance = 0.4; + + public SkillSwipe() { + super("Skill Swipe", EnchantTier.UNIQUE, 5, GearType.SWORD, "A chance to steal some of your enemy's EXP every time you damage them."); + } + + @Override + public void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int level) { + if (!(victim instanceof Player)) return; + + Player victimPlayer = ((Player) victim); + int amountToSteal = level * 6; + int targetXp = XPUtils.getTotalExperience(victimPlayer); + + if (targetXp - amountToSteal < 0) { + amountToSteal = targetXp; + } + + if (amountToSteal <= 0) { + return; + } + + if (Math.random() < procChance) { + XPUtils.setTotalExperience(victimPlayer, targetXp - amountToSteal); + XPUtils.setTotalExperience(attacker, XPUtils.getTotalExperience(attacker) + amountToSteal); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Telepathy.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Telepathy.java new file mode 100644 index 0000000..93f1c42 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/enchantments/unique/Telepathy.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedenchants.enchantments.unique; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.BlockBreakEventEnchant; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Material; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.inventory.ItemStack; + +public class Telepathy extends BlockBreakEventEnchant { + + public Telepathy() { + super("Telepathy", EnchantTier.UNIQUE, 4, GearType.TOOL, "Automatically places blocks broken by tools in your inventory."); + } + + @Override + public void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder) { + event.setCancelled(true); + for (ItemStack drop : event.getBlock().getDrops()) { + event.getPlayer().getInventory().addItem(drop); + } + event.getBlock().setType(Material.AIR); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/BookApplyEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/BookApplyEvent.java new file mode 100644 index 0000000..038fe8b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/BookApplyEvent.java @@ -0,0 +1,42 @@ +package net.crankedpvp.crankedenchants.events; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedenchants.struct.items.BookBuilder; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@Getter +public class BookApplyEvent extends Event implements Cancellable { + + + private boolean cancelled; + private final BookBuilder bookBuilder; + private final EnchantedItemBuilder enchantedItemBuilder; + private static final HandlerList handlers = new HandlerList(); + + @Setter + private String cancelMessage; + + public BookApplyEvent(BookBuilder bookBuilder, EnchantedItemBuilder enchantedItemBuilder) { + this.bookBuilder = bookBuilder; + this.enchantedItemBuilder = enchantedItemBuilder; + this.cancelMessage = ""; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcEvent.java new file mode 100644 index 0000000..efa21db --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcEvent.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedenchants.events; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import lombok.Getter; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@Getter +public class EnchantProcEvent extends Event implements Cancellable { + + private boolean cancelled; + private final Enchantment enchantment; + private final int level; + private static final HandlerList handlers = new HandlerList(); + + + public EnchantProcEvent(Enchantment enchantment, int level) { + this.enchantment = enchantment; + this.level = level; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnBlockEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnBlockEvent.java new file mode 100644 index 0000000..cf5808c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnBlockEvent.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.events; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import lombok.Getter; +import org.bukkit.block.Block; +import org.bukkit.event.HandlerList; + +@Getter +public class EnchantProcOnBlockEvent extends EnchantProcEvent { + + private final Block block; + private static final HandlerList handlers = new HandlerList(); + + public EnchantProcOnBlockEvent(Block block, Enchantment enchantment, int level) { + super(enchantment, level); + this.block = block; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnDamageEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnDamageEvent.java new file mode 100644 index 0000000..907368d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnDamageEvent.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedenchants.events; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.EntityDamageEvent; + +@Getter +public class EnchantProcOnDamageEvent extends EnchantProcEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private final EntityDamageEvent.DamageCause damageCause; + + public EnchantProcOnDamageEvent(Player player, EntityDamageEvent.DamageCause damageCause, Enchantment enchantment, int level) { + super(enchantment, level); + this.damageCause = damageCause; + this.player = player; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEntityDeathEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEntityDeathEvent.java new file mode 100644 index 0000000..cd676f3 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEntityDeathEvent.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedenchants.events; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import lombok.Getter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +@Getter +public class EnchantProcOnEntityDeathEvent extends EnchantProcEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Player killer; + private final LivingEntity victim; + + public EnchantProcOnEntityDeathEvent(Player killer, LivingEntity victim, Enchantment enchantment, int level) { + super(enchantment, level); + this.killer = killer; + this.victim = victim; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEntityEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEntityEvent.java new file mode 100644 index 0000000..4750f17 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEntityEvent.java @@ -0,0 +1,29 @@ +package net.crankedpvp.crankedenchants.events; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import lombok.Getter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.HandlerList; + +@Getter +public class EnchantProcOnEntityEvent extends EnchantProcEvent { + + private static final HandlerList handlers = new HandlerList(); + private final LivingEntity attacker; + private final LivingEntity victim; + + public EnchantProcOnEntityEvent(LivingEntity attacker, LivingEntity victim, Enchantment enchantment, int level) { + super(enchantment, level); + this.attacker = attacker; + this.victim = victim; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEquipEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEquipEvent.java new file mode 100644 index 0000000..7597fc7 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/EnchantProcOnEquipEvent.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.events; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +@Getter +public class EnchantProcOnEquipEvent extends EnchantProcEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Player player; + + public EnchantProcOnEquipEvent(Player player, Enchantment enchantment, int level) { + super(enchantment, level); + this.player = player; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/NaturesLightningHitEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/NaturesLightningHitEvent.java new file mode 100644 index 0000000..7051db7 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/NaturesLightningHitEvent.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.events; + +import lombok.Getter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@Getter +public class NaturesLightningHitEvent extends Event implements Cancellable { + + private boolean cancelled; + private final LivingEntity victim; + private final int level; + private final int timeLeft; + + private static final HandlerList handlers = new HandlerList(); + + public NaturesLightningHitEvent(LivingEntity victim, int level, int timeLeft) { + this.victim = victim; + this.level = level; + this.timeLeft = timeLeft; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/SlownessEnchantProcEvent.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/SlownessEnchantProcEvent.java new file mode 100644 index 0000000..b20a852 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/events/SlownessEnchantProcEvent.java @@ -0,0 +1,37 @@ +package net.crankedpvp.crankedenchants.events; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import lombok.Getter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +@Getter +public class SlownessEnchantProcEvent extends EnchantProcEvent implements Cancellable { + + private boolean cancelled; + private final LivingEntity attacker; + private final LivingEntity victim; + + private static final HandlerList handlers = new HandlerList(); + + public SlownessEnchantProcEvent(LivingEntity attacker, LivingEntity victim, Enchantment enchantment, int level) { + super(enchantment, level); + this.attacker = attacker; + this.victim = victim; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchanterUI.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchanterUI.java new file mode 100644 index 0000000..af808f2 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchanterUI.java @@ -0,0 +1,118 @@ +package net.crankedpvp.crankedenchants.inventories; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.config.ConfigManager; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.TransmogScrollBuilder; +import net.crankedpvp.crankedenchants.struct.items.WhiteScrollBuilder; +import net.crankedpvp.crankedutils.utils.XPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.kyori.adventure.text.Component; +import org.bukkit.Sound; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.ItemStack; + +public class EnchanterUI { + + @Getter + private final Gui enchantersUI; + + public EnchanterUI() { + FileConfiguration settingsConfig = CrankedEnchants.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.SETTINGS); + ConfigurationSection enchanterSection = settingsConfig.getConfigurationSection("enchanter"); + ConfigurationSection tierSection = enchanterSection.getConfigurationSection("tier-items"); + + this.enchantersUI = Gui.gui(). + title(Component.text("Enchanter")) + .rows(enchanterSection.getInt("gui-rows")) + .disableAllInteractions() + .create(); + + for (String enchantTierAsString : tierSection.getKeys(false)) { + EnchantTier enchantTier; + try { + enchantTier = EnchantTier.valueOf(enchantTierAsString); + } catch (Exception e) { + continue; + } + + ConfigurationSection specificTierSection = tierSection.getConfigurationSection(enchantTierAsString); + int price = specificTierSection.getInt("price"); + + + GuiItem guiItem = new GuiItem(enchantTier.getGuiItem(price)); + + guiItem.setAction(event -> { + if (event.getClick() == ClickType.LEFT) { + Player player = (Player) event.getWhoClicked(); + if (XPUtils.hasEnoughExperience(player, price)) { + player.getInventory().addItem(EnchantTier.createMysteryBook(enchantTier, 1)); + XPUtils.removeExperience(player, price); + Language.REMOVE_EXP.send(player, str -> str.replace("{amount}", String.valueOf(price))); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0F, 1.2F); + } else { + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 0.7f, 1.4f); + Language.NOT_ENOUGH_EXP.send(player); + } + } + if (event.getClick() == ClickType.RIGHT) { + PaginatedGui enchantsUI = new EnchantsUI(this.getEnchantersUI(), EnchantRegister.getInstance().getOrderedEnchantments(enchantTier)).getEnchantsGUI(); + enchantsUI.open(event.getWhoClicked()); + } + }); + + this.enchantersUI.setItem(specificTierSection.getInt("slot"), guiItem); + } + + this.enchantersUI.setItem(1, 1, new GuiItem(getWhiteScrollItem(), event -> { + Player player = (Player) event.getWhoClicked(); + int price = 500; + if (XPUtils.hasEnoughExperience(player, price)) { + player.getInventory().addItem(new WhiteScrollBuilder().build()); + XPUtils.removeExperience(player, 500); + Language.REMOVE_EXP.send(player, str -> str.replace("{amount}", "500")); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0F, 1.2F); + } else { + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 0.7f, 1.4f); + Language.NOT_ENOUGH_EXP.send(player); + } + })); + + this.enchantersUI.setItem(1, 9, new GuiItem(getTransmogItem(), event -> { + Player player = (Player) event.getWhoClicked(); + int price = 500; + if (XPUtils.hasEnoughExperience(player, price)) { + player.getInventory().addItem(new TransmogScrollBuilder().build()); + XPUtils.removeExperience(player, 500); + Language.REMOVE_EXP.send(player, str -> str.replace("{amount}", "500")); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0F, 1.2F); + } else { + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 0.7f, 1.4f); + Language.NOT_ENOUGH_EXP.send(player); + } + })); + } + + private ItemStack getWhiteScrollItem() { + ItemBuilder itemBuilder = new ItemBuilder(new WhiteScrollBuilder().build()); + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&b&lCOST &f500 EXP"); + return itemBuilder.colorize().build(); + } + + private ItemStack getTransmogItem() { + ItemBuilder itemBuilder = new ItemBuilder(new TransmogScrollBuilder().build()); + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&b&lCOST &f500 EXP"); + return itemBuilder.colorize().build(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsItemUI.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsItemUI.java new file mode 100644 index 0000000..2ed0487 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsItemUI.java @@ -0,0 +1,34 @@ +package net.crankedpvp.crankedenchants.inventories; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +@Getter +public class EnchantsItemUI { + private final PaginatedGui enchantsItemUI; + + public EnchantsItemUI() { + this.enchantsItemUI = new PaginatedGui(3, 27, "Enchants based on item"); + this.enchantsItemUI.setDefaultClickAction(event -> event.setCancelled(true)); + for (GearType gearType : GearType.values()) { + if (gearType.isDisplayInGUI()) { + enchantsItemUI.addItem(new GuiItem(getDisplayItem(gearType), event -> { + EnchantsUI enchantsUI = new EnchantsUI(this.getEnchantsItemUI(), (List) EnchantRegister.getInstance().getOrderedEnchantments(gearType)); + enchantsUI.getEnchantsGUI().open(event.getWhoClicked()); + })); + } + } + } + + public ItemStack getDisplayItem(GearType type) { + return new ItemBuilder(type.getDisplay(), "&b&l" + type.getFormatedName() + " Enchants", "&7Click to view the " + type.getFormatedName() + " enchants.").colorize().build(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsRarityUI.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsRarityUI.java new file mode 100644 index 0000000..27b4687 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsRarityUI.java @@ -0,0 +1,31 @@ +package net.crankedpvp.crankedenchants.inventories; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +@Getter +public class EnchantsRarityUI { + + private final PaginatedGui enchantsTypeUI; + + public EnchantsRarityUI() { + this.enchantsTypeUI = new PaginatedGui(3, 27, "Enchants based on rarity"); + this.enchantsTypeUI.setDefaultClickAction(event -> event.setCancelled(true)); + for (EnchantTier tier : EnchantTier.values()) { + enchantsTypeUI.addItem(new GuiItem(getDisplayItem(tier), event -> { + EnchantsUI enchantsUI = new EnchantsUI(this.getEnchantsTypeUI(),EnchantRegister.getInstance().getOrderedEnchantments(tier)); + enchantsUI.getEnchantsGUI().open(event.getWhoClicked()); + })); + } + } + + public ItemStack getDisplayItem(EnchantTier tier) { + return new ItemBuilder(new ItemBuilder(Material.STAINED_GLASS_PANE, 1, tier.getGuiItemGlassColor(), tier.getColor() + tier.getFormatedName() + " Enchants", "&7Click to view the " + tier.getFormatedName() + " enchants.").colorize()).build(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsUI.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsUI.java new file mode 100644 index 0000000..3662496 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/EnchantsUI.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedenchants.inventories; + +import dev.triumphteam.gui.guis.BaseGui; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.items.BookBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +@Getter +public class EnchantsUI { + private final PaginatedGui enchantsGUI; + + public EnchantsUI(BaseGui previousGUI, List enchants) { + this.enchantsGUI = new PaginatedGui(6, 54, "Enchants"); + + this.enchantsGUI.setDefaultClickAction(event -> event.setCancelled(true)); + + this.enchantsGUI.setCloseGuiAction(event -> { + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), () -> { + previousGUI.open(event.getPlayer()); + }, 3L); + } + ); + + ItemStack prevPage = (new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.")).colorize().build(); + ItemStack nextPage = (new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.")).colorize().build(); + this.enchantsGUI.setItem(6, 3, new GuiItem(prevPage, event -> enchantsGUI.previous())); + this.enchantsGUI.setItem(6, 7, new GuiItem(nextPage, event -> enchantsGUI.next())); + this.enchantsGUI.setItem(6, 5, new GuiItem(new ItemBuilder(Material.BARRIER).setName("&cGo Back").colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + previousGUI.open(event.getWhoClicked()); + event.setCancelled(true); + })); + this.enchantsGUI.getFiller().fillBottom(new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE).setName("&7").colorize().setDurability((short) 7).build())); + + for (Enchantment enchantment : enchants) { + ItemStack itemStack = new BookBuilder(enchantment, enchantment.getMax()).setDestroyRate(100).setSuccessRate(100).build(); + this.enchantsGUI.addItem(new GuiItem(itemStack, event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) event.getWhoClicked().getInventory().addItem(itemStack); + })); + } + } + + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/MainEnchantsUI.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/MainEnchantsUI.java new file mode 100644 index 0000000..f39ce10 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/MainEnchantsUI.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedenchants.inventories; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +@Getter +public class MainEnchantsUI { + private PaginatedGui enchantsGUI; + public MainEnchantsUI() { + this.enchantsGUI = new PaginatedGui(1, 9, "Cranked Enchants"); + this.enchantsGUI.setDefaultClickAction(event -> event.setCancelled(true)); + enchantsGUI.setItem(3, new GuiItem(getEnchantsByRarityItem(), event -> { + EnchantsRarityUI enchantsGUI = new EnchantsRarityUI(); + enchantsGUI.getEnchantsTypeUI().open(event.getWhoClicked()); + })); + + enchantsGUI.setItem(5, new GuiItem(getEnchantsByItemItem(), event -> { + EnchantsItemUI enchantsGUI = new EnchantsItemUI(); + enchantsGUI.getEnchantsItemUI().open(event.getWhoClicked()); + + })); + } + + public ItemStack getEnchantsByRarityItem() { + return new ItemBuilder(Material.BOOK, "&d&lEnchants by Rarity", "&7Click to view all enchants based on rarity.").colorize().build(); + + } + + public ItemStack getEnchantsByItemItem() { + return new ItemBuilder(Material.DIAMOND_CHESTPLATE, "&b&lEnchants by Item", "&7Click to view all enchants based on item.").colorize().build(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/OmniBlackScrollUI.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/OmniBlackScrollUI.java new file mode 100644 index 0000000..730fa62 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/inventories/OmniBlackScrollUI.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedenchants.inventories; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.items.BookBuilder; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.kyori.adventure.text.Component; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Map; + +public class OmniBlackScrollUI { + + @Getter + private final Gui gui; + + public OmniBlackScrollUI(Map enchants, InventoryClickEvent event) { + this.gui = Gui.gui() + .title(Component.text("Omni Black Scroll")) + .rows(this.getAmountOfRows(enchants.size())) + .create(); + this.gui.setDefaultClickAction(event1 -> event1.setCancelled(true)); + enchants.forEach((enchantment, level) -> { + if (level > enchantment.getMax()) return; + this.gui.addItem(this.getBookItem(enchantment, level, event)); + }); + } + + private int getAmountOfRows(double amountOfEnchants) { + return (int) Math.ceil(amountOfEnchants / 9); + } + + private GuiItem getBookItem(Enchantment enchantment, int level, InventoryClickEvent event) { + return new GuiItem(new BookBuilder(enchantment, level).setSuccessRate(100).setDestroyRate(0).build(), inventoryClickEvent -> { + inventoryClickEvent.setCancelled(true); + ItemStack currentItem = event.getCurrentItem(); + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(currentItem); + enchantedItemBuilder.removeEnchantment(enchantment); + event.setCurrentItem(enchantedItemBuilder.build()); + BookBuilder bookBuilder = new BookBuilder(enchantment, level).setSuccessRate(100).setDestroyRate(0); + Player player = ((Player) event.getWhoClicked()); + player.getInventory().addItem(bookBuilder.build()); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2f, 2f); + player.updateInventory(); + player.closeInventory(); + }); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/language/Language.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/language/Language.java new file mode 100644 index 0000000..784d809 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/language/Language.java @@ -0,0 +1,147 @@ +package net.crankedpvp.crankedenchants.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + SOUL_MODE_ENABLE, + SOUL_MODE_DISABLE, + OUT_OF_SOULS, + CLICKED_WRONG_SOUL_GEM, + SOUL_DRAIN_MESSAGE, + + INVALID_ENCHANTMENT_NAME, + INVALID_ENCHANTMENT_LEVEL, + EMPTY_HAND, + ALREADY_HAS_ENCHANTMENT, + DOESNT_HAVE_ANY_ENCHANTMENTS, + ONLY_HAS_HEROIC_ENCHANTMENTS, + + NE_COMMAND_HELP, + + ADMIN_RELOADING, + ADMIN_RELOADED, + + EQUIP_POTION_ENCHANT, + UNEQUIP_POTION_ENCHANT, + + WEAK_SHOT, + INVALID_ITEM_TYPE_FOR_ENCHANT, + NOT_ENOUGH_SLOTS, + ITEM_PROTECTED_BY_WHITE_SCROLL, + APPLY_HEROIC_MISSING_BASE_ENCHANT, + + SUCCESSFULLY_RENAMED, + RENAME_TAG_CLICKED, + + BOOK_OPEN, + BOOK_RIGHT_CLICK, + + FULL_INVENTORY, + + KIT_RECEIVED, + KIT_COOLDOWN, + KIT_INVALID_NAME, + KIT_NO_ACCESS, + + SOUL_TRACKER_APPLIED, + ALREADY_HAS_SOUL_TRACKER, + SOUL_HARVEST_COOLDOWN, + DOESNT_HAVE_SOUL_TRACKER, + + REMOVE_EXP, + NOT_ENOUGH_EXP, + + CANNOT_DUPE_ITEM, + CANNOT_DUPE_MORE, + CANNOT_DUPE_TIER, + DUPED_ITEM, + + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/language/LanguageHandler.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/language/LanguageHandler.java new file mode 100644 index 0000000..85767c4 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.crankedenchants.language; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final CrankedEnchants plugin; + + public LanguageHandler(CrankedEnchants plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/ArmorSwapListener.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/ArmorSwapListener.java new file mode 100644 index 0000000..97d3765 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/ArmorSwapListener.java @@ -0,0 +1,79 @@ +package net.crankedpvp.crankedenchants.listeners; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + + +//TODO: needs a recode, just call the armor equip event +public class ArmorSwapListener implements Listener { + + private final CrankedEnchants plugin; + + public ArmorSwapListener(CrankedEnchants plugin) { + this.plugin = plugin; + } + +/* @EventHandler + public void onArmorSwap(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (!event.hasItem()) return; + + ItemStack itemInHand = event.getItem(); + int itemInHandArmorSlot = getArmorSlot(itemInHand); + + if (itemInHandArmorSlot == -1) return; + + Player player = event.getPlayer(); + ItemStack[] armorContents = player.getInventory().getArmorContents(); + ItemStack armorItem = armorContents[itemInHandArmorSlot]; + + + if (armorItem == null || armorItem.getType() == Material.AIR) return; + + CrankedEnchantsAPI.clearEnchantsFromCacheFromOneArmorItem(event.getPlayer(), armorItem); + + armorContents[itemInHandArmorSlot] = itemInHand; + + event.getPlayer().getInventory().setArmorContents(armorContents); + CrankedEnchantsAPI.reprocEnchantsFromOneArmorItem(player, itemInHand); + + *//*ArmorSetCache armorSetCache = (ArmorSetCache) CacheManager.getInstance().getCachedPlayer(event.getPlayer()).getCache("armor_set"); + armorSetCache.clear(); + CrankedArmorAPI.refreshArmorSets(player);*//* + + + player.setItemInHand(armorItem); + player.updateInventory(); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0F, 1.2F); + } + + private int getArmorSlot(ItemStack itemStack) { + if (!ItemUtils.isArmor(itemStack)) return -1; + + if (itemStack.getType().name().endsWith("HELMET")) { + return 3; + } + + if (itemStack.getType().name().endsWith("CHESTPLATE")) { + return 2; + } + + if (itemStack.getType().name().endsWith("LEGGINGS")) { + return 1; + } + + if (itemStack.getType().name().endsWith("BOOTS")) { + return 0; + } + return -1; + }*/ +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/BookListeners.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/BookListeners.java new file mode 100644 index 0000000..14f1a6d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/BookListeners.java @@ -0,0 +1,265 @@ +package net.crankedpvp.crankedenchants.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.BookApplyEvent; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.BookBuilder; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +import java.util.Locale; +import java.util.concurrent.ThreadLocalRandom; + +public class BookListeners implements Listener { + + private final EnchantRegister enchantRegister; + private ParticleBuilder critMagicParticle; + private ParticleBuilder lavaParticle; + private ParticleBuilder spellParticle; + + public BookListeners(CrankedEnchants plugin) { + this.enchantRegister = plugin.getEnchantRegister(); + this.initParticles(); + + } + + @EventHandler + public void onRightClickRandomBook(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (!CrankedEnchantsAPI.isRandomEnchantBook(event.getItem())) return; + + Player player = event.getPlayer(); + //if(event.isCancelled()) return; + if (!InventoryUtils.hasAvailableSlot(player)) { + Language.FULL_INVENTORY.send(player); + player.playSound(player.getLocation(), Sound.VILLAGER_NO, 0.7f, 1.4f); + return; + } + + ItemStack itemStack = event.getItem(); + + EnchantTier enchantTier = CrankedEnchantsAPI.getRandomEnchantBookTier(itemStack); + + Enchantment enchantment = this.enchantRegister.selectRandomEnchantment(enchantTier); + + if (enchantment == null) return; + + BookBuilder bookBuilder = new BookBuilder(enchantment); + + if (bookBuilder.getBookLevel() > enchantment.getMax()) { + event.getPlayer().sendMessage(CC.translate("&d&lEnchantments&8 " + Arrow.arrow() + " &7You cannot apply books above the max level.")); + } + + ItemStack book = bookBuilder.build(); + EnchantTier tier = bookBuilder.getBookEnchantment().getTier(); + player.getInventory().addItem(book); + + + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 0.7f, 1.4f); + Language.BOOK_OPEN.send(event.getPlayer(), str -> str.replace("{book-type}", tier.getColor() + tier.getFormatedName()).replace("{book}", tier.getColor() + bookBuilder.getBookEnchantment().getName())); + + if (itemStack.getAmount() > 1) { + itemStack.setAmount(itemStack.getAmount() - 1); + } else { + event.getPlayer().setItemInHand(null); + } + + player.updateInventory(); + } + + + @EventHandler + public void onBookRightClick(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (!CrankedEnchantsAPI.isEnchantBook(event.getItem())) return; + + Language.BOOK_RIGHT_CLICK.send(event.getPlayer()); + } + + + @EventHandler + public void onBookApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + //if(event.isCancelled()) return; + if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + if (!CrankedEnchantsAPI.isEnchantBook(event.getCursor()) || !ItemUtils.isEnchantable(event.getCurrentItem())) return; + if (player.getWorld().getName().contains("underworld")) return; + + if (event.getCurrentItem().getType() == Material.DIAMOND_HOE && event.getCurrentItem().getType() == Material.GOLD_HOE) { + NBTItem nbtItem = new NBTItem(event.getCurrentItem()); + if (!nbtItem.hasKey("hookItem") || !nbtItem.getString("hookItem").equals("hookItem")) { + return; + } + } + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + BookBuilder bookBuilder = new BookBuilder(event.getCursor()); + Enchantment enchantment = bookBuilder.getBookEnchantment(); + int level = bookBuilder.getBookLevel(); + + + BookApplyEvent bookApplyEvent = new BookApplyEvent(bookBuilder, enchantedItemBuilder); + Bukkit.getPluginManager().callEvent(bookApplyEvent); + + if (event.isCancelled()) { + player.sendMessage(CC.translate(bookApplyEvent.getCancelMessage())); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 5.0F, 0.1F); + event.setCancelled(true); + return; + } + + switch (this.applyEnchantment(enchantedItemBuilder, bookBuilder)) { + case FAIL: + event.setCancelled(true); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 3.0F, 0.1F); + break; + case SUCCESS: + event.setCancelled(true); + enchantedItemBuilder.addEnchantment(enchantment, level); + event.setCurrentItem(enchantedItemBuilder.build()); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + player.playSound(player.getLocation(), Sound.LEVEL_UP, 1.0f, 0.75f); + this.spellParticle.setLocation(player.getLocation()).display(PVPUtils.getNearbyPlayers(player, 20)); + this.critMagicParticle.setLocation(player.getLocation()).display(PVPUtils.getNearbyPlayers(player, 20)); + break; + case DESTROY: + event.setCancelled(true); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + event.setCurrentItem(null); + player.playSound(player.getLocation(), Sound.LAVA_POP, 5.0F, 0.1F); + this.lavaParticle.setLocation(player.getLocation()).display(PVPUtils.getNearbyPlayers(player, 20)); + break; + case CONTAINS_HIGHER_LEVEL: + event.setCancelled(true); + Language.ALREADY_HAS_ENCHANTMENT.send(player); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 5.0F, 0.1F); + break; + case CONTAINS_LOWER_LEVEL: + event.setCancelled(true); + enchantedItemBuilder.removeEnchantment(enchantment); + enchantedItemBuilder.addEnchantment(enchantment, level); + event.setCurrentItem(enchantedItemBuilder.build()); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + player.playSound(player.getLocation(), Sound.LEVEL_UP, 1.0f, 0.75f); + this.spellParticle.setLocation(player.getLocation()).display(PVPUtils.getNearbyPlayers(player, 20)); + this.critMagicParticle.setLocation(player.getLocation()).display(PVPUtils.getNearbyPlayers(player, 20)); + break; + case INVALID_COUNT: + event.setCancelled(true); + break; + case INVALID_TYPE: + event.setCancelled(true); + Language.INVALID_ITEM_TYPE_FOR_ENCHANT.send(player, str -> str.replace("{valid-type}", enchantment.getType().name().toLowerCase(Locale.ROOT))); + break; + case NOT_ENOUGH_SLOTS: + event.setCancelled(true); + Language.NOT_ENOUGH_SLOTS.send(player, str -> str.replace("{slots}", String.valueOf(enchantedItemBuilder.getSlots()))); + break; + case PROTECTED: + event.setCancelled(true); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + enchantedItemBuilder.setProtected(false); + event.setCurrentItem(enchantedItemBuilder.build()); + Language.ITEM_PROTECTED_BY_WHITE_SCROLL.send(player); + break; + case HEROIC_MISSING_BASE_ENCHANT: + event.setCancelled(true); + HeroicEnchantment heroicEnchantment = ((HeroicEnchantment) enchantment); + Language.APPLY_HEROIC_MISSING_BASE_ENCHANT.send(player, str -> str.replace("{enchantment}", StringUtils.toNiceString(heroicEnchantment.getBaseEnchantment()))); + break; + } + } + + private EnchantResult applyEnchantment(EnchantedItemBuilder enchantedItemBuilder, BookBuilder bookBuilder) { + Enchantment enchantment = bookBuilder.getBookEnchantment(); + + if (enchantedItemBuilder.build().getAmount() > 1) + return EnchantResult.INVALID_COUNT; + + if (!enchantment.getType().getItems().contains(enchantedItemBuilder.build().getType())) { + return EnchantResult.INVALID_TYPE; + } + + if (enchantedItemBuilder.hasEnchantment(enchantment)) { + if (enchantedItemBuilder.getEnchantmentLevel(enchantment) < bookBuilder.getBookLevel()) { + return EnchantResult.CONTAINS_LOWER_LEVEL; + } + return EnchantResult.CONTAINS_HIGHER_LEVEL; + } + + if (enchantedItemBuilder.getAmountOfEnchantments() + 1 > enchantedItemBuilder.getSlots() && bookBuilder.getBookEnchantment().getTier() != EnchantTier.HEROIC) { + return EnchantResult.NOT_ENOUGH_SLOTS; + } + + if (enchantment instanceof HeroicEnchantment) { + HeroicEnchantment heroicEnchantment = ((HeroicEnchantment) enchantment); + if (!enchantedItemBuilder.getEnchantmentsAsString().containsKey(heroicEnchantment.getBaseEnchantment())) { + return EnchantResult.HEROIC_MISSING_BASE_ENCHANT; + } + } + + if (bookBuilder.getSuccessRate() >= this.generateChance()) { + return EnchantResult.SUCCESS; + } + + if (bookBuilder.getDestroyRate() > this.generateChance()) { + + if (enchantedItemBuilder.isProtected()) { + return EnchantResult.PROTECTED; + } + + return EnchantResult.DESTROY; + } + + return EnchantResult.FAIL; + } + + private enum EnchantResult { + SUCCESS, FAIL, DESTROY, INVALID_COUNT, INVALID_TYPE, CONTAINS_LOWER_LEVEL, CONTAINS_HIGHER_LEVEL, NOT_ENOUGH_SLOTS, PROTECTED, HEROIC_MISSING_BASE_ENCHANT + } + + private int generateChance() { + return ThreadLocalRandom.current().nextInt(1, 101); + } + + private void initParticles() { + this.lavaParticle = new ParticleBuilder(ParticleEffect.LAVA) + .setAmount(30) + .setOffsetY(0.5f) + .setSpeed(0.15f); + + this.spellParticle = new ParticleBuilder(ParticleEffect.SPELL) + .setAmount(30) + .setOffsetY(1f) + .setSpeed(0.1f); + + + this.critMagicParticle = new ParticleBuilder(ParticleEffect.CRIT_MAGIC) + .setAmount(30) + .setOffsetY(1f) + .setSpeed(0.1f); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/EnchantProcListeners.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/EnchantProcListeners.java new file mode 100644 index 0000000..41d9f7f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/EnchantProcListeners.java @@ -0,0 +1,8 @@ +package net.crankedpvp.crankedenchants.listeners; + +import org.bukkit.event.Listener; + +public class EnchantProcListeners implements Listener { + + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/EnchantmentListener.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/EnchantmentListener.java new file mode 100644 index 0000000..0ebfd77 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/EnchantmentListener.java @@ -0,0 +1,80 @@ +package net.crankedpvp.crankedenchants.listeners; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEquipEvent; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.ArmorEquipEventEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.crankedutils.events.ArmorEquipEvent; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; + +public class EnchantmentListener implements Listener { + + @EventHandler(priority = EventPriority.LOW) + public void onPlayerJoin(PlayerJoinEvent event) { + CrankedEnchantsAPI.reprocEnchants(event.getPlayer()); + } + + @EventHandler + public void onPlayerLeave(PlayerQuitEvent event) { + CrankedEnchantsAPI.clearEnchantsFromCache(event.getPlayer()); + } + + @EventHandler + public void onPlayerLeave(PlayerKickEvent event) { + CrankedEnchantsAPI.clearEnchantsFromCache(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.LOW) + public void armorEquipEvent(ArmorEquipEvent event) { + ItemStack itemStack = event.getNewArmorPiece(); + + if (!ItemUtils.isEnchantable(itemStack)) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + enchantedItemBuilder.getEnchantments().forEach(((enchantment, level) -> { + if (enchantment instanceof ArmorEquipEventEnchant) { + EnchantProcEvent procEvent = new EnchantProcOnEquipEvent(event.getPlayer(), enchantment, level); + Bukkit.getPluginManager().callEvent(procEvent); + if(procEvent.isCancelled()) return; + ((ArmorEquipEventEnchant) enchantment).runArmorEquipEvent(event.getPlayer(), level); + } + CrankedEnchantsAPI.addEnchantmentToPlayer(event.getPlayer(), enchantment, level); + })); + + for (Enchantment enchantment : CrankedEnchantsAPI.getEnchantments(event.getPlayer())) { + if (enchantment.getTier() == EnchantTier.HEROIC && !enchantment.isStackable()) { + Enchantment baseEnchantment = EnchantRegister.getInstance().getEnchantmentFromID(((HeroicEnchantment) enchantment).getBaseEnchantment()); + CrankedEnchantsAPI.removeEnchantmentFromPlayer(event.getPlayer(), baseEnchantment); + } + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void armorUnEquipEvent(ArmorEquipEvent event) { + ItemStack itemStack = event.getOldArmorPiece(); + + if (!ItemUtils.isEnchantable(itemStack)) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + enchantedItemBuilder.getEnchantments().forEach(((enchantment, level) -> { + if(enchantment instanceof ArmorEquipEventEnchant) + ((ArmorEquipEventEnchant)enchantment).runArmorUnEquipEvent(event.getPlayer(), level); + CrankedEnchantsAPI.removeEnchantmentFromPlayer(event.getPlayer(), enchantment, level); + })); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/HeadlessAbilityManager.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/HeadlessAbilityManager.java new file mode 100644 index 0000000..7720b41 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/HeadlessAbilityManager.java @@ -0,0 +1,109 @@ +package net.crankedpvp.crankedenchants.listeners; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class HeadlessAbilityManager implements Listener { + + private final Map headless; + + public HeadlessAbilityManager() { + this.headless = new HashMap<>(); + } + + public void activateAbility(Player attacker, Player attacked) { + attacker.sendMessage(CC.translate("&4&l** HALLOWEENIFY &7[" + attacked.getName() + "] &4&l**")); + attacked.sendMessage(CC.translate("&4&l** HALLOWEENIFY &7[&c" + attacker.getName() + "&7] &4&l**")); + + if (attacked.getInventory().getHelmet() != null) { + headless.put(attacked.getUniqueId(), attacked.getInventory().getHelmet().clone()); + } else { + headless.put(attacked.getUniqueId(), null); + + } + ItemStack pumpkin = new ItemBuilder(Material.JACK_O_LANTERN).setName("&6&lHalloweenify Helmet").addLoreLine("&7&o" + attacker.getName() + "'s Halloweenify Enchant.").colorize().build(); + attacked.getInventory().setHelmet(pumpkin); + Bukkit.getScheduler().runTaskLater(CrankedEnchants.getInstance(), () -> { + if(!headless.containsKey(attacked.getUniqueId())) return; + attacked.getInventory().setHelmet(headless.get(attacked.getUniqueId())); + attacked.sendMessage(CC.translate("&4&l** HALLOWEENIFY &7(Expired) &4&l**")); + headless.remove(attacked.getUniqueId()); + }, 5 * 20L); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamageWhileHeadlessed(EntityDamageByEntityEvent event) { + if(event.getEntity() == null) return; + if(!(event.getEntity() instanceof Player)) return; + + Player victim = ((Player) event.getEntity()); + if(this.headless.containsKey(victim.getUniqueId())) { + CrankedUtils.getInstance().getDamageHandler().reduceDamage(55, event, "HeadlessAbilityNerf"); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onDeath(PlayerDeathEvent event) { + + if (headless.containsKey(event.getEntity().getUniqueId())) { + event.getDrops().add(headless.get(event.getEntity().getUniqueId())); + event.getDrops().removeIf(item -> item.getType() == Material.JACK_O_LANTERN); + event.getEntity().getInventory().setHelmet(null); + headless.remove(event.getEntity().getUniqueId()); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onKick(PlayerKickEvent event) { + if (headless.containsKey(event.getPlayer().getUniqueId())) { + event.getPlayer().getInventory().setHelmet(headless.get(event.getPlayer().getUniqueId())); + headless.remove(event.getPlayer().getUniqueId()); + + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onQuit(PlayerQuitEvent event) { + if (headless.containsKey(event.getPlayer().getUniqueId())) { + event.getPlayer().getInventory().setHelmet(headless.get(event.getPlayer().getUniqueId())); + headless.remove(event.getPlayer().getUniqueId()); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onArmorSwitch(PlayerInteractEvent event) { + if (headless.containsKey(event.getPlayer().getUniqueId()) ) { + if (event.getItem() != null && event.getItem().getType().name().endsWith("_HELMET")) { + event.setCancelled(true); + } + } + } + + @EventHandler + public void onClickHelmet(InventoryClickEvent event) { + if (headless.containsKey(event.getWhoClicked().getUniqueId())) { + if (event.getClickedInventory() == event.getWhoClicked().getInventory() && event.getSlot() == 39) { + event.setCancelled(true); + } + } + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/ItemListener.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/ItemListener.java new file mode 100644 index 0000000..c313f21 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/ItemListener.java @@ -0,0 +1,543 @@ +package net.crankedpvp.crankedenchants.listeners; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.inventories.OmniBlackScrollUI; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.cache.SoulModeCache; +import net.crankedpvp.crankedenchants.struct.cache.SoulTrackerCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.*; +import net.crankedpvp.crankedenchants.struct.souls.SoulManager; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class ItemListener implements Listener { + + private final List renameTagList; + + private final SoulManager soulManager; + + public ItemListener(CrankedEnchants plugin) { + this.renameTagList = new ArrayList<>(); + this.soulManager = plugin.getSoulManager(); + } + + @EventHandler + public void onDustApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + if (!CrankedEnchantsAPI.isDust(event.getCursor()) || !CrankedEnchantsAPI.isEnchantBook(event.getCurrentItem())) + return; + + event.setCancelled(true); + + BookBuilder bookBuilder = new BookBuilder(event.getCurrentItem()); + + if (bookBuilder.getSuccessRate() == 100) return; + + DustBuilder dustBuilder = new DustBuilder(event.getCursor()); + + if (dustBuilder.getEnchantTier() != bookBuilder.getBookEnchantment().getTier()) return; + + ItemStack itemStack = bookBuilder.addSuccessRate(dustBuilder.getPercent()).build(); + + event.setCurrentItem(itemStack); + + if (event.getCursor().getAmount() > 1) { + event.getCursor().setAmount(event.getCursor().getAmount() - 1); + } else { + event.setCursor(null); + } + } + + @EventHandler + public void onInfernalDustApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + if (!CrankedEnchantsAPI.isInfernalDust(event.getCursor()) || !CrankedEnchantsAPI.isEnchantBook(event.getCurrentItem())) + return; + + event.setCancelled(true); + + BookBuilder bookBuilder = new BookBuilder(event.getCurrentItem()); + + if (bookBuilder.getSuccessRate() == 100) return; + + InfernalDustBuilder infernalDustBuilder = new InfernalDustBuilder(event.getCursor()); + + if (infernalDustBuilder.getEnchantTier() != bookBuilder.getBookEnchantment().getTier()) return; + + ItemStack itemStack = bookBuilder.setSuccessRate(100).build(); + + event.setCurrentItem(itemStack); + + if (event.getCursor().getAmount() > 1) { + event.getCursor().setAmount(event.getCursor().getAmount() - 1); + } else { + event.setCursor(null); + } + } + + @EventHandler + public void onHeroicBlackScrollApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (!CrankedEnchantsAPI.isHeroicBlackScroll(event.getCursor()) || !ItemUtils.isEnchantable(event.getCurrentItem())) { + return; + } + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + event.setCancelled(true); + + if (!InventoryUtils.hasAvailableSlot(player)) { + Language.FULL_INVENTORY.send(player); + return; + } + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + + if (!enchantedItemBuilder.hasEnchantments()) { + Language.DOESNT_HAVE_ANY_ENCHANTMENTS.send(player); + return; + } + + HeroicBlackScrollBuilder blackScrollBuilder = new HeroicBlackScrollBuilder(event.getCursor()); + Enchantment enchantToRemove = enchantedItemBuilder.selectRandomEnchantment(); + + BookBuilder bookBuilder = new BookBuilder(enchantToRemove, Math.min(enchantedItemBuilder.getEnchantmentLevel(enchantToRemove), enchantToRemove.getMax())); + + enchantedItemBuilder.removeEnchantment(enchantToRemove); + + player.getInventory().addItem(bookBuilder.setSuccessRate(blackScrollBuilder.getPercent()).setDestroyRate(100 - blackScrollBuilder.getPercent()).build()); + + event.setCurrentItem(enchantedItemBuilder.build()); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + } + + @EventHandler + public void onOmniBlackScrollApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (!CrankedEnchantsAPI.isOmniBlackScroll(event.getCursor()) || !ItemUtils.isEnchantable(event.getCurrentItem())) { + return; + } + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + event.setCancelled(true); + + if (!InventoryUtils.hasAvailableSlot(player)) { + Language.FULL_INVENTORY.send(player); + return; + } + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + + if (!enchantedItemBuilder.hasEnchantments()) { + Language.DOESNT_HAVE_ANY_ENCHANTMENTS.send(player); + return; + } + + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + OmniBlackScrollUI omniBlackScrollUI = new OmniBlackScrollUI(enchantedItemBuilder.getEnchantments(), event); + omniBlackScrollUI.getGui().open(event.getWhoClicked()); + } + + @EventHandler + public void onBlackScrollApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (!CrankedEnchantsAPI.isBlackScroll(event.getCursor()) || !ItemUtils.isEnchantable(event.getCurrentItem())) { + return; + } + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + event.setCancelled(true); + + if (!InventoryUtils.hasAvailableSlot(player)) { + Language.FULL_INVENTORY.send(player); + return; + } + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + + if (!enchantedItemBuilder.hasEnchantments()) { + Language.DOESNT_HAVE_ANY_ENCHANTMENTS.send(player); + return; + } + + + + if(enchantedItemBuilder.getEnchantments().keySet().stream().noneMatch(enchantment -> enchantment.getTier() != EnchantTier.HEROIC)) { + Language.ONLY_HAS_HEROIC_ENCHANTMENTS.send(player); + return; + } + + BlackScrollBuilder blackScrollBuilder = new BlackScrollBuilder(event.getCursor()); + Enchantment enchantToRemove = enchantedItemBuilder.selectRandomEnchantment(EnchantTier.HEROIC); + + BookBuilder bookBuilder = new BookBuilder(enchantToRemove, Math.min(enchantedItemBuilder.getEnchantmentLevel(enchantToRemove), enchantToRemove.getMax())); + + enchantedItemBuilder.removeEnchantment(enchantToRemove); + + player.getInventory().addItem(bookBuilder.setSuccessRate(blackScrollBuilder.getPercent()).setDestroyRate(100 - blackScrollBuilder.getPercent()).build()); + + event.setCurrentItem(enchantedItemBuilder.build()); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + } + + @EventHandler + public void onOrbClick(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (!CrankedEnchantsAPI.isEnchantmentOrb(event.getItem())) return; + event.setCancelled(true); + } + + @EventHandler + public void onOrbApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (!CrankedEnchantsAPI.isEnchantmentOrb(event.getCursor()) || !ItemUtils.isEnchantable(event.getCurrentItem())) { + return; + } + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + OrbBuilder orbBuilder = new OrbBuilder(event.getCursor()); + int slots = orbBuilder.getSlots(); + int success = orbBuilder.getSuccessRate(); + + event.setCancelled(true); + + if (!orbBuilder.getOrbType().canBeAppliedToItem(event.getCurrentItem())) { + return; + } + + if (enchantedItemBuilder.getSlots() >= orbBuilder.getSlots()) { + return; + } + + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + + if (success < this.generateChance()) { + return; + } + + enchantedItemBuilder.updateSlotsLore(slots); + enchantedItemBuilder.setSlots(slots); + event.setCurrentItem(enchantedItemBuilder.build()); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @EventHandler + public void onWhiteScrollApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (!CrankedEnchantsAPI.isWhiteScroll(event.getCursor()) || !ItemUtils.isEnchantable(event.getCurrentItem())) { + return; + } + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + + event.setCancelled(true); + + if (enchantedItemBuilder.isProtected()) { + return; + } + + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + + enchantedItemBuilder.setProtected(true); + event.setCurrentItem(enchantedItemBuilder.build()); + } + + @EventHandler + public void onWhiteScrollClick(PlayerInteractEvent event) { + if (event.getItem() == null || event.getItem().getType() == Material.AIR) return; + if (!CrankedEnchantsAPI.isWhiteScroll(event.getItem())) return; + + if(event.isCancelled()) return; + event.setCancelled(true); + event.getPlayer().updateInventory(); + } + + @EventHandler + public void onTransmogScrollApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + //if(event.isCancelled()) return; + // if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (!CrankedEnchantsAPI.isTransmogScroll(event.getCursor()) || !ItemUtils.isEnchantable(event.getCurrentItem())) { + return; + } + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + + event.setCancelled(true); + + if (!enchantedItemBuilder.hasEnchantments()) { + return; + } + + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + + event.setCurrentItem(enchantedItemBuilder.sortEnchantLore().addEnchantAmountToName().build()); + } + + @EventHandler + public void onRandomizationScrollApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (!CrankedEnchantsAPI.isRandomizationScroll(event.getCursor()) || !CrankedEnchantsAPI.isEnchantBook(event.getCurrentItem())) { + return; + } + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + + BookBuilder bookBuilder = new BookBuilder(event.getCurrentItem()); + RandomizationScrollBuilder randomizationScrollBuilder = new RandomizationScrollBuilder(event.getCursor()); + + event.setCancelled(true); + + if (bookBuilder.getBookEnchantment().getTier() != randomizationScrollBuilder.getTier()) return; + + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + + event.setCurrentItem(bookBuilder.setSuccessRate(this.generateChance()).setDestroyRate(this.generateChance()).build()); + } + + @EventHandler + public void onSoulTrackerApply(InventoryClickEvent event) { + if (event.getCurrentItem() == null || event.getCursor() == null) return; + Player player = (Player) event.getWhoClicked(); + if (player.getGameMode() != GameMode.SURVIVAL) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (!CrankedEnchantsAPI.isSoulTracker(event.getCursor()) || !ItemUtils.isWeapon(event.getCurrentItem())) { + return; + } + // if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + SoulTrackerBuilder soulTrackerBuilder = new SoulTrackerBuilder(event.getCursor()); + + event.setCancelled(true); + + if (enchantedItemBuilder.hasSoulTrackerAlreadyApplied()) { + Language.ALREADY_HAS_SOUL_TRACKER.send(player); + return; + } + + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + + event.setCurrentItem(enchantedItemBuilder.applySoulTracker(soulTrackerBuilder).build()); + Language.SOUL_TRACKER_APPLIED.send(player, str -> str + .replace("{soul-tracker}", soulTrackerBuilder.getEnchantTier().getColor() + "&l" + soulTrackerBuilder.getEnchantTier().getFormatedName()) + .replace("{item}", StringUtils.toNiceString(event.getCurrentItem().getType().name())) + ); + } + + @EventHandler + public void onLeave(PlayerQuitEvent event) { + this.renameTagList.remove(event.getPlayer()); + } + + @EventHandler + public void onLeave(PlayerKickEvent event) { + this.renameTagList.remove(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onChat(AsyncPlayerChatEvent event) { + if (!this.renameTagList.contains(event.getPlayer())) return; + event.setCancelled(true); + + Player player = event.getPlayer(); + + if (player.getItemInHand() == null || player.getItemInHand().getType() == Material.AIR) { + Language.EMPTY_HAND.send(player); + return; + } + + if (!ItemUtils.isEnchantable(event.getPlayer().getItemInHand())) return; + + this.renameTagList.remove(event.getPlayer()); + Language.SUCCESSFULLY_RENAMED.send(player, str -> str.replace("{new-name}", CC.translate(event.getMessage()))); + player.setItemInHand(new ItemBuilder(player.getItemInHand()).setName(event.getMessage()).colorizeName().build()); + } + + @EventHandler + public void onPlayerDeathUpdateSoulTracker(PlayerDeathEvent event) { + Player killer = event.getEntity().getKiller(); + + if (killer == null) return; + + ItemStack itemStack = killer.getItemInHand(); + + if (killer.getItemInHand() == null) return; + if (!ItemUtils.isWeapon(itemStack)) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasSoulTrackerAlreadyApplied()) return; + + SoulTrackerCache soulTrackerCache = CacheUtils.getSoulTrackerCache(killer); + + if (soulTrackerCache.isOnHarvestCooldown(event.getEntity())) { + Language.SOUL_HARVEST_COOLDOWN.send(killer, str -> str + .replace("{player}", event.getEntity().getName()) + .replace("{time}", TimeUtils.formatSeconds(soulTrackerCache.getSecondsLeftOnHarvestCooldown(event.getEntity()))) + ); + return; + } + + soulTrackerCache.addHarvestCooldown(event.getEntity()); + + enchantedItemBuilder.incrementHarvestedSouls(); + enchantedItemBuilder.updateSoulsHarvested(); + + killer.setItemInHand(enchantedItemBuilder.build()); + killer.updateInventory(); + } + + @EventHandler(priority = EventPriority.LOW) + public void onRenameTagClick(PlayerInteractEvent event) { + if (event.getItem() == null || event.getItem().getType() == Material.AIR) return; + if (!CrankedEnchantsAPI.isRenameTag(event.getItem())) return; + + event.setCancelled(true); + Player player = event.getPlayer(); + + if (this.renameTagList.contains(player)) return; + + if (event.getItem().getAmount() > 1) { + event.getItem().setAmount(event.getItem().getAmount() - 1); + } else { + player.setItemInHand(null); + } + + this.renameTagList.add(player); + Language.RENAME_TAG_CLICKED.send(player); + } + + @EventHandler(priority = EventPriority.LOW) + public void onSecretDustClick(PlayerInteractEvent event) { + if (event.getItem() == null || event.getItem().getType() == Material.AIR) return; + if (!CrankedEnchantsAPI.isSecretDust(event.getItem())) return; + + event.setCancelled(true); + Player player = event.getPlayer(); + + if (!InventoryUtils.hasAvailableSlot(player)) { + Language.FULL_INVENTORY.send(player); + return; + } + + if (event.getItem().getAmount() > 1) { + event.getItem().setAmount(event.getItem().getAmount() - 1); + } else { + player.setItemInHand(null); + } + + SecretDust secretDust = new SecretDust(event.getItem()); + player.getInventory().addItem(secretDust.getDust()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onSoulPearlClick(PlayerInteractEvent event) { + if (event.isCancelled()) return; + if (event.getItem() == null || event.getItem().getType() == Material.AIR) return; + if (!CrankedEnchantsAPI.isSoulPearl(event.getItem())) return; + + Player player = event.getPlayer(); + SoulModeCache soulModeCache = this.soulManager.getSoulModeCache(player); + + if (soulModeCache == null || soulModeCache.getSouls() < 5) { + event.setCancelled(true); + player.setItemInHand(event.getItem()); + player.updateInventory(); + Language.OUT_OF_SOULS.send(player); + player.playSound(player.getLocation(), Sound.ITEM_BREAK, 0.7f, 0.4f); + return; + } + + if (player.getItemInHand() == null) { + player.setItemInHand(new SoulPearlBuilder().build()); + } else { + player.getItemInHand().setAmount(event.getItem().getAmount() + 1); + } + + player.updateInventory(); + + soulModeCache.getSoulGemBuilder().removeSouls(5); + soulModeCache.updateSoulGem(); + } + + private int generateChance() { + Random random = new Random(); + return random.nextInt(101); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/SoulListener.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/SoulListener.java new file mode 100644 index 0000000..f96ef89 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/SoulListener.java @@ -0,0 +1,193 @@ +package net.crankedpvp.crankedenchants.listeners; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.items.SoulGemBuilder; +import net.crankedpvp.crankedenchants.struct.souls.SoulManager; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; + +public class SoulListener implements Listener { + + private final SoulManager soulManager; + + public SoulListener(CrankedEnchants plugin) { + this.soulManager = plugin.getSoulManager(); + } + + @EventHandler(priority= EventPriority.HIGHEST, ignoreCancelled=true) + public void onInventoryCombineSoulGems(InventoryClickEvent event) { + if (!CrankedEnchantsAPI.isSoulGem(event.getCursor())) return; + if (!CrankedEnchantsAPI.isSoulGem(event.getCurrentItem())) return; + + Player player = (Player)event.getWhoClicked(); + + if (event.getCurrentItem().getAmount() > 1) { + event.setCancelled(true); + return; + } + + if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + + SoulGemBuilder cursorSoulGem = new SoulGemBuilder(event.getCursor()); + SoulGemBuilder currentSoulGem = new SoulGemBuilder(event.getCurrentItem()); + + int cursorSouls = cursorSoulGem.getSouls(); + + event.setCancelled(true); + + if (event.getCursor().getAmount() > 1) { + event.getCursor().setAmount(event.getCursor().getAmount() - 1); + } else { + player.setItemOnCursor(null); + } + soulManager.disableSoulMode(player); + currentSoulGem.addSouls(cursorSouls); + event.setCurrentItem(currentSoulGem.build()); + player.playSound(player.getLocation(), Sound.ANVIL_USE, 1.0f, 1.4f); + player.updateInventory(); + + } + + @EventHandler + public void onInventoryClickSoulGem(InventoryClickEvent event) { + if (event.getSlot() < 0) return; + + ItemStack currentItemStack = event.getCurrentItem(); + Player player = ((Player) event.getWhoClicked()); + + if (!this.soulManager.isInSoulMode(player)) return; + + int slot = event.getSlot(); + + if (CrankedEnchantsAPI.isSoulGem(currentItemStack) && (event.getAction().name().startsWith("PICKUP") || event.getAction().name().startsWith("DROP"))) { + + if (slot != this.soulManager.getSoulModeCache(player).getSlot()) { + return; + } + + this.soulManager.disableSoulMode(player); + return; + } + + if (event.getAction() != InventoryAction.HOTBAR_SWAP) return; + + int hotbarButton = event.getHotbarButton(); + + if (hotbarButton == -1) return; + if (hotbarButton == slot) return; + + ItemStack hotbarItemStack = player.getInventory().getItem(hotbarButton); + boolean isHotBarItemSoulGem = CrankedEnchantsAPI.isSoulGem(hotbarItemStack); + boolean isCurrentItemSoulGem = CrankedEnchantsAPI.isSoulGem(currentItemStack); + boolean isHotBarSlotDifferentToCacheSlot = hotbarButton != this.soulManager.getSoulModeCache(player).getSlot(); + boolean isCurrentSlotDifferentToCacheSlot = slot != this.soulManager.getSoulModeCache(player).getSlot(); + + if (isHotBarItemSoulGem && isCurrentItemSoulGem) { + if (isCurrentSlotDifferentToCacheSlot && isHotBarSlotDifferentToCacheSlot) + return; + + if (!(event.getClickedInventory() instanceof PlayerInventory)) { + this.soulManager.disableSoulMode(player); + return; + } + + + int newSlot = isCurrentSlotDifferentToCacheSlot ? slot : hotbarButton; + this.soulManager.getSoulModeCache(player).setSlot(newSlot); + } + + if (isHotBarItemSoulGem) { + if (isHotBarSlotDifferentToCacheSlot) + return; + + if (!(event.getClickedInventory() instanceof PlayerInventory)) { + this.soulManager.disableSoulMode(player); + return; + } + + this.soulManager.getSoulModeCache(player).setSlot(slot); + } + + if (isCurrentItemSoulGem) { + if (isCurrentSlotDifferentToCacheSlot) + return; + + if (!(event.getClickedInventory() instanceof PlayerInventory)) { + this.soulManager.disableSoulMode(player); + return; + } + + this.soulManager.getSoulModeCache(player).setSlot(hotbarButton); + } + } + + @EventHandler + public void onDropSoulsWhileInSoulMode(PlayerDropItemEvent event) { + if (!CrankedEnchantsAPI.isSoulGem(event.getItemDrop().getItemStack())) return; + Player player = event.getPlayer(); + int slot = player.getInventory().getHeldItemSlot(); + if (this.soulManager.isInSoulMode(player) && slot != this.soulManager.getSoulModeCache(player).getSlot()) { + return; + } + this.soulManager.disableSoulMode(event.getPlayer()); + } + + @EventHandler + public void onPlayerToggleSoulMode(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (!event.hasItem()) return; + if (!CrankedEnchantsAPI.isSoulGem(event.getItem())) return; + Player player = event.getPlayer(); + int slot = player.getInventory().getHeldItemSlot(); + //if(event.isCancelled()) return; + SoulGemBuilder soulGemBuilder = new SoulGemBuilder(event.getItem()); + + if (!this.soulManager.isInSoulMode(player) && soulGemBuilder.getSouls() <= 0) { + if(soulGemBuilder.getSouls() < 100000) { + soulGemBuilder.setSouls(500000); + this.soulManager.toggleSoulMode(player, soulGemBuilder, slot); + return; + } + Language.OUT_OF_SOULS.send(player); + player.playSound(player.getLocation(), Sound.ITEM_BREAK, 0.7f, 0.4f); + return; + } + + if (this.soulManager.isInSoulMode(player) && slot != this.soulManager.getSoulModeCache(player).getSlot()) { + Language.CLICKED_WRONG_SOUL_GEM.send(player); + return; + } + this.soulManager.toggleSoulMode(player, soulGemBuilder, slot); + } + + @EventHandler + public void onDisconnectWhileInSoulMode(PlayerQuitEvent event) { + this.soulManager.disableSoulMode(event.getPlayer()); + } + + @EventHandler + public void onDisconnectWhileInSoulMode(PlayerKickEvent event) { + this.soulManager.disableSoulMode(event.getPlayer()); + } + + @EventHandler + public void onPlayerDeathWhileInSoulMode(PlayerDeathEvent event) { + this.soulManager.disableSoulMode(event.getEntity()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/TinkererListeners.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/TinkererListeners.java new file mode 100644 index 0000000..1f6c174 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/TinkererListeners.java @@ -0,0 +1,139 @@ +package net.crankedpvp.crankedenchants.listeners; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.items.BookBuilder; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.struct.items.MiscItems; +import net.crankedpvp.crankedenchants.struct.items.SecretDust; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class TinkererListeners implements Listener { + + @EventHandler + public void onClickInTinkerer(InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + if (event.getCurrentItem() == null) return; + if (!event.getInventory().getName().equals(" You | Tinkerer")) return; + if (!(event.getClickedInventory() instanceof PlayerInventory) && !event.getClickedInventory().getName().equals(" You | Tinkerer")) return; + if(event.isCancelled()) return; + event.setCancelled(true); + + if (event.getCurrentItem() == null) return; + if (event.getCurrentItem().getType() == Material.AIR) return; + if (!ItemUtils.isEnchantable(event.getCurrentItem()) && !CrankedEnchantsAPI.isEnchantBook(event.getCurrentItem())) return; + + if (ItemUtils.isEnchantable(event.getCurrentItem())) { + NBTItem nbtItem = new NBTItem(event.getCurrentItem()); + + if (!this.hasXPValue(nbtItem)) { + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(event.getCurrentItem()); + nbtItem.setInteger("xp-value", this.generateXPValue(enchantedItemBuilder.getAmountOfEnchantments())); + } + + event.setCurrentItem(nbtItem.getItem()); + } + + Inventory tinkerer = event.getInventory(); + + if (event.getClickedInventory() instanceof PlayerInventory) { + if (this.isTinkererFull(tinkerer)) return; + this.addItemToTinkererLeftSide(tinkerer, event.getCurrentItem()); + + if (CrankedEnchantsAPI.isEnchantBook(event.getCurrentItem())) { + BookBuilder bookBuilder = new BookBuilder(event.getCurrentItem()); + ItemStack itemStack = new SecretDust(bookBuilder.getBookEnchantment().getTier(), bookBuilder.getDustValue()).build(); + this.addItemToTinkererRightSide(tinkerer, itemStack); + } else { + NBTItem nbtItem = new NBTItem(event.getCurrentItem()); + ItemStack itemStack = MiscItems.getTinkererDisplayXpBottle(nbtItem.getInteger("xp-value")); + this.addItemToTinkererRightSide(tinkerer, itemStack); + } + + event.setCurrentItem(null); + } else { + event.getWhoClicked().getInventory().addItem(event.getCurrentItem()); + + int slotToDelete = event.getSlot() <= 5 ? 4 : 5; + + tinkerer.setItem(event.getSlot() + slotToDelete, null); + event.setCurrentItem(null); + } + } + + @EventHandler + public void onTinkererClose(InventoryCloseEvent event) { + if (!event.getInventory().getName().equals(" You | Tinkerer")) return; + if (!(event.getPlayer() instanceof Player)) return; + InventoryUtils.giveItemToPlayer((Player) event.getPlayer(), this.getItemToTinkererLeftSide(event.getInventory())); + } + + private void addItemToTinkererLeftSide(Inventory tinkerer, ItemStack itemStack) { + for (int i = 0; i < 54; i += 9) { + for (int j = 0; j < 4; j++) { + if (tinkerer.getItem(i + j) != null) continue; + tinkerer.setItem(i + j, itemStack); + return; + } + } + } + + private void addItemToTinkererRightSide(Inventory tinkerer, ItemStack itemStack) { + for (int i = 5; i < 54; i += 9) { + for (int j = 0; j < 4; j++) { + if (tinkerer.getItem(i + j) != null) continue; + tinkerer.setItem(i + j, itemStack); + return; + } + } + } + + public List getItemToTinkererLeftSide(Inventory tinkerer) { + List itemsList = new ArrayList<>(); + for (int i = 0; i < 54; i += 9) { + for (int j = 0; j < 4; j++) { + if (tinkerer.getItem(i + j) == null) continue; + if (tinkerer.getItem(i + j).getType() == Material.STAINED_GLASS_PANE) continue; + itemsList.add(tinkerer.getItem(i + j)); + } + } + return itemsList; + } + + private boolean isTinkererFull(Inventory tinkerer) { + for (int i = 0; i < 54; i += 9) { + for (int j = 0; j < 5; j++) { + if (tinkerer.getItem(i + j) != null) continue; + return false; + } + } + return true; + } + + private boolean hasXPValue(NBTItem itemStack) { + return itemStack.hasKey("xp-value"); + } + + private int generateXPValue(int numberOfCustomEnchants) { + Random random = new Random(); + + int bound = numberOfCustomEnchants == 0 ? 180 : numberOfCustomEnchants * 100; + int min = numberOfCustomEnchants == 0 ? 20 : 300; + + return random.nextInt(bound) + min; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/WeaponCacheListener.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/WeaponCacheListener.java new file mode 100644 index 0000000..5793b2b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/listeners/WeaponCacheListener.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedenchants.listeners; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryInteractEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.inventory.ItemStack; + +public class WeaponCacheListener implements Listener { + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/EnchantRegister.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/EnchantRegister.java new file mode 100644 index 0000000..60b13db --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/EnchantRegister.java @@ -0,0 +1,144 @@ +package net.crankedpvp.crankedenchants.struct; + + +import com.google.common.collect.ImmutableList; +import lombok.Getter; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.enchantments.cursed.*; +import net.crankedpvp.crankedenchants.enchantments.elite.*; +import net.crankedpvp.crankedenchants.enchantments.heroic.*; +import net.crankedpvp.crankedenchants.enchantments.legendary.*; +import net.crankedpvp.crankedenchants.enchantments.simple.*; +import net.crankedpvp.crankedenchants.enchantments.soul.*; +import net.crankedpvp.crankedenchants.enchantments.ultimate.*; +import net.crankedpvp.crankedenchants.enchantments.unique.*; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.event.HandlerList; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +public class EnchantRegister { + + @Getter + private static EnchantRegister instance; + private final CrankedEnchants plugin; + private final Map enchantments; + + + public EnchantRegister(CrankedEnchants plugin) { + instance = this; + this.plugin = plugin; + this.enchantments = new HashMap<>(); + } + + public void initialize() { + registerAll( + new Aquatic(), new Gears(), new Glowing(), new AutoSmelt(), new EnderShift(), new CreeperArmor(), new Spirits(), new Ghost(), new FeatherWeight(), + new Obliterate(), new ThunderingBlow(), new Aegis(), new AntiGravity(), new Bleed(), + new Blessed(), new Insomnia(), new Entangle(), new Frozen(), new Haste(), new Blind(), + new Implants(), new Trap(), new RocketEscape(), new Cactus(), new Teleportation(), new Voodoo(), new Angelic(), + new Shockwave(), new Dodge(), new DoubleStrike(), new Guardians(), new Valor(), new Tank(), new ObsidianDestroyer(), new ObsidianShield(), new Metaphysical(), + new Armored(), new BloodLust(), new Deathbringer(), new Diminish(), new Drunk(), new Enlighted(), + new Execute(), new Overload(), new Inquisitive(), new Insanity(), new Lifesteal(), new Rage(), new BossSlayer(), + new Silence(), new Confusion(), new Springs(), new RepairGuard(), new IceAspect(), new Demonforged(), new Reforged(), new Hardened(), + new Wither(), new Vampire(), new Poison(), new Poisoned(), new Stormcaller(), new Solitude(), new Experience(), new Oxygenate(), new Lifebloom(), + new Curse(), new SkillSwipe(), new Ravenous(), new Molten(), new Berserk(), new SelfDestruct(), new Ragdoll(), new DeepWounds(), new Pummel(), + new Paralyze(), new Greatsword(), new DivineImmolation(), new Dominate(), new Clarity(), new Epicness(), new Decapitation(), new Telepathy(), + new Commander(), new Tray(), new Detonate(), new Teleblock(), new Paradox(), new NaturesWrath(), new DeathGod(), new Barbarian(), + new Inversion(), new Devour(), new Cleave(), new SpiritLink(), new Leadership(), new Disintegrate(), new Protection(), new Blacksmith(), new EnderWalker(), + new Assassin(), new Destruction(), new PlagueCarrier(), new SelfDestruct(), new UndeadRuse(), new Heavy(), new ArrowDeflect(), new Block(), new SmokeBomb(), + new Enrage(), new AntiCactus(), new Immortal(), new AntiGank(), new Headless(), new Lucky(), new Abyss(), new Fat(), new Judgement() + ); + + //register heroic enchantments + registerAll(new AtomicDetonate(), new GodlyOverload(), new DivineEnlighted(), new EtherealDodge(), new PlanetaryDeathbringer(), new SoulHardened(), + new DeepBleed(), new PolymorphicMetaphysical(), new ShadowAssassin(), new PermanentExecute()); + //this.register(new Platemail()); + } + + public void registerAll(Enchantment... enchantments) { + for (Enchantment enchantment : enchantments) { + register(enchantment); + } + } + + public void register(Enchantment enchantment) { + try { + this.enchantments.put(enchantment.getID(), enchantment); + this.plugin.getServer().getPluginManager().registerEvents(enchantment, plugin); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register enchantment " + enchantment.getName()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.enchantments.forEach(((enchantName, enchantment) -> HandlerList.unregisterAll(enchantment))); + this.enchantments.clear(); + } + + public void unregister(Enchantment enchantment) { + HandlerList.unregisterAll(enchantment); + this.enchantments.remove(enchantment.getName()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isEnchantment(String name) { + return (getEnchantmentFromID(name) != null); + } + + public Enchantment getEnchantmentFromID(String id) { + Validate.notNull(id); + Validate.notEmpty(id); + return this.enchantments.get(id.toLowerCase()); + } + + public Enchantment getEnchantmentFromName(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + name = this.getEnchantIDFromName(name); + return this.enchantments.get(name.toLowerCase()); + } + + public String getEnchantIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getEnchantments(EnchantTier tier) { + Validate.notNull(tier); + return getEnchantments().stream().filter(customEnchantment -> (customEnchantment.getTier() == tier)).collect(Collectors.toList()); + } + + public Collection getEnchantments(GearType type) { + Validate.notNull(type); + return getEnchantments().stream().filter(customEnchantment -> (customEnchantment.getType() == type)).collect(Collectors.toList()); + } + + public Collection getOrderedEnchantments(GearType type) { + Validate.notNull(type); + return getEnchantments().stream().filter(customEnchantment -> (customEnchantment.getType() == type)).sorted(Comparator.comparing(Enchantment::getTier)).collect(Collectors.toList()); + } + + public List getOrderedEnchantments(EnchantTier tier) { + Validate.notNull(tier); + return getEnchantments().stream().filter(customEnchantment -> (customEnchantment.getTier() == tier)).sorted(Comparator.comparing(Enchantment::getID)).collect(Collectors.toList()); + } + + public Collection getEnchantments() { + return Collections.unmodifiableCollection(this.enchantments.values()); + } + public Enchantment selectRandomEnchantment(EnchantTier enchantTier) { + Collection enchantments = this.getEnchantments(enchantTier); + return (enchantments.size() > 0) ? ImmutableList.copyOf(enchantments).get(ThreadLocalRandom.current().nextInt(enchantments.size())) : null; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/NbtTags.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/NbtTags.java new file mode 100644 index 0000000..53f3b22 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/NbtTags.java @@ -0,0 +1,34 @@ +package net.crankedpvp.crankedenchants.struct; + +public class NbtTags { + + public static final String DATA_STRING = "cosmicData"; + public static final String ENCHANTMENT_CACHE_ID = "enchantments"; + public static final String WEAPON_ENCHANTMENT_CACHE_ID = "weaponEnchantments"; + public static final String WEAK_SHOT_CACHE_ID = "weak_shot"; + public static final String BLACK_SCROLL_DATA_STRING = "blackScroll"; + public static final String OMNI_BLACK_SCROLL_DATA_STRING = "omniBlackScroll"; + public static final String HEROIC_BLACK_SCROLL_DATA_STRING = "heroicBlackScroll"; + public static final String ENCHANT_BOOK_DATA_STRING = "enchantBook"; + public static final String SUCCESS_RATE_STRING = "successRate"; + public static final String DESTROY_RATE_STRING = "destroyRate"; + public static final String DUST_DATA_STRING = "dust"; + public static final String INFERNAL_DUST_DATA_STRING = "infernalDust"; + public static final String ORB_DATA_STRING = "orb"; + public static final String WHITE_SCROLL_DATA_STRING = "whiteScroll"; + public static final String RENAME_TAG_DATA_STRING = "renameTag"; + public static final String TRANSMOG_SCROLL_DATA_STRING = "transmogScroll"; + public static final String RANDOMIZATION_SCROLL_DATA_STRING = "randomizationScroll"; + public final static String ENCHANTS_TAG = "CustomEnchants"; + public static final String BOOK_DATA_STRING = "randomEnchantBook"; + public static final String SECRET_DUST_DATA_STRING = "secretDustBook"; + public static final String BOOK_TIER_DATA_STRING = "bookTier"; + public static final String SOUL_GEM_DATA_STRING = "soulGem"; + public static final String SOUL_PEARL_DATA_STRING = "soulPearl"; + public static final String SOUL_TRACKER_DATA_STRING = "soulTracker"; + public static final String SLOTS_AMOUNT_STRING = "slots"; + public static final String ORB_TYPE_STRING = "orbType"; + public static final String PROTECTED_STRING = "protected"; + + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/annotations/ConfigValue.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/annotations/ConfigValue.java new file mode 100644 index 0000000..8e29685 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/annotations/ConfigValue.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedenchants.struct.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * don't forget to not make the field final when using this annotation + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigValue { + + String path() default "enchant."; + String name() default ""; + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/EnchantInfo.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/EnchantInfo.java new file mode 100644 index 0000000..488bc34 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/EnchantInfo.java @@ -0,0 +1,31 @@ +package net.crankedpvp.crankedenchants.struct.cache; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class EnchantInfo { + + private Integer level; + private Integer amount; + + public void addToCurrentLevel(int level) { + this.level += level; + } + + public void removeFromCurrentLevel(int level) { + this.level -= level; + } + + public void incrementAmount() { + this.amount++; + } + + public void decrementAmount() { + this.amount--; + } +} + diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/EnchantmentCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/EnchantmentCache.java new file mode 100644 index 0000000..7a18bba --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/EnchantmentCache.java @@ -0,0 +1,78 @@ +package net.crankedpvp.crankedenchants.struct.cache; + +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.cache.Cache; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +public class EnchantmentCache extends Cache { + + private final HashMap playerEnchantments; + + public EnchantmentCache() { + super(NbtTags.ENCHANTMENT_CACHE_ID); + this.playerEnchantments = new HashMap<>(); + } + + + public boolean hasEnchantment(Enchantment enchantment) { + if (enchantment == null) return false; + return this.playerEnchantments.containsKey(enchantment.getID()); + } + + public boolean hasEnchantment(String enchantmentID) { + return this.playerEnchantments.containsKey(enchantmentID); + } + + public EnchantInfo getEnchantInfo(Enchantment enchantment) { + return this.playerEnchantments.get(enchantment.getID()); + } + + public EnchantInfo getEnchantInfo(String enchantmentID) { + return this.playerEnchantments.get(enchantmentID); + } + + public void removeEnchantment(Enchantment enchantment, int level) { + if (enchantment == null) return; + if (!this.hasEnchantment(enchantment)) return; + + if (this.getEnchantInfo(enchantment).getAmount() > 1) { + this.getEnchantInfo(enchantment).decrementAmount(); + this.getEnchantInfo(enchantment).removeFromCurrentLevel(level); + return; + } + + this.playerEnchantments.remove(enchantment.getID()); + } + + public void addEnchantment(Enchantment enchantment, int level) { + if (enchantment == null) return; + if (this.hasEnchantment(enchantment) && enchantment.isStackable()) { + this.getEnchantInfo(enchantment).incrementAmount(); + this.getEnchantInfo(enchantment).addToCurrentLevel(level); + return; + } + + this.playerEnchantments.put(enchantment.getID(), new EnchantInfo(level, 1)); + } + + public void clearEnchantments() { + this.playerEnchantments.clear(); + } + + public Set getEnchants() { + Set enchants = new HashSet<>(); + for (String enchantName : this.playerEnchantments.keySet()) { + enchants.add(EnchantRegister.getInstance().getEnchantmentFromID(enchantName)); + } + return enchants; + } + + public Set getEnchantIDs() { + return this.playerEnchantments.keySet(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/SoulModeCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/SoulModeCache.java new file mode 100644 index 0000000..1a400b6 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/SoulModeCache.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedenchants.struct.cache; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.items.SoulGemBuilder; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.entity.Player; + +@Getter +public class SoulModeCache { + + @Setter + private int slot; + private final SoulGemBuilder soulGemBuilder; + private final Player player; + + public SoulModeCache(Player player, SoulGemBuilder soulGemBuilder, int slot) { + this.soulGemBuilder = soulGemBuilder; + this.slot = slot; + this.player = player; + } + + public int getSouls() { + return this.soulGemBuilder.getSouls(); + } + + public boolean hasEnoughSouls(int soulCost) { + return this.getSouls() >= soulCost; + } + + public void updateSoulGem() { + if (!CrankedEnchantsAPI.isSoulGem(player.getInventory().getItem(this.getSlot()))) return; + player.getInventory().setItem(this.getSlot(), this.getSoulGemBuilder().build()); + //player.updateInventory(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/SoulTrackerCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/SoulTrackerCache.java new file mode 100644 index 0000000..69c9923 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/SoulTrackerCache.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedenchants.struct.cache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +public class SoulTrackerCache extends Cache { + + private final Map soulHarvestCooldowns; + private static final long COOLDOWN = 600000; + + public SoulTrackerCache() { + super("soul-tracker"); + this.soulHarvestCooldowns = new HashMap<>(); + } + + public boolean isOnHarvestCooldown(Player killedPlayer) { + if (!this.soulHarvestCooldowns.containsKey(killedPlayer.getUniqueId())) return false; + return this.soulHarvestCooldowns.get(killedPlayer.getUniqueId()) + 600000 > System.currentTimeMillis(); + } + + public long getSecondsLeftOnHarvestCooldown(Player killedPlayer) { + long claimedTimeStamp = this.soulHarvestCooldowns.get(killedPlayer.getUniqueId()); + long currentTimeStamp = System.currentTimeMillis(); + long difference = currentTimeStamp - claimedTimeStamp; + return difference >= COOLDOWN ? 0L : TimeUnit.MILLISECONDS.toSeconds(COOLDOWN - difference); + } + + public void addHarvestCooldown(Player killedPlayer) { + this.soulHarvestCooldowns.put(killedPlayer.getUniqueId(), System.currentTimeMillis()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/WeaponEnchantCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/WeaponEnchantCache.java new file mode 100644 index 0000000..05c04f8 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/WeaponEnchantCache.java @@ -0,0 +1,92 @@ +package net.crankedpvp.crankedenchants.struct.cache; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.utils.cache.Cache; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +public class WeaponEnchantCache extends Cache { + + @Getter @Setter + private int swordSlot; + private long time; + private final Map playerEnchantments; + + public WeaponEnchantCache() { + super(NbtTags.WEAPON_ENCHANTMENT_CACHE_ID); + this.playerEnchantments = new HashMap<>(); + this.swordSlot = -1; + this.time = 0; + } + + public void invalidateCache() { + this.clearEnchantments(); + this.swordSlot = -1; + } + + public void updateTime() { + this.time = System.currentTimeMillis(); + } + + public boolean shouldRefreshCash() { + return this.time + 10000 < System.currentTimeMillis(); + } + + public boolean hasEnchantment(Enchantment enchantment) { + return this.playerEnchantments.containsKey(enchantment.getID()); + } + + public boolean hasEnchantment(String enchantmentID) { + return this.playerEnchantments.containsKey(enchantmentID); + } + + public Integer getEnchantLevel(Enchantment enchantment) { + return this.playerEnchantments.get(enchantment.getID()); + } + + public Integer getEnchantLevel(String enchantmentID) { + return this.playerEnchantments.get(enchantmentID); + } + + public void removeEnchantment(Enchantment enchantment) { + this.playerEnchantments.remove(enchantment.getID()); + } + + public void addEnchantment(Enchantment enchantment, int level) { + this.playerEnchantments.put(enchantment.getID(), level); + } + + public void addEnchantment(String enchantmentID, int level) { + this.playerEnchantments.put(enchantmentID, level); + } + + public void clearEnchantments() { + this.playerEnchantments.clear(); + } + + public boolean hasEnchants() { + return !this.playerEnchantments.isEmpty(); + } + + public Set getEnchants() { + return this.playerEnchantments.keySet().stream() + .map(enchantID -> EnchantRegister.getInstance().getEnchantmentFromID(enchantID)) + .collect(Collectors.toSet()); + } + + public Map getEnchantsAndLevels() { + return this.playerEnchantments; + } + + public Set getEnchantIDs() { + return this.playerEnchantments.keySet(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/DoubleDamageCooldown.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/DoubleDamageCooldown.java new file mode 100644 index 0000000..cccdae1 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/DoubleDamageCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedenchants.struct.cache.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class DoubleDamageCooldown extends CurrentCooldown { + public DoubleDamageCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/DragonReflectSilenceCooldown.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/DragonReflectSilenceCooldown.java new file mode 100644 index 0000000..1758d8c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/DragonReflectSilenceCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedenchants.struct.cache.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class DragonReflectSilenceCooldown extends CurrentCooldown { + public DragonReflectSilenceCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/EnchantCooldownCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/EnchantCooldownCache.java new file mode 100644 index 0000000..4c289fa --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/EnchantCooldownCache.java @@ -0,0 +1,16 @@ +package net.crankedpvp.crankedenchants.struct.cache.cooldowns; + +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class EnchantCooldownCache extends CurrentCooldown { + + public EnchantCooldownCache(Enchantment enchantment, int duration) { + super("enchant_cooldown_" + enchantment.getID(), duration); + } + + public EnchantCooldownCache(String enchantmentID, int duration) { + super("enchant_cooldown_" + enchantmentID, duration); + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/WeakShotCooldown.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/WeakShotCooldown.java new file mode 100644 index 0000000..9df5f69 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/cooldowns/WeakShotCooldown.java @@ -0,0 +1,11 @@ +package net.crankedpvp.crankedenchants.struct.cache.cooldowns; + +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class WeakShotCooldown extends CurrentCooldown { + + public WeakShotCooldown() { + super(NbtTags.WEAK_SHOT_CACHE_ID, 50); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AbyssCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AbyssCache.java new file mode 100644 index 0000000..084f037 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AbyssCache.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.utils.cache.Cache; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class AbyssCache extends Cache { + + @Getter + @Setter + private boolean isAffected; + + public AbyssCache() { + super("abyss"); + this.isAffected = false; + } + + + public void applyAbyssEffect(Player player, int level) { + player.setWalkSpeed(0.0f); + this.setAffected(true); + Bukkit.getScheduler().runTaskLaterAsynchronously(CrankedEnchants.getInstance(), ()-> { + removeAbyssEffect(player); + }, level* 20L); + } + + public void removeAbyssEffect(Player player) { + player.setWalkSpeed(0.2f); + this.setAffected(false); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AegisCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AegisCache.java new file mode 100644 index 0000000..a1bbe17 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AegisCache.java @@ -0,0 +1,48 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; +import org.bukkit.entity.Player; + +import java.util.HashSet; +import java.util.Set; + +public class AegisCache extends Cache { + + @Getter + private long lastHitTime; + private final Set playerHits; + + public AegisCache() { + super("aegis"); + this.updateHitTime(); + playerHits = new HashSet<>(); + } + + public void updateHitTime() { + this.lastHitTime = System.currentTimeMillis(); + } + + public boolean isStillActive() { + return lastHitTime + 10000L > System.currentTimeMillis(); + } + + public void addPlayerToList(Player player) { + if (playerHits.contains(player)) return; + this.playerHits.add(player); + } + + public void clearPlayers() { + this.playerHits.clear(); + } + + public boolean isPlayerAlreadyInList(Player player) { + return this.playerHits.contains(player); + } + + public int getAmountOfPlayers() { + int players = this.playerHits.size(); + if(players > 5) players = 5; + return players; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AntiGankCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AntiGankCache.java new file mode 100644 index 0000000..6c68037 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/AntiGankCache.java @@ -0,0 +1,46 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; +import org.bukkit.entity.Player; + +import java.util.HashSet; +import java.util.Set; + +public class AntiGankCache extends Cache { + + @Getter + private long lastHitTime; + private final Set playerHits; + + public AntiGankCache() { + super("anti_gank"); + this.updateHitTime(); + playerHits = new HashSet<>(); + } + + public void updateHitTime() { + this.lastHitTime = System.currentTimeMillis(); + } + + public boolean isStillActive() { + return lastHitTime + 20000L > System.currentTimeMillis(); + } + + public void addPlayerToList(Player player) { + if (playerHits.contains(player)) return; + this.playerHits.add(player); + } + + public void clearPlayers() { + this.playerHits.clear(); + } + + public boolean isPlayerAlreadyInList(Player player) { + return this.playerHits.contains(player); + } + + public int getAmountOfPlayers() { + return this.playerHits.size(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/BleedStacksCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/BleedStacksCache.java new file mode 100644 index 0000000..364c170 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/BleedStacksCache.java @@ -0,0 +1,35 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; + +public class BleedStacksCache extends Cache { + + @Getter + private long lastBleedStackTime; + private int bleedStack; + private final int maxBleedStack; + + public BleedStacksCache() { + super("bleed_stacks"); + this.bleedStack = 1; + this.maxBleedStack = 5; + this.updateLastBleedStackTime(); + } + + public void updateLastBleedStackTime() { + this.lastBleedStackTime = System.currentTimeMillis(); + } + + public void incrementBleedStack() { + this.bleedStack++; + } + + public void resetBleedStack() { + this.bleedStack = 0; + } + + public int getBleedStack() { + return Math.min(this.maxBleedStack, bleedStack); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DiminishCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DiminishCache.java new file mode 100644 index 0000000..e78e4ec --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DiminishCache.java @@ -0,0 +1,16 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; +import lombok.Setter; + +public class DiminishCache extends Cache { + + @Getter @Setter + private double lastDamage; + + public DiminishCache() { + super("diminish_last_damage"); + this.lastDamage = -1; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DivineCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DivineCache.java new file mode 100644 index 0000000..c078984 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DivineCache.java @@ -0,0 +1,20 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; + +public class DivineCache extends Cache { + + private long lastProcTime; + + public DivineCache() { + super("divine_proc_time"); + } + + public boolean isDivineActive() { + return lastProcTime + 3000L > System.currentTimeMillis(); + } + + public void updateLastProcTime() { + this.lastProcTime = System.currentTimeMillis(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DominateCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DominateCache.java new file mode 100644 index 0000000..1dd71e0 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/DominateCache.java @@ -0,0 +1,45 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; + +@Getter +public class DominateCache extends Cache { + + private int level; + private int duration; + private long lastProcTime; + private int damageReduction; + + public DominateCache() { + super("dominate_proc_time"); + this.lastProcTime = -1; + this.duration = 0; + } + + public boolean isDominateActive() { + return lastProcTime + duration * 1000L > System.currentTimeMillis(); + } + + public void procDominate(int level) { + this.updateLastProcTime(); + this.updateLevel(level); + } + + private void updateLastProcTime() { + this.lastProcTime = System.currentTimeMillis(); + } + + private void updateLevel(int level) { + this.level = level; + this.updateDuration(); + this.updateDamageReduction(); + } + private void updateDamageReduction() { + this.damageReduction = this.level * 5; + } + + private void updateDuration() { + this.duration = this.level * 2; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/NaturesWrathCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/NaturesWrathCache.java new file mode 100644 index 0000000..35fffb2 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/NaturesWrathCache.java @@ -0,0 +1,60 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class NaturesWrathCache extends Cache { + + @Getter @Setter + private boolean isAffected; + + public NaturesWrathCache() { + super("natures-wrath"); + this.isAffected = false; + } + + + public void applyNaturesWrathEffect(Player player, int level) { + player.setWalkSpeed(0.0f); + player.removePotionEffect(PotionEffectType.JUMP); + player.removePotionEffect(PotionEffectType.SLOW); + + PotionEffectUtils.addPotionEffect(player, PotionEffectType.JUMP, 129, "NatureWrathJump", (7 + level) * 20); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SLOW, 129, "NatureWrathSlowness", (7 + level) * 20); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.WEAKNESS, 3, "NatureWrathWeakness", (7 + level) * 20); + + + player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 2.0f, 2.0f); + this.setAffected(true); + } + + public void removeNaturesWrathEffect(Player player) { + player.setWalkSpeed(0.2f); + PotionEffectUtils.removePotionEffect(player, "NatureWrathJump"); + PotionEffectUtils.removePotionEffect(player, "NatureWrathSlowness"); + PotionEffectUtils.removePotionEffect(player, "NatureWrathWeakness"); + + Enchantment springs = EnchantRegister.getInstance().getEnchantmentFromID("springs"); + if (CrankedEnchantsAPI.hasEnchantment(player, springs)) { + int springsLevel = CrankedEnchantsAPI.getEnchantmentLevel(player, springs); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.JUMP, springsLevel, "NatureWrathJump"); + } + + Enchantment antigravity = EnchantRegister.getInstance().getEnchantmentFromID("antigravity"); + if (CrankedEnchantsAPI.hasEnchantment(player, antigravity)) { + int antigravityLevel = CrankedEnchantsAPI.getEnchantmentLevel(player, antigravity); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.JUMP, antigravityLevel + 1, "NatureWrathJump"); + + } + this.setAffected(false); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/RageStacksCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/RageStacksCache.java new file mode 100644 index 0000000..2909231 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/RageStacksCache.java @@ -0,0 +1,49 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; +import org.bukkit.entity.Player; + +import java.util.UUID; + +public class RageStacksCache extends Cache { + + @Getter + private long lastRageStackTime; + private int rageStack; + private final int maxRageStack; + private UUID victim; + + public RageStacksCache() { + super("rage_stacks"); + this.rageStack = 1; + this.maxRageStack = 10; + this.updateLastRageStackTime(); + this.victim = null; + } + + public void updateVictim(Player victim) { + this.victim = victim.getUniqueId(); + } + + public boolean isSameVictim(Player victim) { + if (this.victim == null) return false; + return victim.getUniqueId().equals(this.victim); + } + + public void updateLastRageStackTime() { + this.lastRageStackTime = System.currentTimeMillis(); + } + + public void incrementRageStack() { + this.rageStack++; + } + + public void resetRageStack() { + this.rageStack = 1; + } + + public int getRageStack() { + return Math.min(this.maxRageStack, rageStack); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/SilenceCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/SilenceCache.java new file mode 100644 index 0000000..b49c726 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/SilenceCache.java @@ -0,0 +1,16 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; +import lombok.Setter; + +public class SilenceCache extends Cache { + + @Getter @Setter + private boolean silenced; + + public SilenceCache() { + super("silence_effect"); + this.silenced = false; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/TeleblockCache.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/TeleblockCache.java new file mode 100644 index 0000000..bd0f307 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/cache/enchantscache/TeleblockCache.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.struct.cache.enchantscache; + +import net.crankedpvp.crankedutils.utils.cache.Cache; +import lombok.Getter; + +@Getter +public class TeleblockCache extends Cache { + + private int level; + private int duration; + private long lastProcTime; + + public TeleblockCache() { + super("teleblock"); + this.lastProcTime = -1; + this.duration = 0; + } + + public boolean isTeleblockActive() { + return lastProcTime + duration > System.currentTimeMillis(); + } + + public void procTeleblock(int level) { + this.updateLastProcTime(); + this.updateLevel(level); + } + + private void updateLastProcTime() { + this.lastProcTime = System.currentTimeMillis(); + } + + private void updateLevel(int level) { + this.level = level; + this.updateDuration(); + } + + private void updateDuration() { + this.duration = this.level * 4; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/ConfigManager.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/ConfigManager.java new file mode 100644 index 0000000..9a29ab6 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/ConfigManager.java @@ -0,0 +1,52 @@ +package net.crankedpvp.crankedenchants.struct.config; + +import net.crankedpvp.crankedutils.utils.config.AbstractConfig; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; + +public class ConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public ConfigManager(JavaPlugin plugin) { + + for (ConfigFile configFile : ConfigFile.values()) { + AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName()); + configs.put(configFile, abstractConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AbstractConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AbstractConfig::reloadConfig); + } + + public AbstractConfig getAbstractConfig(ConfigFile configFile) { + return configs.get(configFile); + } + + public FileConfiguration getConfig(ConfigFile configFile) { + return getAbstractConfig(configFile).getConfig(); + } + + @Getter + @RequiredArgsConstructor + public enum ConfigFile { + + SETTINGS("settings.yml"), + ; + + private final String fileName; + + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/EnchantConfig.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/EnchantConfig.java new file mode 100644 index 0000000..99506c3 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/EnchantConfig.java @@ -0,0 +1,125 @@ +package net.crankedpvp.crankedenchants.struct.config; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.annotations.ConfigValue; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.Reloadable; +import net.crankedpvp.crankedutils.utils.CC; +import lombok.AccessLevel; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; + +@Getter +public class EnchantConfig { + + @Getter(value = AccessLevel.PRIVATE) + private final CrankedEnchants plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + private final Enchantment enchantment; + + public EnchantConfig(CrankedEnchants plugin, String path, Enchantment enchantment) { + this.plugin = plugin; + this.path = path; + this.enchantment = enchantment; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public void setupConfigFile() { + this.createDefaultFile(); + this.config = YamlConfiguration.loadConfiguration(configFile); + + this.loadVariables(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path); + e.printStackTrace(); + } + return false; + } + + public void createDefaultFile() { + if (!configFile.exists()) { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path); + e.printStackTrace(); + } + } + } + + public void reloadConfig() { + config = YamlConfiguration.loadConfiguration(configFile); + this.loadVariables(); + } + + public void loadConfigFromDisk() { + try { + config.load(configFile); + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path); + e.printStackTrace(); + } + } + + public void loadVariables() { + boolean needSave = false; + for (Field field : this.enchantment.getClass().getDeclaredFields()) { + + try { + field.setAccessible(true); + + if (field.isAnnotationPresent(ConfigValue.class)) { + ConfigValue annotationValue = field.getAnnotation(ConfigValue.class); + + String name = annotationValue.name().equals("") ? field.getName() : annotationValue.name(); + + String path = annotationValue.path().endsWith(".") ? annotationValue.path() : annotationValue.path() + "."; + + if (!this.config.contains(path + name)) { + this.config.set(path + name, field.get(this.enchantment)); + needSave = true; + continue; + } + + Object fieldValue = this.config.get(path + name); + + if (fieldValue instanceof String) fieldValue = CC.translate((String) fieldValue); + + field.set(this.enchantment, fieldValue); + } + } catch (IllegalAccessException | NullPointerException | IllegalArgumentException e) { + Bukkit.getConsoleSender().sendMessage(CC.translate("&c[CrankedEnchants] - Error invalid config value for enchant " + enchantment.getName())); + } + + if (this.enchantment instanceof Reloadable) { + Reloadable reloadableEnchantment = ((Reloadable) this.enchantment); + reloadableEnchantment.reloadValues(); + } + } + if (needSave) { + saveConfig(); + reloadConfig(); + } + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/EnchantConfigManager.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/EnchantConfigManager.java new file mode 100644 index 0000000..519cc8f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/config/EnchantConfigManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedenchants.struct.config; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class EnchantConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public EnchantConfigManager(CrankedEnchants plugin) { + for (Enchantment enchantment : plugin.getEnchantRegister().getEnchantments()) { + EnchantConfig enchantConfig = new EnchantConfig(plugin, "enchants/" + enchantment.getID() + ".yml", enchantment); + configs.put(enchantment, enchantConfig); + } + } + + public void setupFiles() { + configs.values().forEach(EnchantConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(EnchantConfig::reloadConfig); + } + + public EnchantConfig getAbstractConfig(Enchantment enchantment) { + return configs.get(enchantment); + } + + public FileConfiguration getConfig(Enchantment enchantment) { + return getAbstractConfig(enchantment).getConfig(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/EntityTypes.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/EntityTypes.java new file mode 100644 index 0000000..83175ff --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/EntityTypes.java @@ -0,0 +1,37 @@ +package net.crankedpvp.crankedenchants.struct.custommobs; + +import net.minecraft.server.v1_8_R3.Entity; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; + +import java.util.Map; + +import static net.crankedpvp.crankedutils.utils.NmsUtils.getPrivateField; + +public enum EntityTypes { + + GUARDIANS_GOLEM("Golem", 99, GuardiansIronGolem.class), + //UNDEAD_RUSE_ZOMBIE("Zombie", 54, UndeadRuseZombie.class), + ; + + EntityTypes(String name, int id, Class custom) + { + addToMaps(custom, name, id); + } + + public static org.bukkit.entity.Entity spawnEntity(Entity entity, Location loc) { + entity.setLocation(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch()); + ((CraftWorld)loc.getWorld()).getHandle().addEntity(entity); + return entity.getBukkitEntity(); + } + + private static void addToMaps(Class clazz, String name, int id) { + //getPrivateField is the method from above. + //Remove the lines with // in front of them if you want to override default entities (You'd have to remove the default entity from the map first though). + ((Map)getPrivateField("c", net.minecraft.server.v1_8_R3.EntityTypes.class, null)).put(name, clazz); + ((Map)getPrivateField("d", net.minecraft.server.v1_8_R3.EntityTypes.class, null)).put(clazz, name); + //((Map)getPrivateField("e", net.minecraft.server.v1_7_R4.EntityTypes.class, null)).put(Integer.valueOf(id), clazz); + ((Map)getPrivateField("f", net.minecraft.server.v1_8_R3.EntityTypes.class, null)).put(clazz, id); + //((Map)getPrivateField("g", net.minecraft.server.v1_7_R4.EntityTypes.class, null)).put(name, Integer.valueOf(id)); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/GuardiansIronGolem.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/GuardiansIronGolem.java new file mode 100644 index 0000000..62599de --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/GuardiansIronGolem.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedenchants.struct.custommobs; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedutils.utils.NmsUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.minecraft.server.v1_8_R3.*; +import org.bukkit.World; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.IronGolem; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.metadata.FixedMetadataValue; + +import java.util.List; + +public class GuardiansIronGolem extends EntityIronGolem { + + public GuardiansIronGolem(World world, Player golemOwner, Player target) { + super(((CraftWorld) world).getHandle()); + + List goalB = (List) NmsUtils.getPrivateField("b", PathfinderGoalSelector.class, goalSelector); + goalB.clear(); + List goalC = (List) NmsUtils.getPrivateField("c", PathfinderGoalSelector.class, goalSelector); + goalC.clear(); + List targetB = (List) NmsUtils.getPrivateField("b", PathfinderGoalSelector.class, targetSelector); + targetB.clear(); + List targetC = (List) NmsUtils.getPrivateField("c", PathfinderGoalSelector.class, targetSelector); + targetC.clear(); + + EntityPlayer entityPlayer = ((CraftPlayer) target).getHandle(); + + this.setGoalTarget(entityPlayer, EntityTargetEvent.TargetReason.CUSTOM, true); + + this.goalSelector.a(1, new PathfinderGoalMeleeAttack(this, 1.0D, true)); + this.goalSelector.a(2, new PathfinderGoalMoveTowardsTarget(this, 0.9D, 32.0F)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + + this.fireProof = true; + this.expToDrop = 0; + this.setCustomName(CC.translate("&3" + golemOwner.getName() + "'s Guardian")); + this.setCustomNameVisible(true); + + IronGolem ironGolem = (IronGolem) this.getBukkitEntity(); + ironGolem.setMaxHealth(800); + ironGolem.setHealth(800); + ironGolem.setMetadata("guardian-target", new FixedMetadataValue(CrankedEnchants.getInstance(), String.valueOf(target.getUniqueId()))); + ironGolem.setMetadata("guardian-owner", new FixedMetadataValue(CrankedEnchants.getInstance(), String.valueOf(golemOwner.getUniqueId()))); + } + + @Override + protected void dropDeathLoot(boolean flag, int i) { + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/UndeadRuseZombie.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/UndeadRuseZombie.java new file mode 100644 index 0000000..83164cb --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/custommobs/UndeadRuseZombie.java @@ -0,0 +1,58 @@ +package net.crankedpvp.crankedenchants.struct.custommobs; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedutils.utils.NmsUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.minecraft.server.v1_8_R3.*; +import org.bukkit.World; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.bukkit.entity.Zombie; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.metadata.FixedMetadataValue; + +import java.util.List; + +public class UndeadRuseZombie extends EntityZombie { + + public UndeadRuseZombie(World world, Player zombieOwner, Player target) { + super(((CraftWorld) world).getHandle()); + +/* List goalB = (List) NmsUtils.getPrivateField("b", PathfinderGoalSelector.class, goalSelector); + goalB.clear(); + List goalC = (List) NmsUtils.getPrivateField("c", PathfinderGoalSelector.class, goalSelector); + goalC.clear(); + List targetB = (List) NmsUtils.getPrivateField("b", PathfinderGoalSelector.class, targetSelector); + targetB.clear(); + List targetC = (List) NmsUtils.getPrivateField("c", PathfinderGoalSelector.class, targetSelector); + targetC.clear(); + + EntityPlayer entityPlayer = ((CraftPlayer) target).getHandle(); + + this.setGoalTarget(entityPlayer, EntityTargetEvent.TargetReason.CUSTOM, true); + + this.goalSelector.a(1, new PathfinderGoalMeleeAttack(this, 1.0D, true)); + this.goalSelector.a(2, new PathfinderGoalMoveTowardsTarget(this, 0.9D, 32.0F)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + + this.fireProof = true; + this.expToDrop = 0; + + this.setCustomName(CC.translate("&b" + zombieOwner.getName() + "'s Zombie")); + this.setCustomNameVisible(true); + + Zombie zombie = (Zombie) this.getBukkitEntity(); + zombie.setMaxHealth(800); + zombie.setHealth(800); + zombie.setMetadata("zombie-target", new FixedMetadataValue(CrankedEnchants.getInstance(), String.valueOf(target.getUniqueId()))); + zombie.setMetadata("zombie-owner", new FixedMetadataValue(CrankedEnchants.getInstance(), String.valueOf(zombieOwner.getUniqueId()))); + */ + + } + + @Override + protected void dropDeathLoot(boolean flag, int i) { + + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorEquipEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorEquipEventEnchant.java new file mode 100644 index 0000000..458d63c --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorEquipEventEnchant.java @@ -0,0 +1,15 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.entity.Player; + +public abstract class ArmorEquipEventEnchant extends Enchantment { + + public ArmorEquipEventEnchant(String name, EnchantTier tier, boolean stackable, int max, GearType type, String... description) { + super(name, tier, stackable, max, type, description); + } + + public abstract void runArmorEquipEvent(Player player, int level); + public abstract void runArmorUnEquipEvent(Player player, int level); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorIncomingPVPDamageEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorIncomingPVPDamageEventEnchant.java new file mode 100644 index 0000000..c03797e --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorIncomingPVPDamageEventEnchant.java @@ -0,0 +1,54 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public abstract class ArmorIncomingPVPDamageEventEnchant extends Enchantment { + + public ArmorIncomingPVPDamageEventEnchant(String name, EnchantTier tier, boolean stackable, int max, GearType type, String... description) { + super(name, tier, stackable, max, type, description); + } + + @EventHandler(priority = EventPriority.LOW) + public void incomingDamage(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getDamage() == 0) return; + + if (!(event.getEntity() instanceof Player)) return; + if (!(event.getDamager() instanceof LivingEntity)) return; + + Player victim = (Player) event.getEntity(); + LivingEntity attacker = (LivingEntity) event.getDamager(); + + if (attacker instanceof Player) { + if (!PVPUtils.canPVP(victim, attacker)) return; + } + + if (!CrankedEnchantsAPI.hasEnchantment(victim, this)) return; + + EnchantInfo info = CrankedEnchantsAPI.getEnchantmentInfo(victim, this); + + EnchantProcEvent procEvent = new EnchantProcOnEntityEvent(attacker, victim, this, info.getLevel()); + Bukkit.getPluginManager().callEvent(procEvent); + + if(procEvent.isCancelled()) return; + + if (this.getTier() == EnchantTier.SOUL && !CrankedEnchants.getInstance().getSoulManager().isInSoulMode(victim)) return; + + this.runIncomingDamageEvent(event, victim, attacker, info); + } + + public abstract void runIncomingDamageEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, EnchantInfo enchantInfo); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorOutgoingPVPDamageEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorOutgoingPVPDamageEventEnchant.java new file mode 100644 index 0000000..be42528 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorOutgoingPVPDamageEventEnchant.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public abstract class ArmorOutgoingPVPDamageEventEnchant extends Enchantment { + + public ArmorOutgoingPVPDamageEventEnchant(String name, EnchantTier tier, boolean stackable, int max, GearType type, String... description) { + super(name, tier, stackable, max, type, description); + } + + @EventHandler + public void outgoingDamage(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getDamage() <= 0) return; + + if (!(event.getDamager() instanceof Player)) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + + LivingEntity victim = (LivingEntity) event.getEntity(); + Player attacker = (Player) event.getDamager(); + + if (victim instanceof Player) { + if (!PVPUtils.canPVP(attacker, victim)) return; + } + + if (!CrankedEnchantsAPI.hasEnchantment(attacker, this)) return; + + EnchantInfo info = CrankedEnchantsAPI.getEnchantmentInfo(attacker, this); + + EnchantProcEvent procEvent = new EnchantProcOnEntityEvent(attacker, victim, this, info.getLevel()); + Bukkit.getPluginManager().callEvent(procEvent); + + if(procEvent.isCancelled()) return; + + this.runOutgoingDamageEvent(event, attacker, victim, info); + } + + public abstract void runOutgoingDamageEvent(EntityDamageByEntityEvent event, Player attacker, LivingEntity victim, EnchantInfo enchantInfo); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorPlayerDamageEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorPlayerDamageEventEnchant.java new file mode 100644 index 0000000..a5479f0 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorPlayerDamageEventEnchant.java @@ -0,0 +1,42 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnDamageEvent; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageEvent; + +public abstract class ArmorPlayerDamageEventEnchant extends Enchantment { + + public ArmorPlayerDamageEventEnchant(String name, EnchantTier tier, boolean stackable, int max, GearType type, String... description) { + super(name, tier, stackable, max, type, description); + } + + @EventHandler + public void onDamage(EntityDamageEvent event) { + if (event.isCancelled()) return; + if (event.getDamage() <= 0) return; + + if (!(event.getEntity() instanceof Player)) return; + + Player player = (Player) event.getEntity(); + + if (!CrankedEnchantsAPI.hasEnchantment(player, this)) return; + + EnchantInfo info = CrankedEnchantsAPI.getEnchantmentInfo(player, this); + + EnchantProcEvent procEvent = new EnchantProcOnDamageEvent(player, event.getCause(), this, info.getLevel()); + Bukkit.getPluginManager().callEvent(procEvent); + + if(procEvent.isCancelled()) return; + + this.runOnDamage(event, player, info); + } + + public abstract void runOnDamage(EntityDamageEvent event, Player player, EnchantInfo enchantInfo); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorPlayerDeathEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorPlayerDeathEventEnchant.java new file mode 100644 index 0000000..42a1cb3 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ArmorPlayerDeathEventEnchant.java @@ -0,0 +1,40 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityDeathEvent; +import net.crankedpvp.crankedenchants.struct.cache.EnchantInfo; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.PlayerDeathEvent; + +public abstract class ArmorPlayerDeathEventEnchant extends Enchantment { + + public ArmorPlayerDeathEventEnchant(String name, EnchantTier tier, boolean stackable, int max, GearType type, String... description) { + super(name, tier, stackable, max, type, description); + } + + @EventHandler + public void onDeath(PlayerDeathEvent event) { + Player victim = event.getEntity(); + + if (victim.getKiller() == null) return; + Player killer = victim.getKiller(); + + if (!CrankedEnchantsAPI.hasEnchantment(victim, this)) return; + + EnchantInfo info = CrankedEnchantsAPI.getEnchantmentInfo(victim, this); + + EnchantProcEvent procEvent = new EnchantProcOnEntityDeathEvent(killer, victim, this, info.getLevel()); + Bukkit.getPluginManager().callEvent(procEvent); + + if(procEvent.isCancelled()) return; + + this.runEntityDeathEvent(event, killer, victim, info); + } + + public abstract void runEntityDeathEvent(PlayerDeathEvent event, Player killer, Player victim, EnchantInfo enchantInfo); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/BlockBreakEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/BlockBreakEventEnchant.java new file mode 100644 index 0000000..1a058b5 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/BlockBreakEventEnchant.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnBlockEvent; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.inventory.ItemStack; + +public abstract class BlockBreakEventEnchant extends Enchantment { + + public BlockBreakEventEnchant(String name, EnchantTier tier, int max, GearType type, String... description) { + super(name, tier, false, max, type, description); + } + + @EventHandler + public void blockBreakEvent(BlockBreakEvent event) { + if (event.isCancelled()) return; + + ItemStack itemStack = event.getPlayer().getItemInHand(); + + if (itemStack == null) return; + if (!this.getType().getItems().contains(itemStack.getType())) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + EnchantProcEvent procEvent = new EnchantProcOnBlockEvent(event.getBlock(), this,enchantedItemBuilder.getEnchantmentLevel(this)); + Bukkit.getPluginManager().callEvent(procEvent); + + if(procEvent.isCancelled()) return; + this.runBlockBreakEvent(event, enchantedItemBuilder); + } + + public abstract void runBlockBreakEvent(BlockBreakEvent event, EnchantedItemBuilder enchantedItemBuilder); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/BowEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/BowEventEnchant.java new file mode 100644 index 0000000..f72097a --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/BowEventEnchant.java @@ -0,0 +1,91 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedenchants.struct.cache.cooldowns.WeakShotCooldown; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityShootBowEvent; +import org.bukkit.inventory.ItemStack; + +public abstract class BowEventEnchant extends Enchantment { + + protected boolean hasEnoughPower = false; + + public BowEventEnchant(String name, EnchantTier tier, int max, GearType type, String... description) { + super(name, tier, false, max, type, description); + } + + @EventHandler + public void damageEvent(EntityDamageByEntityEvent event) { + if (!(event.getEntity() instanceof Player) || !(event.getDamager() instanceof Arrow)) return; + + Arrow arrow = (Arrow) event.getDamager(); + + if (!(arrow.getShooter() instanceof Player)) return; + if (event.getDamage() <= 0) return; + + Player victim = (Player) event.getEntity(); + Player attacker = (Player) arrow.getShooter(); + + if (!PVPUtils.canPVP(victim, attacker)) return; + + ItemStack itemStack = attacker.getItemInHand(); + + if (itemStack == null) return; + if (!this.getType().getItems().contains(itemStack.getType())) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + + if (!hasEnoughPower) return; + + EnchantProcEvent procEvent = new EnchantProcOnEntityEvent(attacker, victim, this, enchantedItemBuilder.getEnchantmentLevel(this)); + Bukkit.getPluginManager().callEvent(procEvent); + + if (procEvent.isCancelled()) return; + + this.runEntityDamageByEntityEvent(event, victim, attacker, arrow, enchantedItemBuilder); + } + + public abstract void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, Player victim, Player attacker, Arrow arrow, EnchantedItemBuilder enchantedItemBuilder); + + @EventHandler(priority = EventPriority.LOW) + public void onBowShoot(EntityShootBowEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player shooter = (Player) ((Arrow) event.getProjectile()).getShooter(); + ItemStack itemStack = shooter.getItemInHand(); + + if (!ItemUtils.isEnchantable(itemStack)) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantments()) return; + + if (event.getForce() >= 0.75D) { + this.hasEnoughPower = true; + return; + } + + + + this.hasEnoughPower = false; + if (!CooldownUtils.isCooldownActive(shooter, NbtTags.WEAK_SHOT_CACHE_ID)) { + CooldownUtils.registerCooldown(shooter, new WeakShotCooldown()); + Language.WEAK_SHOT.send(shooter); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/Enchantment.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/Enchantment.java new file mode 100644 index 0000000..529b8ec --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/Enchantment.java @@ -0,0 +1,98 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import lombok.Getter; +import net.crankedpvp.crankedenchants.struct.cache.cooldowns.EnchantCooldownCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import net.crankedpvp.crankedutils.utils.cache.CachedPlayer; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.UnaryOperator; + +@Getter +public abstract class Enchantment implements Listener { + + private final String name; + private final List description; + private final EnchantTier tier; + private final boolean stackable; + private final int max; + private final GearType type; + private final DamageHandler damageHandler; + + public Enchantment(String name, EnchantTier tier, boolean stackable, int max, GearType type, String... description) { + this.name = name; + this.description = Arrays.asList(description); + this.tier = tier; + this.stackable = stackable; + this.max = max; + this.type = type; + this.damageHandler = CrankedUtils.instance.getDamageHandler(); + } + + public String getID() { + return this.getName().replace(" ", "").toLowerCase(Locale.ROOT); + } + + public void registerCooldown(Player player, int cooldown) { + CachedPlayer cacheManager = CacheManager.getInstance().getCachedPlayer(player); + + if (this instanceof HeroicEnchantment) { + cacheManager.registerCache(new EnchantCooldownCache(((HeroicEnchantment) this).getBaseEnchantment(), cooldown)); + } else { + cacheManager.registerCache(new EnchantCooldownCache(this, cooldown)); + } + } + + public boolean isOnCooldown(Player player) { + CachedPlayer cacheManager = CacheManager.getInstance().getCachedPlayer(player); + + if (this instanceof HeroicEnchantment) { + HeroicEnchantment heroicEnchantment = ((HeroicEnchantment) this); + if (!cacheManager.hasCache("enchant_cooldown_" + heroicEnchantment.getBaseEnchantment())) return false; + return ((EnchantCooldownCache) cacheManager.getCache("enchant_cooldown_" + heroicEnchantment.getBaseEnchantment())).isActive(); + } + + if (!cacheManager.hasCache("enchant_cooldown_" + this.getID())) return false; + return ((EnchantCooldownCache) cacheManager.getCache("enchant_cooldown_" + this.getID())).isActive(); + } + + public int getEnchantTierWeight() { + return this.getTier().getWeight(); + } + + protected void sendMessage(LivingEntity player, String message, UnaryOperator function) { + player.sendMessage(CC.translate(function.apply(message))); + } + + protected void sendMessage(LivingEntity player, String message) { + player.sendMessage(CC.translate(message)); + } + + protected void sendMessage(LivingEntity player, List message) { + message.stream() + .map(CC::translate) + .forEach(player::sendMessage); + } + protected void sendMessage(LivingEntity player, List message, UnaryOperator function) { + message.stream() + .map(function) + .map(CC::translate) + .forEach(player::sendMessage); + } + + public int getRandomLevel() { + return ThreadLocalRandom.current().nextInt(1, this.max + 1); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ItemInteractEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ItemInteractEventEnchant.java new file mode 100644 index 0000000..bb0feab --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/ItemInteractEventEnchant.java @@ -0,0 +1,43 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public abstract class ItemInteractEventEnchant extends Enchantment { + + public ItemInteractEventEnchant(String name, EnchantTier tier, boolean stackable, int max, GearType type, String... description) { + super(name, tier, stackable, max, type, description); + } + + @EventHandler + public void interactEvent(PlayerInteractEvent event) { + if (event.isCancelled()) return; + + ItemStack itemStack = event.getItem(); + + if (itemStack == null) return; + if (!this.getType().getItems().contains(itemStack.getType())) return; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + + Player player = event.getPlayer(); + Action action = event.getAction(); + + if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) + this.runInteractRightClickEvent(event, player, itemStack, enchantedItemBuilder); + + if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) + this.runInteractLeftClickEvent(event, player, itemStack, enchantedItemBuilder); + } + + public abstract void runInteractRightClickEvent(PlayerInteractEvent event, Player player, ItemStack itemStack, EnchantedItemBuilder enchantedItemBuilder); + public abstract void runInteractLeftClickEvent(PlayerInteractEvent event, Player player, ItemStack itemStack, EnchantedItemBuilder enchantedItemBuilder); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponBossDeathEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponBossDeathEventEnchant.java new file mode 100644 index 0000000..8828c4b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponBossDeathEventEnchant.java @@ -0,0 +1,73 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.bosses.events.BossDeathEvent; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityDeathEvent; +import net.crankedpvp.crankedenchants.struct.cache.WeaponEnchantCache; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; + +import static net.crankedpvp.crankedenchants.CrankedEnchantsAPI.getWeaponEnchantCache; + +public abstract class WeaponBossDeathEventEnchant extends Enchantment { + + public WeaponBossDeathEventEnchant(String name, EnchantTier tier, int max, GearType type, String... description) { + super(name, tier, false, max, type, description); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onDeath(BossDeathEvent event) { + LivingEntity victim = event.getEntity(); + if (victim.getKiller() == null) return; + Player killer = victim.getKiller(); + if (killer.getItemInHand() == null) return; + ItemStack itemStack = killer.getItemInHand(); + + if (!this.getType().getItems().contains(itemStack.getType())) return; + + int level; + + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(killer); + + if (enchantmentCache.hasEnchants()) { + + if (enchantmentCache.getSwordSlot() != killer.getInventory().getHeldItemSlot()) { + CrankedEnchantsAPI.cacheWeaponEnchants(killer, new EnchantedItemBuilder(itemStack)); + } + + if (enchantmentCache.shouldRefreshCash()) { + CrankedEnchantsAPI.cacheWeaponEnchants(killer, new EnchantedItemBuilder(itemStack)); + } + + if (!enchantmentCache.hasEnchantment(this)) { + return; + } + + level = enchantmentCache.getEnchantLevel(this); + } else { + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + level = enchantedItemBuilder.getEnchantmentLevel(this); + + CrankedEnchantsAPI.cacheWeaponEnchants(killer, enchantedItemBuilder); + } + + EnchantProcEvent procEvent = new EnchantProcOnEntityDeathEvent(killer, victim, this, level); + Bukkit.getPluginManager().callEvent(procEvent); + + if (procEvent.isCancelled()) return; + this.runEntityDeathEvent(event, killer, event.getBoss(), victim, level); + } + + public abstract void runEntityDeathEvent(BossDeathEvent event, Player killer, Boss boss, LivingEntity victim, int level); +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponDamageEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponDamageEventEnchant.java new file mode 100644 index 0000000..bf59ac0 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponDamageEventEnchant.java @@ -0,0 +1,96 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.struct.cache.WeaponEnchantCache; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import static net.crankedpvp.crankedenchants.CrankedEnchantsAPI.getWeaponEnchantCache; + +public abstract class WeaponDamageEventEnchant extends Enchantment { + + public WeaponDamageEventEnchant(String name, EnchantTier tier, int max, GearType type, String... description) { + super(name, tier, false, max, type, description); + } + + @EventHandler(priority = EventPriority.HIGH) + public void damageEvent(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getDamage() <= 0) return; + if (!(event.getEntity() instanceof LivingEntity) || !(event.getDamager() instanceof Player)) return; + + Player attacker = (Player) event.getDamager(); + ItemStack itemStack = attacker.getItemInHand(); + + if (!ItemUtils.isWeapon(itemStack)) return; + + LivingEntity victim = (LivingEntity) event.getEntity(); + + if (victim instanceof Player) { + if (!PVPUtils.canPVP(attacker, victim)) return; + } + + int level; + + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(attacker); + + if (enchantmentCache.hasEnchants()) { + + if (enchantmentCache.getSwordSlot() != attacker.getInventory().getHeldItemSlot()) { + CrankedEnchantsAPI.cacheWeaponEnchants(attacker, new EnchantedItemBuilder(itemStack)); + } + + if (enchantmentCache.shouldRefreshCash()) { + CrankedEnchantsAPI.cacheWeaponEnchants(attacker, new EnchantedItemBuilder(itemStack)); + } + + if (!enchantmentCache.hasEnchantment(this)) { + return; + } + + level = enchantmentCache.getEnchantLevel(this); + } else { +/* + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + level = enchantedItemBuilder.getEnchantmentLevel(this); + + CrankedEnchantsAPI.cacheWeaponEnchants(attacker, enchantedItemBuilder); +*/ + + + //this is going to be the more optimised version, ill uncomment it once im sure it works + + if (!CrankedEnchantsAPI.itemHasEnchantment(itemStack, this)) return; + level = CrankedEnchantsAPI.getEnchantmentLevelFromItem(itemStack, this); + + CrankedEnchantsAPI.cacheWeaponEnchants(attacker, itemStack); + + } + + EnchantProcEvent procEvent = new EnchantProcOnEntityEvent(attacker, victim, this, level); + Bukkit.getPluginManager().callEvent(procEvent); + + if (procEvent.isCancelled()) return; + + if (this.getTier() == EnchantTier.SOUL && !CrankedEnchants.getInstance().getSoulManager().isInSoulMode(attacker)) return; + + this.runEntityDamageByEntityEvent(event, victim, attacker, level); + } + + public abstract void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, LivingEntity victim, Player attacker, int enchantLevel); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponDeathEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponDeathEventEnchant.java new file mode 100644 index 0000000..bd43a11 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponDeathEventEnchant.java @@ -0,0 +1,69 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityDeathEvent; +import net.crankedpvp.crankedenchants.struct.cache.WeaponEnchantCache; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.inventory.ItemStack; + +import static net.crankedpvp.crankedenchants.CrankedEnchantsAPI.getWeaponEnchantCache; + +public abstract class WeaponDeathEventEnchant extends Enchantment { + + public WeaponDeathEventEnchant(String name, EnchantTier tier, int max, GearType type, String... description) { + super(name, tier, false, max, type, description); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onDeath(EntityDeathEvent event) { + LivingEntity victim = event.getEntity(); + if (victim.getKiller() == null) return; + Player killer = victim.getKiller(); + if (killer.getItemInHand() == null) return; + ItemStack itemStack = killer.getItemInHand(); + + if (!this.getType().getItems().contains(itemStack.getType())) return; + + int level; + + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(killer); + + if (enchantmentCache.hasEnchants()) { + + if (enchantmentCache.getSwordSlot() != killer.getInventory().getHeldItemSlot()) { + CrankedEnchantsAPI.cacheWeaponEnchants(killer, new EnchantedItemBuilder(itemStack)); + } + + if (enchantmentCache.shouldRefreshCash()) { + CrankedEnchantsAPI.cacheWeaponEnchants(killer, new EnchantedItemBuilder(itemStack)); + } + + if (!enchantmentCache.hasEnchantment(this)) { + return; + } + + level = enchantmentCache.getEnchantLevel(this); + } else { + if (!CrankedEnchantsAPI.itemHasEnchantment(itemStack, this)) return; + level = CrankedEnchantsAPI.getEnchantmentLevelFromItem(itemStack, this); + + CrankedEnchantsAPI.cacheWeaponEnchants(killer, itemStack); + } + EnchantProcEvent procEvent = new EnchantProcOnEntityDeathEvent(killer, victim, this, level); + Bukkit.getPluginManager().callEvent(procEvent); + + if(procEvent.isCancelled()) return; + this.runEntityDeathEvent(event, killer, victim, level); + } + + public abstract void runEntityDeathEvent(EntityDeathEvent event, Player killer, LivingEntity victim, int level); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponIncomingDamageEventEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponIncomingDamageEventEnchant.java new file mode 100644 index 0000000..ab461c8 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/WeaponIncomingDamageEventEnchant.java @@ -0,0 +1,85 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.events.EnchantProcEvent; +import net.crankedpvp.crankedenchants.events.EnchantProcOnEntityEvent; +import net.crankedpvp.crankedenchants.struct.cache.WeaponEnchantCache; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import static net.crankedpvp.crankedenchants.CrankedEnchantsAPI.getWeaponEnchantCache; + +public abstract class WeaponIncomingDamageEventEnchant extends Enchantment { + + public WeaponIncomingDamageEventEnchant(String name, EnchantTier tier, int max, GearType type, String... description) { + super(name, tier, false, max, type, description); + } + + @EventHandler(priority = EventPriority.HIGH) + public void damageEvent(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getDamage() <= 0) return; + if (!(event.getEntity() instanceof Player) || !(event.getDamager() instanceof LivingEntity)) return; + + Player victim = (Player) event.getEntity(); + LivingEntity attacker = (LivingEntity) event.getDamager(); + + if (attacker instanceof Player) { + if (!PVPUtils.canPVP(victim, attacker)) return; + } + + ItemStack itemStack = victim.getItemInHand(); + + if (itemStack == null) return; + if (!this.getType().getItems().contains(itemStack.getType())) return; + + int level; + + WeaponEnchantCache enchantmentCache = getWeaponEnchantCache(victim); + + if (enchantmentCache.hasEnchants()) { + + if (enchantmentCache.getSwordSlot() != victim.getInventory().getHeldItemSlot()) { + CrankedEnchantsAPI.cacheWeaponEnchants(victim, new EnchantedItemBuilder(itemStack)); + } + + if (enchantmentCache.shouldRefreshCash()) { + CrankedEnchantsAPI.cacheWeaponEnchants(victim, new EnchantedItemBuilder(itemStack)); + } + + if (!enchantmentCache.hasEnchantment(this)) { + return; + } + + level = enchantmentCache.getEnchantLevel(this); + } else { + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(itemStack); + + if (!enchantedItemBuilder.hasEnchantment(this)) return; + level = enchantedItemBuilder.getEnchantmentLevel(this); + + CrankedEnchantsAPI.cacheWeaponEnchants(victim, enchantedItemBuilder); + } + + EnchantProcEvent procEvent = new EnchantProcOnEntityEvent(attacker, victim, this, level); + Bukkit.getPluginManager().callEvent(procEvent); + + if(procEvent.isCancelled()) return; + + if (this.getTier() == EnchantTier.SOUL && !CrankedEnchants.getInstance().getSoulManager().isInSoulMode(victim)) return; + + this.runEntityDamageByEntityEvent(event, victim, attacker, level); + } + + public abstract void runEntityDamageByEntityEvent(EntityDamageByEntityEvent event, Player victim, LivingEntity attacker, int level); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/BlindingEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/BlindingEnchant.java new file mode 100644 index 0000000..d07100f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/BlindingEnchant.java @@ -0,0 +1,4 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces; + +public interface BlindingEnchant { +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/DrainSoulEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/DrainSoulEnchant.java new file mode 100644 index 0000000..4dc4f93 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/DrainSoulEnchant.java @@ -0,0 +1,4 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces; + +public interface DrainSoulEnchant extends SoulEnchant { +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/HeroicEnchantment.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/HeroicEnchantment.java new file mode 100644 index 0000000..5d1c0ad --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/HeroicEnchantment.java @@ -0,0 +1,6 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces; + +public interface HeroicEnchantment { + + String getBaseEnchantment(); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/Reloadable.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/Reloadable.java new file mode 100644 index 0000000..b33ed9e --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/Reloadable.java @@ -0,0 +1,6 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces; + +public interface Reloadable { + + void reloadValues(); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/Silenceable.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/Silenceable.java new file mode 100644 index 0000000..dc49bfe --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/Silenceable.java @@ -0,0 +1,4 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces; + +public interface Silenceable { +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/SlownessEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/SlownessEnchant.java new file mode 100644 index 0000000..e9c592b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/SlownessEnchant.java @@ -0,0 +1,6 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces; + +public interface SlownessEnchant { + + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/SoulEnchant.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/SoulEnchant.java new file mode 100644 index 0000000..5f9c257 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enchantstruct/interfaces/SoulEnchant.java @@ -0,0 +1,6 @@ +package net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces; + +public interface SoulEnchant { + + int getSoulCost(); +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enums/EnchantTier.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enums/EnchantTier.java new file mode 100644 index 0000000..1f3e403 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enums/EnchantTier.java @@ -0,0 +1,70 @@ +package net.crankedpvp.crankedenchants.struct.enums; + +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.MiscUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.text.NumberFormat; +import java.util.Locale; + + +@AllArgsConstructor +@Getter +public enum EnchantTier { + + SIMPLE(CC.Gray, (short) 0, 10, 1), + UNIQUE(CC.Green, (short) 5, 9, 2), + ELITE(CC.Aqua, (short) 3, 8, 5), + ULTIMATE(CC.Yellow, (short) 4, 7, 10), + LEGENDARY(CC.Gold, (short) 1, 6, 20), + HEROIC(CC.LightPurple, (short) 2, 5, 25), + SOUL(CC.Red, (short) 14, 4, 30), + CURSED(CC.DarkRed, (short) 14, 3, 35), + UNDERWORLD(CC.DarkAqua, (short) 9, 2, 0), + ; + + private final String color; + private final short guiItemGlassColor; + private final int weight; + private final int soulValue; + + public ItemStack getGuiItem(int cost) { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, this.guiItemGlassColor) + .setName(this.color + CC.Bold + MiscUtils.toNiceString(this.name()) + " Enchantment &7(Right Click)") + .setLore( + "&7Examine to receive a random", + this.color + this.name().toLowerCase(Locale.ROOT) + "&7 enchantment book", + "", + "&7Use " + this.color + "/help enchants " + this.name().toLowerCase(Locale.ROOT) + "&7 to view a list", + "&7of possible enchantments you could unlock!", + "", + "&b&lCOST&f " + NumberFormat.getIntegerInstance().format(cost) + " EXP" + ) + .colorize() + .build(); + } + + public static ItemStack createMysteryBook(EnchantTier tier, int amount) { + ItemStack itemStack = new ItemBuilder(Material.BOOK, amount, (short) 0, + tier.getColor() + tier.getFormatedName() + " Enchantment Book &7(Right Click)", + "&7Examine to recieve a random", + tier.getColor() + tier.name().toLowerCase(Locale.ROOT) + "&r&7 enchantment book.") + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString(NbtTags.DATA_STRING, NbtTags.BOOK_DATA_STRING); + nbtItem.setString(NbtTags.BOOK_TIER_DATA_STRING, tier.getFormatedName().toUpperCase()); + return nbtItem.getItem(); + } + + public String getFormatedName() { + return MiscUtils.toNiceString(this.name()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enums/GearType.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enums/GearType.java new file mode 100644 index 0000000..300ae1e --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/enums/GearType.java @@ -0,0 +1,61 @@ +package net.crankedpvp.crankedenchants.struct.enums; + +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.MiscUtils; +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@Getter +public enum GearType { + HELMET(Material.DIAMOND_HELMET, true, Material.LEATHER_HELMET, Material.IRON_HELMET, Material.CHAINMAIL_HELMET, Material.GOLD_HELMET, Material.DIAMOND_HELMET), + CHESTPLATE(Material.DIAMOND_CHESTPLATE, true, Material.LEATHER_CHESTPLATE, Material.IRON_CHESTPLATE, Material.CHAINMAIL_CHESTPLATE, Material.GOLD_CHESTPLATE, Material.DIAMOND_CHESTPLATE), + LEGGINGS(Material.DIAMOND_LEGGINGS, true, Material.LEATHER_LEGGINGS, Material.IRON_LEGGINGS, Material.CHAINMAIL_LEGGINGS, Material.GOLD_LEGGINGS, Material.DIAMOND_LEGGINGS), + BOOTS(Material.DIAMOND_BOOTS, true, Material.LEATHER_BOOTS, Material.IRON_BOOTS, Material.CHAINMAIL_BOOTS, Material.GOLD_BOOTS, Material.DIAMOND_BOOTS), + SWORD(Material.DIAMOND_SWORD, true, Material.WOOD_SWORD, Material.IRON_SWORD, Material.STONE_SWORD, Material.GOLD_SWORD, Material.DIAMOND_SWORD, Material.DIAMOND_HOE, Material.GOLD_HOE), + BOW(Material.BOW,true, Material.BOW), + PICKAXE(Material.DIAMOND_PICKAXE, true, Material.WOOD_PICKAXE, Material.IRON_PICKAXE, Material.STONE_PICKAXE, Material.GOLD_PICKAXE, Material.DIAMOND_PICKAXE), + SHOVEL(Material.DIAMOND_SPADE, true, Material.WOOD_SPADE, Material.IRON_SPADE, Material.STONE_SPADE, Material.GOLD_SPADE, Material.DIAMOND_SPADE), + AXE(Material.DIAMOND_AXE, true, Material.WOOD_AXE, Material.IRON_AXE, Material.STONE_AXE, Material.GOLD_AXE, Material.DIAMOND_AXE, Material.DIAMOND_HOE, Material.GOLD_HOE), + HOE(Material.DIAMOND_HOE, true, Material.WOOD_HOE, Material.IRON_HOE, Material.STONE_HOE, Material.GOLD_HOE, Material.DIAMOND_HOE), + TOOL(Material.GOLD_PICKAXE, true, GearType.PICKAXE, GearType.SHOVEL, GearType.AXE, GearType.HOE), + PICKAXE_SHOVEL(Material.IRON_PICKAXE, true, GearType.PICKAXE, GearType.SHOVEL), + ARMOR(Material.GOLD_CHESTPLATE, true, GearType.HELMET, GearType.CHESTPLATE, GearType.LEGGINGS, GearType.BOOTS), + BOOTS_AND_HELMET(Material.GOLD_BOOTS, true, GearType.BOOTS, GearType.HELMET), + WEAPON(Material.GOLD_SWORD, true, GearType.SWORD, GearType.AXE), + WEAPONS_AND_TOOLS(Material.GOLD_AXE, true, GearType.WEAPON, GearType.TOOL) + ; + + + + private final List items = new ArrayList<>(); + private final Material display; + private boolean displayInGUI; + + GearType(Material display, boolean displayInGUI, Material... itemsStack) { + items.addAll(Arrays.asList(itemsStack)); + this.display = display; + this.displayInGUI = displayInGUI; + } + + + GearType(Material display, boolean displayInGUI, GearType... gearTypes) { + for (GearType gearType : gearTypes) { + items.addAll(gearType.getItems()); + } + this.display = display; + this.displayInGUI = displayInGUI; + } + + public List getItems() { + return items; + } + + public String getFormatedName() { + return MiscUtils.toNiceString(this.name()); + } + + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/BlackScrollBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/BlackScrollBuilder.java new file mode 100644 index 0000000..950fbf3 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/BlackScrollBuilder.java @@ -0,0 +1,45 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlackScrollBuilder extends CustomItem { + + public BlackScrollBuilder(int percent) { + super(NbtTags.BLACK_SCROLL_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.INK_SACK) + .setName("&f&lBlack Scroll") + .addLore( + "&7Removes a random enchantment", + "&7from an item and converts", + "&7it into a &f" + percent + "%&7 success book.", + "&fPlace scroll onto an item to extract." + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("scroll-percent", percent); + super.nbtItem = nbtItem; + super.applyID(); + } + + public BlackScrollBuilder() { + this(ThreadLocalRandom.current().nextInt(1, 101)); + } + + public BlackScrollBuilder(ItemStack itemStack) { + super(NbtTags.BLACK_SCROLL_DATA_STRING); + this.nbtItem = new NBTItem(itemStack); + } + + public int getPercent() { + return this.nbtItem.getInteger("scroll-percent"); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/BookBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/BookBuilder.java new file mode 100644 index 0000000..0993ef7 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/BookBuilder.java @@ -0,0 +1,152 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +public class BookBuilder extends CustomItem { + + private int success; + private int destroy; + + public BookBuilder(Enchantment enchantment, int level) { + super(NbtTags.ENCHANT_BOOK_DATA_STRING); + this.success = generateChanceSuccess(enchantment); + this.destroy = generateChanceDestroy(enchantment); + + List description = enchantment.getDescription().stream().map(str -> "&f" + str).collect(Collectors.toList()); + + ItemStack itemStack = new ItemBuilder(Material.BOOK, + enchantment.getTier().getColor() + "&l&n" + enchantment.getName() + " " + RomanNumeral.convertToRoman(level), + "&a" + success + "% Success Rate", + "&c" + destroy + "% Destroy Rate", + "&6Max Level: &f" + enchantment.getMax(), + "&7") + .addLore(description) + .addLore("&7", + "&fStackable: " + (enchantment.isStackable() ? "&aYes" : "&cNo"), + "&7" + enchantment.getType().getFormatedName() + " Enchantment", + "&7Drag n' Drop onto an item to enchant it.").colorize().build(); + + NBTItem nbtItem = new NBTItem(itemStack); + //nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setString("enchantment", enchantment.getID()); + nbtItem.setInteger("level", level); + //nbtItem.setInteger("dust-value", generateDustValue()); + nbtItem.setInteger(NbtTags.SUCCESS_RATE_STRING, success); + nbtItem.setInteger(NbtTags.DESTROY_RATE_STRING, destroy); + this.nbtItem = nbtItem; + super.applyID(); + } + + public BookBuilder(Enchantment enchantment) { + this(enchantment, enchantment.getMax()); + //this(enchantment, ThreadLocalRandom.current().nextInt(1, enchantment.getMax() + 1)); + } + + public BookBuilder(ItemStack itemStack) { + super(NbtTags.ENCHANT_BOOK_DATA_STRING); + this.nbtItem = new NBTItem(itemStack); + + this.success = this.getSuccessRate(); + this.destroy = this.getDestroyRate(); + } + + public BookBuilder(NBTItem nbtItem) { + super(NbtTags.ENCHANT_BOOK_DATA_STRING); + this.nbtItem = nbtItem; + + this.success = this.getSuccessRate(); + this.destroy = this.getDestroyRate(); + } + + private int generateChanceDestroy(Enchantment enchantment) { + //return ThreadLocalRandom.current().nextInt(70, 101); + switch (enchantment.getTier()) { + case SOUL: + return ThreadLocalRandom.current().nextInt(0, 40); + case HEROIC: + return ThreadLocalRandom.current().nextInt(0, 75); + case CURSED: + return ThreadLocalRandom.current().nextInt(0, 35); + default: + return 0; + } + } + + private int generateChanceSuccess(Enchantment enchantment) { + switch (enchantment.getTier()) { + case SOUL: + return ThreadLocalRandom.current().nextInt(50, 101); + case HEROIC: + return ThreadLocalRandom.current().nextInt(35, 101); + case CURSED: + return ThreadLocalRandom.current().nextInt(65, 101); + default: + return 100; + } + + } + + private int generateDustValue() { + Random random = new Random(); + return random.nextInt(16); + } + + public int getDustValue() { + return this.nbtItem.getInteger("dust-value"); + } + + public int getSuccessRate() { + return this.nbtItem.getInteger(NbtTags.SUCCESS_RATE_STRING); + } + + public int getDestroyRate() { + return this.nbtItem.getInteger(NbtTags.DESTROY_RATE_STRING); + } + + public BookBuilder setSuccessRate(int successRate) { + this.success = successRate; + this.nbtItem.setInteger(NbtTags.SUCCESS_RATE_STRING, success); + + this.nbtItem = new NBTItem(new ItemBuilder(this.nbtItem.getItem()) + .setLoreLine("&a" + success + "% Success Rate", 0) + .colorize() + .build()); + return this; + } + + public BookBuilder addSuccessRate(int amount) { + this.setSuccessRate(Math.min(100, this.getSuccessRate() + amount)); + return this; + } + + public BookBuilder setDestroyRate(int destroyRate) { + this.destroy = destroyRate; + this.nbtItem.setInteger(NbtTags.DESTROY_RATE_STRING, destroy); + + this.nbtItem = new NBTItem(new ItemBuilder(this.nbtItem.getItem()) + .setLoreLine("&c" + destroy + "% Destroy Rate", 1) + .colorize() + .build()); + return this; + } + + public Enchantment getBookEnchantment() { + return EnchantRegister.getInstance().getEnchantmentFromID(this.nbtItem.getString("enchantment")); + } + + public int getBookLevel() { + return this.nbtItem.getInteger("level"); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/CustomItem.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/CustomItem.java new file mode 100644 index 0000000..7a0e50b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/CustomItem.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import org.bukkit.inventory.ItemStack; + +public abstract class CustomItem { + + protected NBTItem nbtItem; + protected final String id; + + public CustomItem(String id) { + this.id = id; + } + + protected void applyID() { + this.nbtItem.setString(NbtTags.DATA_STRING, id); + } + + public String getID() { + return this.id; + } + + public ItemStack build() { + return this.nbtItem.getItem(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/DustBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/DustBuilder.java new file mode 100644 index 0000000..32cb630 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/DustBuilder.java @@ -0,0 +1,71 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.concurrent.ThreadLocalRandom; + +@Getter +public class DustBuilder extends CustomItem { + + private int percent; + + public DustBuilder(EnchantTier enchantTier, int percent) { + super(NbtTags.DUST_DATA_STRING); + this.percent = percent; + + boolean isPrimal = percent >= 10; + Material material = isPrimal ? Material.GLOWSTONE_DUST : Material.SUGAR; + String name = isPrimal ? enchantTier.getColor() + "&l" + enchantTier.getFormatedName() + " Primal Dust" : enchantTier.getColor() + enchantTier.getFormatedName() + " Dust"; + String isBold = isPrimal ? "&l" : ""; + + ItemStack itemStack = new ItemBuilder(material) + .setName(name) + .addLore( + "&a" + isBold + "+" + percent + "% SUCCESS", + "&7Apply to a " + enchantTier.getColor() + isBold + enchantTier.getFormatedName() + " &7Enchanted Book", + "&7to increase its success rate by " + enchantTier.getColor() + isBold + percent + "%", + "", + "&7Place dust on an enchantment book" + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + //nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setInteger("dust-percent", percent); + nbtItem.setString("dust-tier", enchantTier.name()); + super.nbtItem = nbtItem; + super.applyID(); + } + + public DustBuilder(EnchantTier enchantTier) { + this(enchantTier, ThreadLocalRandom.current().nextInt(1, 15)); + this.percent = this.getPercent(); + } + + public DustBuilder(ItemStack itemStack) { + super(NbtTags.DUST_DATA_STRING); + this.nbtItem = new NBTItem(itemStack); + this.percent = this.getPercent(); + } + + public int getPercent() { + return this.nbtItem.getInteger("dust-percent"); + } + + public EnchantTier getEnchantTier() { + return EnchantTier.valueOf(this.nbtItem.getString("dust-tier")); + } + + public DustBuilder setPercent(int percent) { + this.percent = percent; + this.nbtItem.setInteger("dust-percent", percent); + return this; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/EnchantedItemBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/EnchantedItemBuilder.java new file mode 100644 index 0000000..bcc7bfd --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/EnchantedItemBuilder.java @@ -0,0 +1,355 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedenchants.struct.EnchantRegister; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.HeroicEnchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.MiscUtils; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.*; +import java.util.stream.Collectors; + +public class EnchantedItemBuilder { + + private transient final NBTItem nbtItem; + private transient final NBTCompound enchantsCompound; + + public EnchantedItemBuilder(ItemStack itemStack) { + this(new NBTItem(itemStack)); + } + + public EnchantedItemBuilder(NBTItem itemStack) { + this.nbtItem = itemStack; + this.enchantsCompound = this.getOrCreateEnchantsCompound(); + if (!this.nbtItem.hasKey(NbtTags.SLOTS_AMOUNT_STRING)) + this.nbtItem.setInteger(NbtTags.SLOTS_AMOUNT_STRING, 9); + if (!this.nbtItem.hasKey(NbtTags.PROTECTED_STRING)) + this.nbtItem.setBoolean(NbtTags.PROTECTED_STRING, false); + } + + private NBTCompound getOrCreateEnchantsCompound() { + NBTCompound enchantsCompound = this.nbtItem.getCompound(NbtTags.ENCHANTS_TAG); + if (enchantsCompound == null) enchantsCompound = this.nbtItem.addCompound(NbtTags.ENCHANTS_TAG); + return enchantsCompound; + } + + public HashMap getEnchantments() { + HashMap enchants = new HashMap<>(); + + this.enchantsCompound.getKeys().forEach(key -> { + int level = this.enchantsCompound.getInteger(key); + Enchantment enchantment = EnchantRegister.getInstance().getEnchantmentFromID(key); + if (enchantment == null) return; + enchants.put(enchantment, level); + }); + + return enchants; + } + + public HashMap getEnchantmentsAsString() { + HashMap enchants = new HashMap<>(); + + this.enchantsCompound.getKeys().forEach(key -> { + int level = this.enchantsCompound.getInteger(key); + enchants.put(key, level); + }); + + return enchants; + } + + public boolean hasEnchantment(Enchantment enchantment) { + return this.getEnchantments().containsKey(enchantment); + } + + public boolean hasEnchantment(String enchantment) { + return this.getEnchantmentsAsString().containsKey(enchantment); + } + + public boolean hasEnchantments() { + return this.getEnchantments().size() > 0; + } + + // returns 0 if not applies + public int getEnchantmentLevel(Enchantment enchantment) { + if (!this.hasEnchantment(enchantment)) return 0; + return this.enchantsCompound.getInteger(enchantment.getID()); + } + + public int getEnchantmentLevel(String enchantment) { + if (!this.hasEnchantment(enchantment)) return 0; + return this.enchantsCompound.getInteger(enchantment); + } + + public int getAmountOfEnchantments() { + return this.getEnchantments().keySet().size(); + } + + public boolean hasSoulTrackerAlreadyApplied() { + return this.nbtItem.hasKey("soul-tracker"); + } + + public EnchantTier getSoulTrackerTier() { + return EnchantTier.valueOf(this.nbtItem.getString("soul-tracker-tier")); + } + + public int getHarvestedSouls() { + return MiscUtils.defaultIfNull(this.nbtItem.getInteger("soul-tracker"), 0); + } + + public void incrementHarvestedSouls() { + this.nbtItem.setInteger("soul-tracker", this.getHarvestedSouls() + 1); + } + + public void setHarvestedSouls(int amount) { + this.nbtItem.setInteger("soul-tracker", amount); + } + + public void removeHarvestedSouls(int amount) { + this.nbtItem.setInteger("soul-tracker", Math.max(this.getHarvestedSouls() - amount, 0)); + } + + public void resetHarvestedSouls() { + this.nbtItem.setInteger("soul-tracker", 0); + } + + public EnchantedItemBuilder applySoulTracker(SoulTrackerBuilder soulTrackerBuilder) { + this.nbtItem.setInteger("soul-tracker", 0); + this.nbtItem.setString("soul-tracker-tier", soulTrackerBuilder.getEnchantTier().name()); + this.addSoulsHarvestedToLore(); + return this; + } + + public EnchantedItemBuilder addEnchantment(Enchantment enchantment, int level) { + if (enchantment instanceof HeroicEnchantment) { + HeroicEnchantment heroicEnchantment = ((HeroicEnchantment) enchantment); + String baseEnchantment = heroicEnchantment.getBaseEnchantment(); + if (this.getEnchantmentsAsString().containsKey(baseEnchantment)) { + this.removeEnchantment(baseEnchantment); + } + } + + this.enchantsCompound.setInteger(enchantment.getID(), level); + ItemStack item = this.nbtItem.getItem(); + ItemMeta itemMeta = item.getItemMeta(); + List lore = itemMeta.getLore(); + if (lore == null) lore = new ArrayList<>(); + + lore.add(this.getEnchantments().keySet().size() - 1, enchantment.getTier().getColor() + enchantment.getName() + " " + RomanNumeral.convertToRoman(level)); + + itemMeta.setLore(lore); + this.nbtItem.getItem().setItemMeta(itemMeta); + return this; + } + + public EnchantedItemBuilder addEnchantments(Map enchantments) { + enchantments.forEach((this::addEnchantment)); + return this; + } + + public Enchantment selectRandomEnchantment() { + Random random = new Random(); + int number = random.nextInt(this.getEnchantments().size()); + Enchantment[] enchantments = this.getEnchantments().keySet().toArray(new Enchantment[0]); + return enchantments[number]; + } + + public Enchantment selectRandomEnchantment(EnchantTier excludedTier) { + Random random = new Random(); + Set enchantmentsToBeFiltered = this.getEnchantments().keySet(); + enchantmentsToBeFiltered = enchantmentsToBeFiltered.stream().filter(enchantment -> enchantment.getTier() != excludedTier).collect(Collectors.toSet()); + int number = random.nextInt(enchantmentsToBeFiltered.size()); + Enchantment[] enchantments = enchantmentsToBeFiltered.toArray(new Enchantment[0]); + return enchantments[number]; + } + + public EnchantedItemBuilder removeEnchantment(Enchantment enchantment) { + this.enchantsCompound.removeKey(enchantment.getID()); + ItemStack item = this.nbtItem.getItem(); + ItemMeta itemMeta = item.getItemMeta(); + List lore = itemMeta.getLore(); + if (lore == null) return this; + + for (int i = 0; i < this.getEnchantments().size() + 1; i++) { + if (lore.get(i).contains(enchantment.getName())) { + lore.remove(i); + break; + } + } + + + itemMeta.setLore(lore); + this.nbtItem.getItem().setItemMeta(itemMeta); + return this; + } + + public void removeEnchantment(String enchantmentID) { + this.enchantsCompound.removeKey(enchantmentID); + Enchantment enchantment = EnchantRegister.getInstance().getEnchantmentFromID(enchantmentID); + ItemStack item = this.nbtItem.getItem(); + ItemMeta itemMeta = item.getItemMeta(); + List lore = itemMeta.getLore(); + if (lore == null) return; + + for (int i = 0; i < this.getEnchantments().size() + 1; i++) { + if (lore.get(i).contains(enchantment.getName())) { + lore.remove(i); + break; + } + } + + + itemMeta.setLore(lore); + this.nbtItem.getItem().setItemMeta(itemMeta); + } + + public int getSlots() { + return MiscUtils.defaultIfNull(this.nbtItem.getInteger(NbtTags.SLOTS_AMOUNT_STRING), 9); + } + + public void setSlots(int slots) { + this.nbtItem.setInteger(NbtTags.SLOTS_AMOUNT_STRING, slots); + } + + public boolean isProtected() { + return this.nbtItem.getBoolean(NbtTags.PROTECTED_STRING); + } + + public void setProtected(boolean status) { + this.nbtItem.setBoolean(NbtTags.PROTECTED_STRING, status); + + if (status) { + this.addProtectedToLore(); + return; + } + + this.removeProtectedFromLore(); + } + + private void addProtectedToLore() { + ItemStack itemStack = this.nbtItem.getItem(); + ItemMeta itemMeta = itemStack.getItemMeta(); + List lore = this.getLore(); + String protectedLoreLine = CC.translate("&f&lPROTECTED"); + + if (lore.contains(protectedLoreLine)) return; + + lore.add(protectedLoreLine); + + itemMeta.setLore(lore); + this.nbtItem.getItem().setItemMeta(itemMeta); + } + + private void removeProtectedFromLore() { + ItemStack itemStack = this.nbtItem.getItem(); + ItemMeta itemMeta = itemStack.getItemMeta(); + + String protectedLoreLine = CC.translate("&f&lPROTECTED"); + + List lore = this.getLore() + .stream() + .filter(str -> !str.equals(protectedLoreLine)) + .collect(Collectors.toList()); + + itemMeta.setLore(lore); + this.nbtItem.getItem().setItemMeta(itemMeta); + } + + public EnchantedItemBuilder sortEnchantLore() { + if (this.getLore().isEmpty()) return this; + + List sortedEnchantsLore = this.getEnchantments() + .keySet() + .stream() + .sorted(Comparator.comparingInt(Enchantment::getEnchantTierWeight)) + .map(enchantment -> enchantment.getTier().getColor() + enchantment.getName() + " " + RomanNumeral.convertToRoman(this.getEnchantmentLevel(enchantment))) + .collect(Collectors.toList()); + + List newLore = this.getLore(); + + for (int i = 0; i < this.getAmountOfEnchantments(); i++) { + newLore.set(i, sortedEnchantsLore.get(i)); + } + + ItemStack itemStack = this.nbtItem.getItem(); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setLore(newLore); + this.nbtItem.getItem().setItemMeta(itemMeta); + return this; + } + + private void addSoulsHarvestedToLore() { + ItemStack itemStack = this.nbtItem.getItem(); + ItemMeta itemMeta = itemStack.getItemMeta(); + + String soulHarvesterLoreLine = CC.translate("&6&lSouls Harvested: "); + + List lore = this.getLore() + .stream() + .filter(str -> !str.startsWith(soulHarvesterLoreLine)) + .collect(Collectors.toList()); + + lore.add(soulHarvesterLoreLine + this.getHarvestedSouls()); + + itemMeta.setLore(lore); + this.nbtItem.getItem().setItemMeta(itemMeta); + } + + public void updateSoulsHarvested() { + ItemStack itemStack = this.nbtItem.getItem(); + ItemMeta itemMeta = itemStack.getItemMeta(); + + String soulHarvesterLoreLine = CC.translate("&6&lSouls Harvested: "); + + List lore = this.getLore(); + lore.replaceAll(str -> str.startsWith(soulHarvesterLoreLine) ? soulHarvesterLoreLine + this.getHarvestedSouls() : str); + + itemMeta.setLore(lore); + this.nbtItem.getItem().setItemMeta(itemMeta); + } + + public void updateSlotsLore(int newSlotsAmount) { + ItemStack itemStack = this.nbtItem.getItem(); + ItemMeta itemMeta = itemStack.getItemMeta(); + + List lore = this.getLore() + .stream() + .filter(str -> !str.startsWith(CC.translate("&a&l" + this.getSlots() + " Enchantment Slots &7(Orb [&a+"))) + .collect(Collectors.toList()); + + lore.add(CC.translate("&a&l" + newSlotsAmount + " Enchantment Slots &7(Orb [&a+" + (newSlotsAmount - 9) + "&7])")); + + itemMeta.setLore(lore); + this.nbtItem.getItem().setItemMeta(itemMeta); + } + + public EnchantedItemBuilder addEnchantAmountToName() { + ItemStack itemStack = this.nbtItem.getItem(); + ItemMeta itemMeta = itemStack.getItemMeta(); + String itemName = itemMeta.getDisplayName(); + + if (itemName != null && itemName.contains(CC.translate("&d&l[&b&l&n"))) { + itemName = itemName.substring(0, itemName.lastIndexOf(" ")); + } + + String name = MiscUtils.defaultIfNull(itemName, CC.translate("&b" + MiscUtils.toNiceString(itemStack.getType().name()))); + + itemMeta.setDisplayName(CC.translate(name + " &d&l[&b&l&n" + this.getAmountOfEnchantments() + "&d&l]")); + this.nbtItem.getItem().setItemMeta(itemMeta); + return this; + } + + public List getLore() { + return MiscUtils.defaultIfNull(this.nbtItem.getItem().getItemMeta().getLore(), new ArrayList<>()); + } + + public ItemStack build() { + return this.nbtItem.getItem(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/HeroicBlackScrollBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/HeroicBlackScrollBuilder.java new file mode 100644 index 0000000..7e88eb2 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/HeroicBlackScrollBuilder.java @@ -0,0 +1,46 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.concurrent.ThreadLocalRandom; + +public class HeroicBlackScrollBuilder extends CustomItem { + + public HeroicBlackScrollBuilder(int percent) { + super(NbtTags.HEROIC_BLACK_SCROLL_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.INK_SACK) + .setName("&d&lHeroic Black Scroll") + .addLore( + "&7Removes a random enchantment", + "&7from an item and converts", + "&7it into a &d"+ percent + "%&7 success book.", + "&fPlace scroll onto an item to extract." + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + //nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setInteger("scroll-percent", percent); + super.nbtItem = nbtItem; + super.applyID(); + } + + public HeroicBlackScrollBuilder() { + this(ThreadLocalRandom.current().nextInt(1, 101)); + } + + public HeroicBlackScrollBuilder(ItemStack itemStack) { + super(NbtTags.HEROIC_BLACK_SCROLL_DATA_STRING); + this.nbtItem = new NBTItem(itemStack); + } + + public int getPercent() { + return this.nbtItem.getInteger("scroll-percent"); + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/InfernalDustBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/InfernalDustBuilder.java new file mode 100644 index 0000000..1e48f5f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/InfernalDustBuilder.java @@ -0,0 +1,43 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +@Getter +public class InfernalDustBuilder extends CustomItem { + + public InfernalDustBuilder(EnchantTier enchantTier) { + super(NbtTags.INFERNAL_DUST_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.REDSTONE) + .setName("&4&lInfernal Dust &8(" + enchantTier.getColor() + enchantTier.getFormatedName() + "&8)") + .addLore( + "&7Apply to a " + enchantTier.getColor() + enchantTier.getFormatedName() + " &7Enchanted Book", + "&7to set the success rate to " + enchantTier.getColor() + "100%", + "", + "&7Place dust on an enchantment book" + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + //nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setString("dust-tier", enchantTier.name()); + super.nbtItem = nbtItem; + super.applyID(); + } + + public InfernalDustBuilder(ItemStack itemStack) { + super(NbtTags.INFERNAL_DUST_DATA_STRING); + this.nbtItem = new NBTItem(itemStack); + } + + public EnchantTier getEnchantTier() { + return EnchantTier.valueOf(this.nbtItem.getString("dust-tier")); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/ItemRenameTagBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/ItemRenameTagBuilder.java new file mode 100644 index 0000000..801c63b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/ItemRenameTagBuilder.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class ItemRenameTagBuilder extends CustomItem { + + public ItemRenameTagBuilder() { + super(NbtTags.RENAME_TAG_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.NAME_TAG) + .setName("&6&lItem NameTag") + .addLore( + "&7Rename and customize your equipment" + ) + .colorize() + .build(); + + super.nbtItem = new NBTItem(itemStack); + super.applyID(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/MiscItems.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/MiscItems.java new file mode 100644 index 0000000..b756518 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/MiscItems.java @@ -0,0 +1,35 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class MiscItems { + + public static ItemStack getTinkererDisplayXpBottle(int amountOfXP) { + ItemStack itemStack = new ItemBuilder(Material.EXP_BOTTLE) + .setName("&a&lExperience Bottle&7 (Throw)") + .setLore( + "&dValue &f" + amountOfXP + " XP", + "&dEnchanter &fCosmic Tinkerer" + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("xp-value", amountOfXP); + return nbtItem.getItem(); + } + + public static ItemStack getMysteryDust() { + return new ItemBuilder(Material.SULPHUR) + .setName("&fMystery Dust") + .setLore( + "&7The failed bi-product of", + "&7Magic and Primal dust." + ) + .colorize() + .build(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/OmniBlackScrollBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/OmniBlackScrollBuilder.java new file mode 100644 index 0000000..81e37af --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/OmniBlackScrollBuilder.java @@ -0,0 +1,45 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.concurrent.ThreadLocalRandom; + +public class OmniBlackScrollBuilder extends CustomItem { + + public OmniBlackScrollBuilder(int percent) { + super(NbtTags.OMNI_BLACK_SCROLL_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.INK_SACK) + .setName("&3&lOmni &f&lBlack Scroll") + .addLore( + "&7Removes an enchantment of choice", + "&7from an item and converts", + "&7it into a &f" + percent + "%&7 success book.", + "&fPlace scroll onto an item to extract." + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("scroll-percent", percent); + super.nbtItem = nbtItem; + super.applyID(); + } + + public OmniBlackScrollBuilder() { + this(ThreadLocalRandom.current().nextInt(1, 101)); + } + + public OmniBlackScrollBuilder(ItemStack itemStack) { + super(NbtTags.OMNI_BLACK_SCROLL_DATA_STRING); + this.nbtItem = new NBTItem(itemStack); + } + + public int getPercent() { + return this.nbtItem.getInteger("scroll-percent"); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/OrbBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/OrbBuilder.java new file mode 100644 index 0000000..34e4faf --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/OrbBuilder.java @@ -0,0 +1,95 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedenchants.struct.enums.GearType; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Locale; + +public class OrbBuilder extends CustomItem { + + public OrbBuilder(OrbType orbType, int slots, int successRate) { + super(NbtTags.ORB_DATA_STRING); + + String loreFix = orbType == OrbType.ARMOR ? "slots on a piece of armor by " : "slots on a weapon by "; + + ItemStack itemStack = new ItemBuilder(Material.EYE_OF_ENDER) + .setName("&6&l" + orbType.getFancyName() + " Enchantment Orb [&a&n" + slots + "&6&l]") + .addLore( + "&a" + successRate + "% Success Rate", + "", + "&6+" + (slots - 9) + " Enchantment Slot", + "&6" + slots + " Max Enchantment Slots", + "", + "&eIncrease the amount of enchantment", + "&e" + loreFix + (slots - 9) + ".", + "&eUp to a maximum of " + slots + ".", + "&7Drag n' Drop onto " + orbType.name().toLowerCase(Locale.ROOT) + " to apply." + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + //nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setInteger(NbtTags.SUCCESS_RATE_STRING, successRate); + nbtItem.setInteger(NbtTags.SLOTS_AMOUNT_STRING, slots); + nbtItem.setString(NbtTags.ORB_TYPE_STRING, orbType.name()); + super.nbtItem = nbtItem; + super.applyID(); + } + + public OrbBuilder(ItemStack itemStack) { + super(NbtTags.ORB_DATA_STRING); + super.nbtItem = new NBTItem(itemStack); + } + + public int getSlots() { + return this.nbtItem.getInteger(NbtTags.SLOTS_AMOUNT_STRING); + } + + public int getSuccessRate() { + return this.nbtItem.getInteger(NbtTags.SUCCESS_RATE_STRING); + } + + public OrbBuilder setSuccessRate(int successRate) { + this.nbtItem.setInteger(NbtTags.SUCCESS_RATE_STRING, successRate); + + this.nbtItem = new NBTItem(new ItemBuilder(this.nbtItem.getItem()) + .setLoreLine("&a" + successRate + "% Success Rate", 0) + .colorize() + .build()); + return this; + } + + public OrbBuilder addSuccessRate(int amount) { + this.setSuccessRate(Math.min(100, this.getSuccessRate() + amount)); + return this; + } + + public OrbType getOrbType() { + return OrbType.valueOf(this.nbtItem.getString(NbtTags.ORB_TYPE_STRING)); + } + + public enum OrbType { + WEAPON(GearType.WEAPON), + ARMOR(GearType.ARMOR); + + final GearType applicableItems; + + OrbType(GearType applicableItems) { + this.applicableItems = applicableItems; + } + + public boolean canBeAppliedToItem(ItemStack itemStack) { + return this.applicableItems.getItems().contains(itemStack.getType()); + } + + public String getFancyName() { + return StringUtils.toNiceString(this.name()); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/RandomizationScrollBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/RandomizationScrollBuilder.java new file mode 100644 index 0000000..520e7a7 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/RandomizationScrollBuilder.java @@ -0,0 +1,39 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class RandomizationScrollBuilder extends CustomItem { + + public RandomizationScrollBuilder(EnchantTier tier) { + super(NbtTags.RANDOMIZATION_SCROLL_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.PAPER) + .setName(tier.getColor() + tier.getFormatedName() + " Randomization Scroll") + .addLore( + "&7Apply to any " + tier.getFormatedName() + " Enchantment Book", + "&7to reroll the success and destroy rates.", + "", + "&7Drag n' drop onto &nenchantment book&7 to apply." + ) + .colorize() + .build(); + + super.nbtItem = new NBTItem(itemStack); + super.nbtItem.setString("tier", tier.name()); + super.applyID(); + } + + public RandomizationScrollBuilder(ItemStack itemStack) { + super(NbtTags.RANDOMIZATION_SCROLL_DATA_STRING); + super.nbtItem = new NBTItem(itemStack); + } + + public EnchantTier getTier() { + return EnchantTier.valueOf(super.nbtItem.getString("tier")); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SecretDust.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SecretDust.java new file mode 100644 index 0000000..fe2ff65 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SecretDust.java @@ -0,0 +1,56 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Random; + +public class SecretDust extends CustomItem { + + public SecretDust(EnchantTier enchantTier, int maxPercent) { + super(NbtTags.SECRET_DUST_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.FIREBALL) + .setName(enchantTier.getColor() + enchantTier.getFormatedName() + " Secret Dust &7(Right Click)") + .addLore( + "&aSuccess: +0-" + maxPercent + "%", + "&7Contains: &bMagic, &ePrimal,&7 or &fMystery&7 dust.", + "&7An unidentified satchel of dust." + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("dust-tier", enchantTier.name()); + nbtItem.setInteger("dust-max-percent", maxPercent); + super.nbtItem = nbtItem; + super.applyID(); + } + + public SecretDust(ItemStack itemStack) { + super(NbtTags.SECRET_DUST_DATA_STRING); + super.nbtItem = new NBTItem(itemStack); + } + + public int getMaxPercent() { + return nbtItem.getInteger("dust-max-percent"); + } + + public EnchantTier getEnchantTier() { + return EnchantTier.valueOf(nbtItem.getString("dust-tier")); + } + + public int generateRandomPercent() { + Random random = new Random(); + return random.nextInt(this.getMaxPercent() + 1) + 1; + } + + public ItemStack getDust() { + if (Math.random() < 0.7) return MiscItems.getMysteryDust(); + return new DustBuilder(this.getEnchantTier(), this.generateRandomPercent()).build(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulGemBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulGemBuilder.java new file mode 100644 index 0000000..fdd371f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulGemBuilder.java @@ -0,0 +1,101 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +public class SoulGemBuilder extends CustomItem { + + public SoulGemBuilder(int soulAmount) { + super(NbtTags.SOUL_GEM_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.EMERALD) + .setName(this.getSoulGemName(soulAmount)) + .addLore( + "", + "&c&l*&r &cClick this item to toggle &nSoul Mode&r", + "&7While in Soul Mode your ACTIVE god tier", + "&7enchantment will activate and drain souls", + "&7for as long as the mode is enabled.", + "", + "&c&l*&r &7Use &c&n/splitsouls&r &7with this item", + "&7to split souls off of it.", + "", + "&c&l*&r &7Stack other &cSoul Gems&r &7ontop of this", + "&7one to combine their soul count." + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setInteger("soul-amount", soulAmount); + super.nbtItem = nbtItem; + super.applyID(); + } + + public SoulGemBuilder(ItemStack itemStack) { + super(NbtTags.SOUL_GEM_DATA_STRING); + this.nbtItem = new NBTItem(itemStack); + } + + public int getSouls() { + return super.nbtItem.getInteger("soul-amount"); + } + + public SoulGemBuilder setSouls(int soulAmount) { + this.nbtItem.setInteger("soul-amount", soulAmount); + this.updateSoulAmountName(); + return this; + } + + public SoulGemBuilder addSouls(int amount) { + this.setSouls(this.getSouls() + amount); + return this; + } + + public SoulGemBuilder removeSouls(int amount) { + if (this.getSouls() - amount <= 0) { + this.setSouls(0); + return this; + } + + this.setSouls(this.getSouls() - amount); + return this; + } + + public void updateSoulAmountName() { + this.nbtItem = new NBTItem(new ItemBuilder(this.nbtItem.getItem()) + .setName(this.getSoulGemName(this.getSouls())) + .build()); + } + + private String getSoulGemName(int soulAmount) { + return CC.translate("&c&lSoul Gem [" + getColor(soulAmount) + soulAmount + "&c&l]"); + } + + private static String getColor(int amount) { + if (amount >= 5000) { + return ChatColor.DARK_RED.toString() + ChatColor.BOLD.toString(); + } + if (amount >= 1000) { + return ChatColor.GOLD.toString() + ChatColor.BOLD.toString(); + } + if (amount >= 500) { + return ChatColor.AQUA.toString(); + } + if (amount >= 100) { + return ChatColor.GREEN.toString(); + } + if (amount >= 0) { + return ChatColor.WHITE.toString(); + } + return ""; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulPearlBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulPearlBuilder.java new file mode 100644 index 0000000..1f46fc3 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulPearlBuilder.java @@ -0,0 +1,30 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class SoulPearlBuilder extends CustomItem { + + public SoulPearlBuilder() { + super(NbtTags.SOUL_PEARL_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.ENDER_PEARL) + .setName("&5&lSoul Pearl") + .addLore( + "&dA rare /dungeon trinket that", + "&dfunctions like a normal enderpearl,", + "&dbut costs souls instead of being,", + "&dconsumed on use.", + "", + "&5&nsoul Cost:&d 5/pearl" + ) + .colorize() + .build(); + + super.nbtItem = new NBTItem(itemStack); + super.applyID(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulTrackerBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulTrackerBuilder.java new file mode 100644 index 0000000..35d5424 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/SoulTrackerBuilder.java @@ -0,0 +1,42 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class SoulTrackerBuilder extends CustomItem { + + public SoulTrackerBuilder(EnchantTier enchantTier) { + super(NbtTags.SOUL_TRACKER_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.PAPER) + .setName(enchantTier.getColor() + enchantTier.getFormatedName() + " Soul Tracker") + .addLore( + "&7Apply to weapons to start tracking", + enchantTier.getColor() + enchantTier.getFormatedName() + " Souls&7 collected from kills.", + "", + "&c&lWARNING:&7 Previously tracked souls", + "&7will be released on apply." + ) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + //nbtItem.setString("randomUUID", String.valueOf(UUID.randomUUID())); + nbtItem.setString("tracker-tier", enchantTier.name()); + super.nbtItem = nbtItem; + super.applyID(); + } + + public SoulTrackerBuilder(ItemStack itemStack) { + super(NbtTags.SOUL_TRACKER_DATA_STRING); + super.nbtItem = new NBTItem(itemStack); + } + + public EnchantTier getEnchantTier() { + return EnchantTier.valueOf(this.nbtItem.getString("tracker-tier")); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/TransmogScrollBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/TransmogScrollBuilder.java new file mode 100644 index 0000000..643453a --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/TransmogScrollBuilder.java @@ -0,0 +1,28 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class TransmogScrollBuilder extends CustomItem { + + public TransmogScrollBuilder() { + super(NbtTags.TRANSMOG_SCROLL_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.PAPER) + .setName("&c&lTransmog Scroll") + .addLore( + "&7Organizes enchants by &e&nrarity&7 on item", + "&7and adds the &dlore &bcount&7 to name.", + "", + "&e&oPlace scroll on item to apply." + ) + .colorize() + .build(); + + super.nbtItem = new NBTItem(itemStack); + super.applyID(); + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/WhiteScrollBuilder.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/WhiteScrollBuilder.java new file mode 100644 index 0000000..e5b8e69 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/items/WhiteScrollBuilder.java @@ -0,0 +1,27 @@ +package net.crankedpvp.crankedenchants.struct.items; + +import net.crankedpvp.crankedenchants.struct.NbtTags; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class WhiteScrollBuilder extends CustomItem { + + public WhiteScrollBuilder() { + super(NbtTags.WHITE_SCROLL_DATA_STRING); + + ItemStack itemStack = new ItemBuilder(Material.EMPTY_MAP) + .setName("&fWhite Scroll") + .addLore( + "&fPrevent an item from being destroyer", + "&fdue to a failed Enchantment Book.", + "&ePlace scroll on item to apply" + ) + .colorize() + .build(); + + super.nbtItem = new NBTItem(itemStack); + super.applyID(); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/souls/SoulManager.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/souls/SoulManager.java new file mode 100644 index 0000000..194daba --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/struct/souls/SoulManager.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedenchants.struct.souls; + +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.cache.SoulModeCache; +import net.crankedpvp.crankedenchants.struct.items.SoulGemBuilder; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class SoulManager { + + private final Map soulModePlayers; + + public SoulManager() { + this.soulModePlayers = new HashMap<>(); + } + + public void enableSoulMode(Player player, SoulGemBuilder soulGemBuilder, int slot) { + if (isInSoulMode(player)) return; + soulModePlayers.put(player.getUniqueId(), new SoulModeCache(player, soulGemBuilder, slot)); + Language.SOUL_MODE_ENABLE.send(player); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0F, 1.2F); + } + + public void disableSoulMode(Player player) { + if (!isInSoulMode(player)) return; + soulModePlayers.remove(player.getUniqueId()); + Language.SOUL_MODE_DISABLE.send(player); + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 1.0F, 1.2F); + } + + public void toggleSoulMode(Player player, SoulGemBuilder soulGemBuilder, int slot) { + if (isInSoulMode(player)) { + disableSoulMode(player); + return; + } + enableSoulMode(player, soulGemBuilder, slot); + } + + public boolean isInSoulMode(Player player) { + return soulModePlayers.containsKey(player.getUniqueId()); + } + + public Collection getPlayersInSoulMode() { + return this.soulModePlayers.values(); + } + + public SoulModeCache getSoulModeCache(Player player) { + return this.soulModePlayers.get(player.getUniqueId()); + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/AngelicTask.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/AngelicTask.java new file mode 100644 index 0000000..386f12d --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/AngelicTask.java @@ -0,0 +1,36 @@ +package net.crankedpvp.crankedenchants.tasks; + +import lombok.AllArgsConstructor; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedutils.CrankedUtils; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +@AllArgsConstructor +public class AngelicTask extends BukkitRunnable { + + private final Player player; + private final double amount; + private double timesItHeals; + + @Override + public void run() { + if (this.player == null || this.player.isDead()) { + this.cancel(); + return; + } + + if (this.timesItHeals <= 0) { + this.cancel(); + return; + } + + if (!CrankedEnchantsAPI.hasEnchantment(player, "angelic")) { + this.cancel(); + return; + } + + CrankedUtils.getInstance().getDamageHandler().healEntity(this.player, amount, "Angelic"); + this.timesItHeals--; + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/NaturesWrathTask.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/NaturesWrathTask.java new file mode 100644 index 0000000..a10e674 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/NaturesWrathTask.java @@ -0,0 +1,66 @@ +package net.crankedpvp.crankedenchants.tasks; + +import net.crankedpvp.crankedenchants.events.NaturesLightningHitEvent; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.NaturesWrathCache; +import net.crankedpvp.crankedenchants.utils.CacheUtils; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.List; + +public class NaturesWrathTask extends BukkitRunnable { + + private final List affectedPlayers; + private final int level; + private int timeLeft; + + public NaturesWrathTask(List affectedPlayers, int level) { + this.affectedPlayers = affectedPlayers; + this.level = level; + this.timeLeft = 5; + } + + @Override + public void run() { + if (this.timeLeft <= 0) { + for (Player victim : this.affectedPlayers) { + if (victim != null) { + NaturesWrathCache naturesWrathCache = CacheUtils.getNaturesWrathCache(victim); + naturesWrathCache.removeNaturesWrathEffect(victim); + } + } + this.cancel(); + return; + } + + for (Player victim : this.affectedPlayers) { + if (victim != null && !victim.isDead()) { + + if (!WorldGuardUtils.canPvPInRegion(victim)) { + continue; + } + + NaturesLightningHitEvent event = new NaturesLightningHitEvent(victim, this.level, this.timeLeft); + + Bukkit.getPluginManager().callEvent(event); + + if(event.isCancelled()) return; + this.applyNaturesWrathDamage(victim); + } + } + this.timeLeft--; + } + + public void applyNaturesWrathDamage(Player player) { + player.getWorld().strikeLightningEffect(player.getLocation()); + player.damage(this.level); + player.playSound(player.getLocation(), Sound.GHAST_SCREAM2, 2.0f, 2.0f); + player.sendMessage(CC.translate("&2&l** NATURES **")); + + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/RotAndDecayTask.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/RotAndDecayTask.java new file mode 100644 index 0000000..23f951f --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/RotAndDecayTask.java @@ -0,0 +1,116 @@ +package net.crankedpvp.crankedenchants.tasks; + +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.List; + +public class RotAndDecayTask extends BukkitRunnable { + + private static final int RADIUS = 7; + + private DamageHandler damageHandler; + private final Player player; + + private final List blockList; + private final List blocksToClear; + private List previousBlockList; + private int countDown; + private double damage; + + public RotAndDecayTask(DamageHandler damageHandler, Player player, int abilityDurationInSeconds, double damage) { + this.damageHandler = damageHandler; + this.player = player; + this.countDown = abilityDurationInSeconds; + this.damage = damage; + this.blockList = new ArrayList<>(); + this.blocksToClear = new ArrayList<>(); + this.previousBlockList = new ArrayList<>(); + } + + @Override + public void run() { + + this.previousBlockList.clear(); + this.previousBlockList.addAll(this.blockList); + + if (this.countDown <= 0) { + this.cancel(); + + for (Block block : this.blockList) { + block.getState().update(); + block.getRelative(BlockFace.UP).getState().update(); + } + + this.blockList.clear(); + return; + } + + this.blockList.clear(); + this.setBlocks(); + + this.blocksToClear.addAll(this.previousBlockList); + this.blocksToClear.removeAll(this.blockList); + + for (Block block : this.blocksToClear) { + block.getState().update(); + block.getRelative(BlockFace.UP).getState().update(); + } + + this.blocksToClear.clear(); + + this.countDown--; + } + + public void setBlocks() { + Location loc = this.player.getLocation(); + + int cx = loc.getBlockX(); + int cy = loc.getBlockY() - 1; + int cz = loc.getBlockZ(); + + for (int x = cx - RADIUS; x <= cx + RADIUS; x++) { + for (int z = cz - RADIUS; z <= cz + RADIUS; z++) { + if ((cx - x) * (cx - x) + (cz - z) * (cz - z) <= RADIUS * RADIUS) { + Block block = loc.getWorld().getBlockAt(x, cy, z); + if (block.getType() != Material.AIR && block.getType().isSolid()) { + this.blockList.add(block); + } + + Block blockAbove = loc.getWorld().getBlockAt(x, cy + 1, z); + if (blockAbove.getType() != Material.AIR && blockAbove.getType().isSolid()) { + this.blockList.add(blockAbove); + } + + Block blockBellow = loc.getWorld().getBlockAt(x, cy - 1, z); + if (blockBellow.getType() != Material.AIR && blockBellow.getType().isSolid()) { + this.blockList.add(blockBellow); + } + } + } + } + + for (Player nearbyPlayer : PVPUtils.getNearbyPlayers(this.player, 30)) { + Material material = nearbyPlayer.equals(this.player) ? Material.GLOWSTONE : Material.REDSTONE_BLOCK; + this.blockList.forEach(block -> { + nearbyPlayer.sendBlockChange(block.getLocation(), material, (byte) 0); + }); + } + + for (Player nearbyPlayer : PVPUtils.getNearbyPlayersExceptPlayer(this.player, RADIUS)) { + if (FactionUtils.cantPvPFaction(this.player, nearbyPlayer)) continue; + if (!WorldGuardUtils.canPvPInRegion(this.player)) continue; + if (!WorldGuardUtils.canPvPInRegion(nearbyPlayer)) continue; + this.damageHandler.damage(nearbyPlayer, this.damage, "Rot And Decay Circle"); + } + } +} \ No newline at end of file diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/SoulDrainTask.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/SoulDrainTask.java new file mode 100644 index 0000000..16ae848 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/tasks/SoulDrainTask.java @@ -0,0 +1,88 @@ +package net.crankedpvp.crankedenchants.tasks; + +import net.crankedpvp.crankedenchants.CrankedEnchants; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedenchants.language.Language; +import net.crankedpvp.crankedenchants.struct.cache.SoulModeCache; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.DrainSoulEnchant; +import net.crankedpvp.crankedenchants.struct.enchantstruct.interfaces.SoulEnchant; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedenchants.struct.souls.SoulManager; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; +import xyz.xenondevs.particle.ParticleBuilder; +import xyz.xenondevs.particle.ParticleEffect; + +import java.util.ArrayList; +import java.util.List; + +public class SoulDrainTask extends BukkitRunnable { + + private final SoulManager soulManager; + private final ParticleBuilder spellParticle; + + public SoulDrainTask(CrankedEnchants plugin) { + this.soulManager = plugin.getSoulManager(); + this.spellParticle = new ParticleBuilder(ParticleEffect.SPELL) + .setAmount(15) + .setOffsetY(0.5f) + .setSpeed(0.2f); + } + + @Override + public void run() { + List ranOutOfSouls = new ArrayList<>(); + for (SoulModeCache soulModeCache : this.soulManager.getPlayersInSoulMode()) { + Player player = soulModeCache.getPlayer(); + + ItemStack itemStack = player.getInventory().getItem(soulModeCache.getSlot()); + + if (!CrankedEnchantsAPI.isSoulGem(itemStack)) { + this.soulManager.disableSoulMode(player); + continue; + } + + if (player.getItemInHand() == null) continue; + if (!ItemUtils.isWeapon(player.getItemInHand())) continue; + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(player.getItemInHand()); + int soulCost = 0; + + for (Enchantment enchantment : enchantedItemBuilder.getEnchantments().keySet()) { + if (enchantment instanceof DrainSoulEnchant) { + DrainSoulEnchant soulEnchant = ((DrainSoulEnchant) enchantment); + soulCost += soulEnchant.getSoulCost(); + } else if (enchantment instanceof SoulEnchant) { + SoulEnchant soulEnchant = ((SoulEnchant) enchantment); + soulCost += soulEnchant.getSoulCost(); + } + } + + if (soulCost == 0) continue; + + soulModeCache.getSoulGemBuilder().removeSouls(soulCost); + player.playSound(player.getLocation(), Sound.EAT, 0.4F, 0.2F); + this.spellParticle.setLocation(player.getLocation()).display(player); + soulModeCache.updateSoulGem(); + + if (soulModeCache.getSouls() % 100 == 0) { + Language.SOUL_DRAIN_MESSAGE.send(player, s -> s.replace("{souls}", String.valueOf(soulModeCache.getSouls()))); + } + + if (soulModeCache.getSoulGemBuilder().getSouls() <= 0) { + player.playSound(player.getLocation(), Sound.FIRE_IGNITE, 1.0F, 1.2F); + soulModeCache.updateSoulGem(); + ranOutOfSouls.add(player); + } + } + + for (Player ranOutOfSoul : ranOutOfSouls) { + this.soulManager.disableSoulMode(ranOutOfSoul); + } + } +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/utils/CacheUtils.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/utils/CacheUtils.java new file mode 100644 index 0000000..9539e51 --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/utils/CacheUtils.java @@ -0,0 +1,110 @@ +package net.crankedpvp.crankedenchants.utils; + +import net.crankedpvp.crankedenchants.struct.cache.SoulTrackerCache; +import net.crankedpvp.crankedenchants.struct.cache.enchantscache.*; +import net.crankedpvp.crankedutils.utils.cache.CacheManager; +import org.bukkit.entity.Player; + +public final class CacheUtils { + + private CacheUtils() { + + } + + public static BleedStacksCache getBleedStackCache(Player player) { + BleedStacksCache bleedStacksCache = (BleedStacksCache) CacheManager.getInstance().getCachedPlayer(player).getCache("bleed_stacks"); + + if (bleedStacksCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new BleedStacksCache()); + + return (BleedStacksCache) CacheManager.getInstance().getCachedPlayer(player).getCache("bleed_stacks"); + } + + public static RageStacksCache getRageStackCache(Player player) { + RageStacksCache rageStacksCache = (RageStacksCache) CacheManager.getInstance().getCachedPlayer(player).getCache("rage_stacks"); + + if (rageStacksCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new RageStacksCache()); + + return (RageStacksCache) CacheManager.getInstance().getCachedPlayer(player).getCache("rage_stacks"); + } + + public static DiminishCache getDiminishLastAttackCache(Player player) { + DiminishCache bleedStacksCache = (DiminishCache) CacheManager.getInstance().getCachedPlayer(player).getCache("diminish_last_damage"); + + if (bleedStacksCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new DiminishCache()); + + return (DiminishCache) CacheManager.getInstance().getCachedPlayer(player).getCache("diminish_last_damage"); + } + + public static SilenceCache getSilenceCache(Player player) { + SilenceCache silenceCache = (SilenceCache) CacheManager.getInstance().getCachedPlayer(player).getCache("silence_effect"); + + if (silenceCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new SilenceCache()); + + return (SilenceCache) CacheManager.getInstance().getCachedPlayer(player).getCache("silence_effect"); + } + + public static DominateCache getDominateCache(Player player) { + DominateCache dominateCache = (DominateCache) CacheManager.getInstance().getCachedPlayer(player).getCache("dominate_proc_time"); + + if (dominateCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new DominateCache()); + + return (DominateCache) CacheManager.getInstance().getCachedPlayer(player).getCache("dominate_proc_time"); + } + + public static TeleblockCache getTeleblockCache(Player player) { + TeleblockCache teleblockCache = (TeleblockCache) CacheManager.getInstance().getCachedPlayer(player).getCache("teleblock"); + + if (teleblockCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new TeleblockCache()); + + return (TeleblockCache) CacheManager.getInstance().getCachedPlayer(player).getCache("teleblock"); + } + + public static NaturesWrathCache getNaturesWrathCache(Player player) { + NaturesWrathCache naturesWrathCache = (NaturesWrathCache) CacheManager.getInstance().getCachedPlayer(player).getCache("natures-wrath"); + + if (naturesWrathCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new NaturesWrathCache()); + + return (NaturesWrathCache) CacheManager.getInstance().getCachedPlayer(player).getCache("natures-wrath"); + } + + public static AbyssCache getAbyssCache(Player player) { + AbyssCache abyssCache = (AbyssCache) CacheManager.getInstance().getCachedPlayer(player).getCache("abyss"); + + if (abyssCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new AbyssCache()); + + return (AbyssCache) CacheManager.getInstance().getCachedPlayer(player).getCache("abyss"); + } + + public static DivineCache getDivineCache(Player player) { + DivineCache divineCache = (DivineCache) CacheManager.getInstance().getCachedPlayer(player).getCache("divine_proc_time"); + + if (divineCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new DivineCache()); + + return (DivineCache) CacheManager.getInstance().getCachedPlayer(player).getCache("divine_proc_time"); + } + + public static AntiGankCache getAntiGankCache(Player player) { + AntiGankCache antiGankCache = (AntiGankCache) CacheManager.getInstance().getCachedPlayer(player).getCache("anti_gank"); + + if (antiGankCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new AntiGankCache()); + + return (AntiGankCache) CacheManager.getInstance().getCachedPlayer(player).getCache("anti_gank"); + } + + public static AegisCache getAegisCache(Player player) { + AegisCache aegisCache = (AegisCache) CacheManager.getInstance().getCachedPlayer(player).getCache("aegis"); + + if (aegisCache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new AegisCache()); + + return (AegisCache) CacheManager.getInstance().getCachedPlayer(player).getCache("aegis"); + } + + public static SoulTrackerCache getSoulTrackerCache(Player player) { + SoulTrackerCache cache = (SoulTrackerCache) CacheManager.getInstance().getCachedPlayer(player).getCache("soul-tracker"); + + if (cache == null) CacheManager.getInstance().getCachedPlayer(player).registerCache(new SoulTrackerCache()); + + return (SoulTrackerCache) CacheManager.getInstance().getCachedPlayer(player).getCache("soul-tracker"); + } + +} diff --git a/Enchants/src/main/java/net/crankedpvp/crankedenchants/utils/DetonateUtils.java b/Enchants/src/main/java/net/crankedpvp/crankedenchants/utils/DetonateUtils.java new file mode 100644 index 0000000..364589b --- /dev/null +++ b/Enchants/src/main/java/net/crankedpvp/crankedenchants/utils/DetonateUtils.java @@ -0,0 +1,66 @@ +package net.crankedpvp.crankedenchants.utils; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import net.crankedpvp.crankedutils.utils.BlockUtil; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import java.util.List; + +public class DetonateUtils { + + + private static final Board board = Board.getInstance(); + private static final FPlayers fPlayers = FPlayers.getInstance(); + public static void trenchEffect(Block block, int r, Player p, List trenchBlackListedBlocks) { + int chunkX = block.getChunk().getX(); + int chunkZ = block.getChunk().getZ(); + Block target; + + final double borderRadius = block.getWorld().getWorldBorder().getSize() / 2; + final Faction playerFac = fPlayers.getByPlayer(p).getFaction(); + final World world = block.getWorld(); + final int startX = block.getX(); + final int startY = block.getY(); + final int startZ = block.getZ(); + + Faction facAtChunk; + boolean chunkSkip = false; + + for (int x = -r; x <= r; x++) { + for (int z = -r; z <= r; z++) { + if (chunkX != FLocation.blockToChunk(startX + x) || chunkZ != FLocation.blockToChunk(startZ + z)) { + chunkX = FLocation.blockToChunk(startX + x); + chunkZ = FLocation.blockToChunk(startZ + z); + + facAtChunk = board.getFactionAt(new FLocation(world.getName(), chunkX, chunkZ)); + chunkSkip = !facAtChunk.isWilderness() && !playerFac.equals(facAtChunk); + } + + if (chunkSkip) continue; + + if (Math.abs(getAccurateCoord(startX + x)) >= borderRadius || Math.abs(getAccurateCoord(startZ + z)) >= borderRadius) continue; + + for (int y = -r; y <= r; y++) { + if (startY + y < 0 || startY + y > 256) continue; + target = world.getBlockAt(startX + x,startY + y, startZ + z); + + Material type = target.getType(); + if (!trenchBlackListedBlocks.contains(type)) { + BlockUtil.setAir(world, startX + x, startY + y, startZ + z, false); + } + } + } + } + } + + private static double getAccurateCoord(double coord) { + if (coord < 0) return coord + 1.0; + return coord; + } +} diff --git a/Enchants/src/main/resources/language.yml b/Enchants/src/main/resources/language.yml new file mode 100644 index 0000000..f2dec16 --- /dev/null +++ b/Enchants/src/main/resources/language.yml @@ -0,0 +1,81 @@ +SOUL_MODE_ENABLE: + - "" + - "&a&l** SOUL MODE: &nON&r&a&l **" + - "&7Active soul enchantments will now drain soul gems." + - "" +SOUL_MODE_DISABLE: + - "" + - "&c&l** SOUL MODE: &nOFF&r&c&l **" + - "&7Soul enchantments will no longer drain soul gems." + - "" +OUT_OF_SOULS: "&c&l** OUT OF SOUL **" +CLICKED_WRONG_SOUL_GEM: "&d&lEnchants &8➥ &cThis Soul Gem is not currently active. (To disable Soul Mode, click the Soul Gem you used to enable it)." +SOUL_DRAIN_MESSAGE: "&e&l** SOULS: &n{souls}&e&l **" + +NE_COMMAND_HELP: + - "&8--- &4Cranked &cEnchantments &8---" + - "&4/ce &cenchant &7 [level]" + - "&4/ce &cunenchant &7" + - "&4/ce &cbook &7 [player]" + - "&4/ce &crbook &7 [player]" + - "&4/ce &csoulgem &7 [player]" + - "&4/ce &cblackscroll &7 [player]" + - "&4/ce &cwhitescroll &7 [player]" + - "&4/ce &cnametag &7 [player]" + - "&4/ce &ctransmogscroll &7 [player]" + - "&4/ce &crandomizationscroll &7 [player]" + - "&4/ce &csoultracker &7 [player]" + - "&4/ce &cdust &7 [player]" + - "&4/ce &cidust &7 [player]" + - "&4/ce &corb &7 [player]" + - "&4/ce &cgkit &7 [player]" + - "&4/ce &creload" + +INVALID_ENCHANTMENT_NAME: "&d&lEnchants &8➥ &cInvalid enchantment name." +INVALID_ENCHANTMENT_LEVEL: "&d&lEnchants &8➥ &cInvalid enchantment level (max level: {max})." +EMPTY_HAND: "&d&lEnchants &8➥ &cPlease hold an item in your hand." +ALREADY_HAS_ENCHANTMENT: "&d&lEnchants &8➥ &cThis item already has this enchantment with a higher level." +DOESNT_HAVE_ANY_ENCHANTMENTS: "&d&lEnchants &8➥ &cThis item doesn't have any enchantments." +ONLY_HAS_HEROIC_ENCHANTMENTS: "&d&lEnchants &8➥ &cYou cannot blackscroll heroic enchantments" +APPLY_HEROIC_MISSING_BASE_ENCHANT: "&d&lEnchants &8➥ &cYou need the {enchantment} enchantment to apply this heroic book." + +ADMIN_RELOADING: "&c&l(!) &7Reloading configs now..." +ADMIN_RELOADED: "&c&l(!) &7Reloaded configs and other cool stuff. Took &4%took%ms&7." + +EQUIP_POTION_ENCHANT: "&a&l[+]&a {enchant} {enchant-level}: &7applying {effect} {effect-level}" +UNEQUIP_POTION_ENCHANT: "&c&l[-]&c {enchant} {enchant-level}: &7removing {effect}" + +WEAK_SHOT: + - "&7Certain enchantments will &c&lNOT&7 proc on your victims" + - "&7unless your bow shot is charged at &c&lLEAST&7 75%" +INVALID_ITEM_TYPE_FOR_ENCHANT: "&d&lEnchants &8➥ &cInvalid item type, this enchantment is a &n{valid-type}&c enchantment." +NOT_ENOUGH_SLOTS: "&d&lEnchants &8➥ &cYou can only apply up to {slots} enchantments on this item." +ITEM_PROTECTED_BY_WHITE_SCROLL: "&d&lEnchants &8➥ &cYour item was not destroyed because it was protected by a while scroll." +RENAME_TAG_CLICKED: "&6&l(!) &6Type in chat to rename the item you are holding in your hand." +SUCCESSFULLY_RENAMED: "&6&l(!) &6You have successfully renamed your item to: {new-name}&6." +FULL_INVENTORY: "&d&lEnchants &8➥ &cWarning, you have a &lFULL&c inventory." + +BOOK_OPEN: + - "&e&l(!) &eYou examine the {book-type} Enchantment Book...&r" + - "&eand discover &l&n{book}&r&e!" +BOOK_RIGHT_CLICK: + - "&e&l(!) &eTo apply this enchantment to an item, simply drag n' drop the book onto the item you'd like to enchant in your inventory!" + - "&7The &bSuccess Rate&7 is the chance of the book successfully being applied to your equipment. The &bDestruction Chance&7 is the percent chance of your piece of equipment being &nDESTROYED&7 if the book fails to apply." + +KIT_RECEIVED: "&d&lEnchants &8➥&a You have received the &4{gkit}&c gkit." +KIT_COOLDOWN: "&d&lEnchants &8➥&c You have to wait another &4{time}&c." +KIT_INVALID_NAME: "&d&lEnchants &8➥&c Invalid gkit name." +KIT_NO_ACCESS: "&d&lEnchants &8➥&c You do not have access to this gkit." + +SOUL_TRACKER_APPLIED: "&e&l(!)&e You have applied a {soul-tracker} Soul Tracker&e to your {item}!" +ALREADY_HAS_SOUL_TRACKER: "&d&lEnchants &8➥&c This item already has a soul tracker applied to it." +DOESNT_HAVE_SOUL_TRACKER: "&d&lEnchants &8➥&c This item doesn't have a soul tracker applied to it." +SOUL_HARVEST_COOLDOWN: "&d&lEnchants &8➥&c You cannot collect {player}'s Soul for another {time}." + +REMOVE_EXP: "&c&l-{amount} EXP" +NOT_ENOUGH_EXP: "&d&lEnchants &8➥&c Not enough experience!" + +CANNOT_DUPE_ITEM: "&d&lEnchants &8➥ &cThis item cannot be duped." +CANNOT_DUPE_MORE: "&d&lEnchants &8➥ &cThis item is at the max stack size." +CANNOT_DUPE_TIER: "&d&lEnchants &8➥ &cThis tier of enchantment cannot be duped." +DUPED_ITEM: "&d&lEnchants &8➥ &aSuccessfully duplicated this item to a stack of 64." \ No newline at end of file diff --git a/Enchants/src/main/resources/plugin.yml b/Enchants/src/main/resources/plugin.yml new file mode 100644 index 0000000..dd32fac --- /dev/null +++ b/Enchants/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedEnchants +main: net.crankedpvp.crankedenchants.CrankedEnchants +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - Factions \ No newline at end of file diff --git a/Enchants/src/main/resources/settings.yml b/Enchants/src/main/resources/settings.yml new file mode 100644 index 0000000..39e1471 --- /dev/null +++ b/Enchants/src/main/resources/settings.yml @@ -0,0 +1,18 @@ +enchanter: + gui-rows: 1 + tier-items: + SIMPLE: + slot: 0 + price: 500 + UNIQUE: + slot: 1 + price: 1000 + ELITE: + slot: 2 + price: 2000 + ULTIMATE: + slot: 3 + price: 5000 + LEGENDARY: + slot: 4 + price: 20000 diff --git a/Envoys/pom.xml b/Envoys/pom.xml new file mode 100644 index 0000000..d839459 --- /dev/null +++ b/Envoys/pom.xml @@ -0,0 +1,41 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Envoys + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + LootTable + + + net.crankedpvp + Leaderboards + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/EnvoyPlugin.java b/Envoys/src/main/java/net/crankedpvp/envoys/EnvoyPlugin.java new file mode 100644 index 0000000..361f35f --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/EnvoyPlugin.java @@ -0,0 +1,75 @@ +package net.crankedpvp.envoys; + +import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.crankedutils.utils.serializer.location.LocationSerializerDeserializer; +import net.crankedpvp.envoys.commands.AdminEnvoyCommand; +import net.crankedpvp.envoys.commands.EnvoyCommand; +import net.crankedpvp.envoys.language.LanguageHandler; +import net.crankedpvp.envoys.listeners.AddCrateLocationListener; +import net.crankedpvp.envoys.listeners.EnvoySummonerListener; +import net.crankedpvp.envoys.listeners.OpenEnvoyCrateListener; +import net.crankedpvp.envoys.struct.EnvoyManager; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.concurrent.ThreadLocalRandom; + +public class EnvoyPlugin extends JavaPlugin { + + @Getter + private static EnvoyPlugin instance; + + @Getter + private EnvoyManager envoyManager; + + @Getter + private CommandManager commandManager; + + @Getter + private LanguageHandler languageHandler; + + + @Override + public void onEnable() { + instance = this; + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + this.registerListeners(this.getServer().getPluginManager()); + this.commandManager = new CommandManager(this); + this.commandManager.register(new EnvoyCommand(this)); + this.commandManager.register(new AdminEnvoyCommand(this)); + this.envoyManager = new EnvoyManager(this); + this.registerLocationsFromConfig(); + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> { + this.envoyManager.startEnvoyEvent(); + }, 20L * 60L * 30L, 20L * 60L * 20L); + HologramsAPI.registerPlaceholder(EnvoyPlugin.getInstance(), "{envoy_time}", 1, this.getEnvoyManager()); + + } + + private void registerListeners(PluginManager pluginManager) { + pluginManager.registerEvents(new AddCrateLocationListener(this), this); + pluginManager.registerEvents(new OpenEnvoyCrateListener(this), this); + pluginManager.registerEvents(new EnvoySummonerListener(this), this); + } + + + private void registerLocationsFromConfig() { + FileConfiguration yamlConfiguration = this.getConfig(); + if (yamlConfiguration.contains("locations")) { + for (String string : yamlConfiguration.getStringList("locations")) { + this.envoyManager.getLocations().add(LocationSerializerDeserializer.deserialize(string)); + } + } + } + + @Override + public void onDisable() { + this.envoyManager.handleCrateRemoving(); + this.envoyManager.setActive(false); + this.envoyManager.setRemainingCrates(0); + } +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/commands/AdminEnvoyCommand.java b/Envoys/src/main/java/net/crankedpvp/envoys/commands/AdminEnvoyCommand.java new file mode 100644 index 0000000..ab316fc --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/commands/AdminEnvoyCommand.java @@ -0,0 +1,124 @@ +package net.crankedpvp.envoys.commands; + +import com.gmail.filoghost.holographicdisplays.api.Hologram; +import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import com.gmail.filoghost.holographicdisplays.api.placeholder.PlaceholderReplacer; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CustomItemUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.envoys.EnvoyPlugin; +import net.crankedpvp.envoys.language.Language; +import net.crankedpvp.envoys.struct.EnvoyManager; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("aenvoy") +public class AdminEnvoyCommand extends CommandBase { + + private final EnvoyPlugin plugin; + public AdminEnvoyCommand(EnvoyPlugin plugin) { + this.plugin = plugin; + } + + @Default + @Permission("cranked.admin") + public void defaultCommand(CommandSender commandSender) { + sendHelpMessage(commandSender); + } + + @SubCommand("setup") + @Permission("cranked.admin") + public void setupCommand(final CommandSender commandSender) { + if(!(commandSender instanceof Player)) { + commandSender.sendMessage(CC.translate("&cYou must be a player to execute this command")); + return; + } + + final Player player = ((Player) commandSender); + final ItemBuilder itemBuilder = new ItemBuilder(Material.CHEST, "&b&lEnvoy Setup Chest", + "&7Place this down to set the blocks placed", + "&7location to a envoy location"); + player.getInventory().addItem(CustomItemUtils.setCrankedCustomItem(itemBuilder.colorize().build(), "envoySetupChest")); + player.sendMessage(CC.translate("&aYou have been given a crate to edit crate locations")); + } + + @SubCommand("reload") + @WrongUsage("&cUsage: /aenvoy reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + EnvoyPlugin.getInstance().getLanguageHandler().load(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } + + @SubCommand("summoner") + @Permission("cranked.admin") + public void summonerCommand(final CommandSender commandSender, @Optional @Completion("#players") Player player) { + if(player == null) player = (Player)commandSender; + ItemBuilder itemBuilder = new ItemBuilder(Material.TORCH, "&f&ki&r&e✦&f&ki&r &6&lEnvoy Summoner &f&ki&e✦&f&ki&r", + "&7Right-Click this summoner to", + "&7forcefully begin a envoy event", + "", + "&7The event will not start if", + "&7another envoy event is ongoing"); + itemBuilder.setGlowing(); + PlayerUtils.giveOrDropProtectedItem(player, CustomItemUtils.setCrankedCustomItem(itemBuilder.colorize().build(), "envoySummoner"), 15); + } + + @SubCommand("forcestart") + @Permission("cranked.admin") + public void forceStartCommand(final CommandSender commandSender) { + if(this.plugin.getEnvoyManager().isActive()) { + commandSender.sendMessage(CC.translate(EnvoyManager.prefix + "&cThere is already an active envoy event")); + SoundUtils.tryPlayErrorSound(commandSender); + return; + } + + /* + this.plugin.getServer().getOnlinePlayers() + .stream() + .filter(Objects::nonNull) //TODO filter people with envoy messages enabled + .forEach(player -> player.sendMessage(CC.translate(EnvoyManager.prefix + "&aAn envoy event has just started"))); + + */ + this.plugin.getEnvoyManager().startEnvoyEvent(); + } + + @SubCommand("forceend") + @Permission("cranked.admin") + public void forceEndCommand(final CommandSender commandSender) { + if(!this.plugin.getEnvoyManager().isActive()) { + commandSender.sendMessage(CC.translate(EnvoyManager.prefix + "&cThere is no ongoing envoy event")); + SoundUtils.tryPlayErrorSound(commandSender); + return; + } + + /* + this.plugin.getServer().getOnlinePlayers() + .stream() + .filter(Objects::nonNull) //TODO filter people with envoy messages enabled + .forEach(player -> player.sendMessage(CC.translate(EnvoyManager.prefix + "&cThe envoy event has ended"))); + + */ + this.plugin.getEnvoyManager().endEnvoyEvent(); + } + + + + private void sendHelpMessage(CommandSender commandSender) { + commandSender.sendMessage("/aenvoy forceend"); + commandSender.sendMessage("/aenvoy forcestart"); + commandSender.sendMessage("/aenvoy setup"); + commandSender.sendMessage("/aenvoy summoner"); + } + +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/commands/EnvoyCommand.java b/Envoys/src/main/java/net/crankedpvp/envoys/commands/EnvoyCommand.java new file mode 100644 index 0000000..d151e66 --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/commands/EnvoyCommand.java @@ -0,0 +1,38 @@ +package net.crankedpvp.envoys.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.envoys.EnvoyPlugin; +import net.crankedpvp.envoys.inventory.EnvoyInventory; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import static net.crankedpvp.envoys.struct.EnvoyManager.prefix; + +@Command("envoy") +public class EnvoyCommand extends CommandBase { + + private final EnvoyPlugin plugin; + public EnvoyCommand(EnvoyPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final CommandSender commandSender) { + if(commandSender instanceof Player) { + final Player player = (Player)commandSender; + final EnvoyInventory envoyInventory = new EnvoyInventory(); + envoyInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + } + + @SubCommand("time") + public void timeCommand(final CommandSender commandSender) { + commandSender.sendMessage(CC.translate(prefix + "&7The next envoy is in &f" + plugin.getEnvoyManager().formatedTimeUntilNextEnvoy() + "&7.")); + } +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/inventory/EnvoyInventory.java b/Envoys/src/main/java/net/crankedpvp/envoys/inventory/EnvoyInventory.java new file mode 100644 index 0000000..25eeaa8 --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/inventory/EnvoyInventory.java @@ -0,0 +1,81 @@ +package net.crankedpvp.envoys.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.envoys.EnvoyPlugin; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Arrays; + +public class EnvoyInventory { + private final Gui envoyInventory; + + public Gui getUI() { + return this.envoyInventory; + } + + public EnvoyInventory() { + this.envoyInventory = new Gui(GuiType.HOPPER, "Cranked Envoys"); + this.envoyInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.envoyInventory.setItem(1, new GuiItem(createInformationItem())); + this.envoyInventory.setItem(3, new GuiItem(createPreviewLootItem(), event -> { + event.getWhoClicked().closeInventory(); + LootPreviewInventory lootPreviewInventory = new LootPreviewInventory(); + lootPreviewInventory.getUI().open(event.getWhoClicked()); + })); + //this.envoyInventory.setItem(Arrays.asList(0, 4), new GuiItem(createExitItem(), event -> event.getWhoClicked().closeInventory())); + this.envoyInventory.setItem(Arrays.asList(2, 0, 4), new GuiItem(createFillerItem())); + + } + + private ItemStack createPreviewLootItem() { + final ItemBuilder itemBuilder = new ItemBuilder(Material.CHEST, "&c&lEnvoy Loot"); + itemBuilder.setLore(Arrays.asList("&7Click to view the contents of", + "&7the envoy event rewards")); + return itemBuilder.colorize().build(); + + } + + private ItemStack createInformationItem() { + final ItemBuilder itemBuilder = new ItemBuilder(Material.PAPER, "&e&lEnvoy Information"); + String active = EnvoyPlugin.getInstance().getEnvoyManager().isActive() ? "&a&lACTIVE" : "&c&lINACTIVE"; + itemBuilder.setLore(Arrays.asList( + "&7Envoys are &fpassive &7events where", + "&7players roam the &cwarzone &7to find", + "&7and destroy &fcrates&7, which are filled", + "&7with &euseful &7loot to begin your", + "&7journey.", + "", + "&7While searching for &eenvoy &7crates,", + "&7it is possible for you to be attacked", + "&7by &cenemy &7players who are also searching", + "&7for &eenvoy &7crates. Be aware, and &agood &7luck.", + "", + "&7Envoys occur every &f25-35 minutes", + "", + "&fEnvoy Status: " + active)); + return itemBuilder.colorize().build(); + } + + private ItemStack createExitItem() { + final ItemStack item = new ItemStack(Material.REDSTONE); + final ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cExit envoy inventory")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createFillerItem() { + final ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getWoolData()); + final ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/inventory/LootPreviewInventory.java b/Envoys/src/main/java/net/crankedpvp/envoys/inventory/LootPreviewInventory.java new file mode 100644 index 0000000..4cf3d4d --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/inventory/LootPreviewInventory.java @@ -0,0 +1,65 @@ +package net.crankedpvp.envoys.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Objects; + +public class LootPreviewInventory { + + private final PaginatedGui envoyLootPreviewInventory; + + public PaginatedGui getUI() { + return this.envoyLootPreviewInventory; + } + + + public LootPreviewInventory() { + + this.envoyLootPreviewInventory = new PaginatedGui(6, 28, "Envoy Loot"); + this.envoyLootPreviewInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.envoyLootPreviewInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + ItemStack prevPage = new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.").colorize().build(); + ItemStack nextPage = new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.").colorize().build(); + this.envoyLootPreviewInventory.setItem(6, 1, new GuiItem(prevPage, event -> { + this.envoyLootPreviewInventory.previous(); + event.setCancelled(true); + })); + this.envoyLootPreviewInventory.setItem(6, 9, new GuiItem(nextPage, event -> { + this.envoyLootPreviewInventory.next(); + event.setCancelled(true); + })); + + + this.envoyLootPreviewInventory.updateItem(6, 5, new GuiItem(new ItemBuilder(Material.BED, "&cReturn to Slot Bot").colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + EnvoyInventory envoyInventory = new EnvoyInventory(); + envoyInventory.getUI().open(event.getWhoClicked()); + })); + + + LootTableAPI.getAllLootFromLootTable(LootTableType.ENVOY).stream() + .filter(Objects::nonNull) + .filter(ItemStack::hasItemMeta) + .forEach(itemStack -> this.envoyLootPreviewInventory.addItem(new GuiItem(itemStack, event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) event.getWhoClicked().getInventory().addItem(itemStack); + }))); + ; + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/language/Language.java b/Envoys/src/main/java/net/crankedpvp/envoys/language/Language.java new file mode 100644 index 0000000..1bf5007 --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/language/Language.java @@ -0,0 +1,99 @@ +package net.crankedpvp.envoys.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + ENVOY_STARTED, + ADMIN_RELOADING, + ADMIN_RELOADED, + + + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/language/LanguageHandler.java b/Envoys/src/main/java/net/crankedpvp/envoys/language/LanguageHandler.java new file mode 100644 index 0000000..851e647 --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.envoys.language; + +import net.crankedpvp.envoys.EnvoyPlugin; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final EnvoyPlugin plugin; + + public LanguageHandler(EnvoyPlugin plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/listeners/AddCrateLocationListener.java b/Envoys/src/main/java/net/crankedpvp/envoys/listeners/AddCrateLocationListener.java new file mode 100644 index 0000000..a9c3682 --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/listeners/AddCrateLocationListener.java @@ -0,0 +1,48 @@ +package net.crankedpvp.envoys.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CustomItemUtils; +import net.crankedpvp.crankedutils.utils.serializer.location.LocationSerializerDeserializer; +import net.crankedpvp.envoys.EnvoyPlugin; +import net.crankedpvp.envoys.struct.EnvoyManager; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; + +import java.util.ArrayList; +import java.util.List; + +public class AddCrateLocationListener implements Listener { + + private final EnvoyPlugin plugin; + public AddCrateLocationListener(EnvoyPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void placeCrateEvent(final BlockPlaceEvent event) { + if(event.getItemInHand() == null || event.getItemInHand().getType() != Material.CHEST) return; + if(!CustomItemUtils.getCrankedCustomItem(event.getItemInHand()).equals("envoySetupChest")) return; + event.setCancelled(true); + Player player = event.getPlayer(); + Location location = event.getBlockPlaced().getLocation(); + this.plugin.getEnvoyManager().getLocations().add(location); + player.sendMessage(CC.translate(EnvoyManager.prefix + "&aAdded crate location at: &7" + LocationSerializerDeserializer.serialize(location))); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + + + FileConfiguration yamlConfiguration = this.plugin.getConfig(); + List serializedLocations = new ArrayList<>(); + String base64Location = LocationSerializerDeserializer.serialize(location); + if(yamlConfiguration.contains("locations")) serializedLocations.addAll(yamlConfiguration.getStringList("locations")); + serializedLocations.add(base64Location); + yamlConfiguration.set("locations", serializedLocations); + this.plugin.saveConfig(); + } + +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/listeners/EnvoySummonerListener.java b/Envoys/src/main/java/net/crankedpvp/envoys/listeners/EnvoySummonerListener.java new file mode 100644 index 0000000..3366e7c --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/listeners/EnvoySummonerListener.java @@ -0,0 +1,38 @@ +package net.crankedpvp.envoys.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CustomItemUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.envoys.EnvoyPlugin; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class EnvoySummonerListener implements Listener { + + private final EnvoyPlugin plugin; + public EnvoySummonerListener(EnvoyPlugin envoyPlugin) { + this.plugin = envoyPlugin; + } + + @EventHandler + public void useItem(PlayerInteractEvent event) { + if(event.getPlayer() == null) return; + if(event.getPlayer().getItemInHand() == null) return; + ItemStack itemStack = event.getPlayer().getItemInHand(); + if(!CustomItemUtils.isCrankedCustomItem(itemStack)) return; + if(!CustomItemUtils.getCrankedCustomItem(itemStack).equals("envoySummoner")) return; + if(!this.plugin.getEnvoyManager().isActive() || this.plugin.getEnvoyManager().canSpawnEnvoy()) { + event.getPlayer().setItemInHand(ItemUtils.decreaseItemStackAmountByOne(itemStack)); + this.plugin.getEnvoyManager().startEnvoyEvent(); + return; + } + + event.setCancelled(true); + event.getPlayer().sendMessage(CC.translate("&c&l(!) &cThere is already an active envoy event")); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + + } +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/listeners/OpenEnvoyCrateListener.java b/Envoys/src/main/java/net/crankedpvp/envoys/listeners/OpenEnvoyCrateListener.java new file mode 100644 index 0000000..394c85d --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/listeners/OpenEnvoyCrateListener.java @@ -0,0 +1,44 @@ +package net.crankedpvp.envoys.listeners; + +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.envoys.EnvoyPlugin; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class OpenEnvoyCrateListener implements Listener { + + private final EnvoyPlugin plugin; + public OpenEnvoyCrateListener(EnvoyPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void openEnvoyCrate(PlayerInteractEvent event) { + if(event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if(event.getClickedBlock().getType() != Material.CHEST) return; + Location clickedBlockLocation = event.getClickedBlock().getLocation(); + if(!this.plugin.getEnvoyManager().isActive() || !this.plugin.getEnvoyManager().getCurrentChests().contains(clickedBlockLocation)) return; + event.setCancelled(true); + this.plugin.getEnvoyManager().removeCrateAt(clickedBlockLocation); + this.plugin.getEnvoyManager().setRemainingCrates(this.plugin.getEnvoyManager().getRemainingCrates() - 1); + Player player = event.getPlayer(); + player.playSound(player.getLocation(), Sound.FIZZ, 2.0F, 2.0F); + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).incrementEnvoysOpened(); + PlayerUtils.dropProtectedItem(player, clickedBlockLocation, LootTableAPI.getRandomLootItem(LootTableType.ENVOY), 15); + PlayerUtils.dropProtectedItem(player, clickedBlockLocation, LootTableAPI.getRandomLootItem(LootTableType.ENVOY), 15); + PlayerUtils.dropProtectedItem(player, clickedBlockLocation, LootTableAPI.getRandomLootItem(LootTableType.ENVOY), 15); + if(this.plugin.getEnvoyManager().getRemainingCrates() <= 0) { + this.plugin.getEnvoyManager().endEnvoyEvent(); + } + + } +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/struct/EnvoyManager.java b/Envoys/src/main/java/net/crankedpvp/envoys/struct/EnvoyManager.java new file mode 100644 index 0000000..6718551 --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/struct/EnvoyManager.java @@ -0,0 +1,170 @@ +package net.crankedpvp.envoys.struct; + +import com.gmail.filoghost.holographicdisplays.api.placeholder.PlaceholderReplacer; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.BlockUtil; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.envoys.EnvoyPlugin; +import net.crankedpvp.envoys.language.Language; +import net.crankedpvp.envoys.tasks.FireworkTask; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.meta.FireworkMeta; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +public class EnvoyManager implements PlaceholderReplacer { + + public static String prefix = "&d&lEnvoys &8➥ "; + + private final EnvoyPlugin plugin; + + @Getter + private long lastEnvoyTime; + + @Getter @Setter + private int remainingCrates = 0; + + @Getter @Setter + private boolean active; + + private FireworkTask fireworkTask; + + @Getter @Setter + private List locations = new ArrayList<>(); + + @Getter @Setter + private List currentChests = new ArrayList<>(); + + public EnvoyManager(EnvoyPlugin plugin) { + this.plugin = plugin; + this.active = false; + this.updateLastEnvoyTime(); + } + + public void handleCrateSpawning() { + List availableLocations = this.locations.stream() + .filter(Objects::nonNull) + .filter(location -> location.getWorld() != null) + .map(location -> location.getBlock().getLocation()) + .filter(location -> location.getBlock().getType() == Material.AIR) + .distinct() + .collect(Collectors.toList()); + this.currentChests.clear(); + this.remainingCrates = 0; + int crates = Bukkit.getOnlinePlayers().size() > 15 ? Bukkit.getOnlinePlayers().size() / 3 : 7; + int cratesToSpawn = Math.min(crates, availableLocations.size()); + for (int i = 0; i < cratesToSpawn; i++) { + Location crateLocation = availableLocations.remove(ThreadLocalRandom.current().nextInt(availableLocations.size())); + BlockUtil.setBlockFast(crateLocation.getBlock(), Material.CHEST.getId(), (byte) 0, false); + this.currentChests.add(crateLocation); + this.remainingCrates++; + ArmorStand armorStand = (ArmorStand) crateLocation.getWorld().spawnEntity(crateLocation.clone().add(0.5D, 0.1D, 0.5D), EntityType.ARMOR_STAND); + armorStand.setCustomName(CC.translate("&6✧ &e&lEnvoy Crate &6✧")); + armorStand.setCustomNameVisible(true); + armorStand.setGravity(false); + armorStand.setVisible(false); + armorStand.setSmall(true); + Firework firework = crateLocation.getWorld().spawn(crateLocation.clone().add(0.5D, 0.0D, 0.5D), Firework.class); + FireworkMeta fireworkMeta = firework.getFireworkMeta(); + fireworkMeta.addEffect(FireworkEffect.builder().withColor(Color.YELLOW).withFade(Color.WHITE) + .with(FireworkEffect.Type.BALL_LARGE).flicker(true).withTrail().build()); + firework.setFireworkMeta(fireworkMeta); + fireworkMeta.setPower(5); + Bukkit.getScheduler().runTaskLater(EnvoyPlugin.getInstance(), firework::detonate, 20L); + } + if (this.remainingCrates == 0) return; + this.fireworkTask = new FireworkTask(); + fireworkTask.runTaskTimer(plugin, 0, 5*20); + } + + public void handleCrateRemoving() { + new ArrayList<>(this.currentChests).stream() + .filter(location -> location.getBlock().getType() == Material.CHEST) + .forEach(this::removeCrateAt); + this.currentChests.clear(); + } + + public void removeCrateAt(Location location) { + //location.getBlock().setType(Material.AIR); + BlockUtil.setAir(location.getBlock(), false); + removeNearbyHologram(location); + this.currentChests.remove(location); + } + + public void removeNearbyHologram(Location location) { + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.3D, 0.6D, 0.3D)) { + if (!(entity instanceof ArmorStand)) + continue; + entity.remove(); + } + } + + public void endEnvoyEvent() { + this.setActive(false); + this.plugin.getServer().getOnlinePlayers() + .stream() + .filter(Objects::nonNull) //TODO filter people with envoy messages enabled + .forEach(player -> player.sendMessage(CC.translate(EnvoyManager.prefix + "&cThe previous envoy event has ended"))); + this.handleCrateRemoving(); + this.remainingCrates = 0; + if (this.fireworkTask != null) { + this.fireworkTask.cancel(); + this.fireworkTask = null; + } + //this.plugin.getServer().getScheduler().runTaskLater(this.plugin, this::startEnvoyEvent, 20L * 60 * ThreadLocalRandom.current().nextInt(25, 35)); + } + + public void startEnvoyEvent() { + if(this.isActive()) { + System.out.println("[Envoy] Stopping previous envoy to start a new one"); + endEnvoyEvent(); + } + + this.handleCrateSpawning(); + if (this.remainingCrates == 0) { + this.plugin.getLogger().warning("Cannot start envoy: no configured crate locations are available in loaded worlds with air blocks"); + return; + } + this.updateLastEnvoyTime(); + this.setActive(true); + this.plugin.getServer().getOnlinePlayers() + .stream() + .filter(Objects::nonNull) //TODO filter people with envoy messages enabled + .forEach(player -> sendEnvoyStartMessage(player, this.remainingCrates)); + } + + private void sendEnvoyStartMessage(Player player, int chests) { + for (String line : Language.ENVOY_STARTED.getValuesAsList()) { + line = line.replace("{chests}", String.valueOf(chests)); + player.sendMessage(CC.translate(line)); + } + } + + public boolean canSpawnEnvoy() { + return (this.getLastEnvoyTime() + (300 * 1000)) < System.currentTimeMillis(); + } + + public long secondsUntilNextEnvoy() { + return (this.getLastEnvoyTime() + (1000 * 60 * 30) - System.currentTimeMillis()) / 1000; + } + + public String formatedTimeUntilNextEnvoy() { + return TimeUtils.formatSeconds(this.secondsUntilNextEnvoy()); + } + + public void updateLastEnvoyTime() { + this.lastEnvoyTime = System.currentTimeMillis(); + } + + @Override + public String update() { + return formatedTimeUntilNextEnvoy(); + } +} diff --git a/Envoys/src/main/java/net/crankedpvp/envoys/tasks/FireworkTask.java b/Envoys/src/main/java/net/crankedpvp/envoys/tasks/FireworkTask.java new file mode 100644 index 0000000..ae4d1c6 --- /dev/null +++ b/Envoys/src/main/java/net/crankedpvp/envoys/tasks/FireworkTask.java @@ -0,0 +1,30 @@ +package net.crankedpvp.envoys.tasks; + +import net.crankedpvp.envoys.EnvoyPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.entity.Firework; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.List; + +public class FireworkTask extends BukkitRunnable { + + @Override + public void run() { + for (int i = 0; i < EnvoyPlugin.getInstance().getEnvoyManager().getCurrentChests().size(); i++) { + + Location location = EnvoyPlugin.getInstance().getEnvoyManager().getCurrentChests().get(i); + Firework firework = location.getWorld().spawn(location.clone().add(0.5D, 0.0D, 0.5D), Firework.class); + FireworkMeta fireworkMeta = firework.getFireworkMeta(); + fireworkMeta.addEffect(FireworkEffect.builder().withColor(Color.YELLOW).withFade(Color.WHITE) + .with(FireworkEffect.Type.BALL_LARGE).flicker(true).withTrail().build()); + firework.setFireworkMeta(fireworkMeta); + fireworkMeta.setPower(5); + Bukkit.getScheduler().runTaskLater(EnvoyPlugin.getInstance(), firework::detonate, 20L); + } + } +} diff --git a/Envoys/src/main/resources/language.yml b/Envoys/src/main/resources/language.yml new file mode 100644 index 0000000..1545b26 --- /dev/null +++ b/Envoys/src/main/resources/language.yml @@ -0,0 +1,8 @@ +ADMIN_RELOADING: "&a&lEnvoy &8➥ &7Reloading configs now..." +ADMIN_RELOADED: "&a&lEnvoy &8➥ &7Reloaded configs and other cool stuff. Took &d%took%ms&7." +ENVOY_STARTED: + - "" + - "&6&l*** &e&lAN ENVOY EVENT HAS JUST STARTED &6&l***" + - "&7&o(( A total of &f&n{chests}&r &7&ohave been spawned around the /spawn warzone! ))" + - "" + diff --git a/Envoys/src/main/resources/plugin.yml b/Envoys/src/main/resources/plugin.yml new file mode 100644 index 0000000..75c4dac --- /dev/null +++ b/Envoys/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedEnvoys +main: net.crankedpvp.envoys.EnvoyPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + diff --git a/Events/pom.xml b/Events/pom.xml new file mode 100644 index 0000000..eba7b49 --- /dev/null +++ b/Events/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + + ProjectCranked + net.crankedpvp + 1.0 + + + Events + + + 8 + 8 + + + + + codemc-repo + https://repo.codemc.io/repository/maven-public/ + + + aikar + https://repo.aikar.co/content/groups/aikar/ + + + + + + com.gmail.filoghost.holographicdisplays + holographicdisplays-api + 2.4.0 + provided + + + net.astropvp + FactionsKore + 0.1 + system + ${project.basedir}/../.lib/FactionsKore-1.3.431.jar + + + net.crankedpvp + Utils + + + net.crankedpvp + DeadMansChest + + + com.massivecraft + Factions + + + net.crankedpvp + PvPTop + + + net.crankedpvp + Bosses + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + diff --git a/Events/src/main/java/net/crankedpvp/events/EventsPlugin.java b/Events/src/main/java/net/crankedpvp/events/EventsPlugin.java new file mode 100644 index 0000000..f4440c1 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/EventsPlugin.java @@ -0,0 +1,204 @@ +package net.crankedpvp.events; + +import com.massivecraft.factions.Factions; +import lombok.Getter; +import me.mattstudios.mf.base.CommandBase; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.events.commands.*; +import net.crankedpvp.events.game.MiniGameManager; +import net.crankedpvp.events.game.MiniGameRegister; +import net.crankedpvp.events.inventories.CerberusInventory; +import net.crankedpvp.events.inventories.CitadelInventory; +import net.crankedpvp.events.inventories.EventsInventory; +import net.crankedpvp.events.inventories.WarpKothInventory; +import net.crankedpvp.events.listeners.CerberusDeathListener; +import net.crankedpvp.events.listeners.KothStateChangeListener; +import net.crankedpvp.events.listeners.PlayerDeathListener; +import net.crankedpvp.events.listeners.PlayerTeleportListener; +import net.crankedpvp.events.managers.CerberusManager; +import net.crankedpvp.events.managers.CitadelManager; +import net.crankedpvp.events.managers.WarpKothManager; +import net.crankedpvp.events.tasks.UpdateNextCerberusTimerTask; +import net.crankedpvp.events.tasks.UpdateNextCitadelTimerTask; +import net.crankedpvp.events.tasks.UpdateNextWarpKothTimerTask; +import net.crankedpvp.events.utils.configuration.ConfigManager; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Arrays; +import java.util.Calendar; +import java.util.List; +import java.util.TimeZone; + +@Getter +public class EventsPlugin extends JavaPlugin { + + public final static String WARP_KOTH_WORLD_NAME = "world_the_end"; + + @Getter + private static EventsPlugin instance; + + private ConfigManager configManager; + private MiniGameRegister miniGameRegister; + private MiniGameManager miniGameManager; + private CommandManager commandManager; + private List commands; + + private EventsInventory eventsInventory; + + private WarpKothInventory warpKothInventory; + private CitadelInventory citadelInventory; + private CerberusInventory cerberusInventory; + + private CitadelManager citadelManager; + private WarpKothManager warpKothManager; + private CerberusManager cerberusManager; + + @Override + public void onEnable() { + instance = this; + + saveDefaultConfig(); + + this.configManager = new ConfigManager(this); + this.configManager.setupFiles(); + + this.miniGameRegister = new MiniGameRegister(this); + this.miniGameRegister.initialize(); + + this.commandManager = new CommandManager(this); + + this.miniGameManager = new MiniGameManager(this); +// this.miniGameManager.startAutoMiniGameTask(); + + this.registerCommands(); + this.registerListeners(); + + this.setupSavagesEvents(); + + } + + private void setupSavagesEvents() { + + this.citadelManager = new CitadelManager(this); + this.warpKothManager = new WarpKothManager(this); + this.cerberusManager = new CerberusManager(this); + + this.citadelInventory = new CitadelInventory(this); + this.warpKothInventory = new WarpKothInventory(this); + this.cerberusInventory = new CerberusInventory(this); + + this.eventsInventory = new EventsInventory(this); + + this.citadelManager.setLastFactionCaptured(Factions.getInstance().getFactionById(this.getConfig().getString("CITADEL_LAST_WON"))); + this.warpKothManager.setLastFactionCaptured(Factions.getInstance().getFactionById(this.getConfig().getString("WARP_KOTH_LAST_WON"))); + this.cerberusManager.setLastFactionCaptured(Factions.getInstance().getFactionById(this.getConfig().getString("CERBERUS_LAST_WON"))); + + new UpdateNextCitadelTimerTask(this).runTaskTimer(this, 40L, 20L); + new UpdateNextWarpKothTimerTask(this).runTaskTimer(this, 40L, 20L); + new UpdateNextCerberusTimerTask(this).runTaskTimer(this, 40L, 20L); + + } + + @Override + public void onDisable() { + instance = null; + this.getMiniGameRegister().unregisterAll(); + + this.getConfig().set("CITADEL_LAST_WON", this.citadelManager.getLastFactionCaptured().getId()); + this.getConfig().set("WARP_KOTH_LAST_WON", this.warpKothManager.getLastFactionCaptured().getId()); + this.getConfig().set("CERBERUS_LAST_WON", this.cerberusManager.getLastFactionCaptured().getId()); + this.saveConfig(); + } + + private void registerCommands() { + this.initNewCommands(); + this.commands.forEach(command -> this.commandManager.register(command)); + } + + public void initNewCommands() { + this.commands = Arrays.asList( + new AdminEventsCommand(this), + new ParkourEventCommand(this), + new SumoEventCommand(this), + new EventsCommand(this), + new CitadelCommand(this), + new WarpKothCommand(this), + new CerberusCommand(this) + ); + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new KothStateChangeListener(this), this); + pluginManager.registerEvents(new PlayerDeathListener(this), this); + pluginManager.registerEvents(new PlayerTeleportListener(this), this); + pluginManager.registerEvents(new CerberusDeathListener(this), this); + } + + + public long getTimeUntilNextCitadel() { + return (getNextCitadel() - System.currentTimeMillis()) - 1000; + } + + public long getTimeUntilNextWarpKoth() { + return (getNextWarpKoth() - System.currentTimeMillis()) - 1000; + } + + public long getTimeUntilNextCerberus() { + return (getNextCerberus() - System.currentTimeMillis()) - 1000; + } + + private long getNextCitadel() { + Calendar nextCitadel = Calendar.getInstance(TimeZone.getTimeZone("America/New_York")); + nextCitadel.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); + nextCitadel.set(Calendar.HOUR_OF_DAY, 16); + Calendar now = Calendar.getInstance(TimeZone.getTimeZone("America/New_York")); + if((now.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && now.get(Calendar.HOUR_OF_DAY) > 16)) { + nextCitadel.add(Calendar.DAY_OF_WEEK, 7); + } + nextCitadel.set(Calendar.MINUTE, 0); + nextCitadel.set(Calendar.SECOND, 0); + return nextCitadel.getTimeInMillis(); + } + + private long getNextWarpKoth() { + Calendar nextCitadel = Calendar.getInstance(TimeZone.getTimeZone("America/New_York")); + nextCitadel.set(Calendar.MINUTE, 0); + nextCitadel.set(Calendar.SECOND, 0); + + Calendar current = Calendar.getInstance(TimeZone.getTimeZone("America/New_York")); + if(current.get(Calendar.HOUR_OF_DAY) < 6) { + nextCitadel.set(Calendar.HOUR_OF_DAY, 6); + } else if(current.get(Calendar.HOUR_OF_DAY) < 12) { + nextCitadel.set(Calendar.HOUR_OF_DAY, 12); + } else if(current.get(Calendar.HOUR_OF_DAY) < 18) { + nextCitadel.set(Calendar.HOUR_OF_DAY, 18); + } else { + nextCitadel.add(Calendar.DAY_OF_MONTH, 1); + nextCitadel.set(Calendar.HOUR_OF_DAY, 0); + } + return nextCitadel.getTimeInMillis(); + } + + private long getNextCerberus() { + Calendar nextCerberus = Calendar.getInstance(TimeZone.getTimeZone("America/New_York")); + nextCerberus.set(Calendar.MINUTE, 0); + nextCerberus.set(Calendar.SECOND, 0); + + Calendar current = Calendar.getInstance(TimeZone.getTimeZone("America/New_York")); + if(current.get(Calendar.HOUR_OF_DAY) < 3) { + nextCerberus.set(Calendar.HOUR_OF_DAY, 3); + } else if(current.get(Calendar.HOUR_OF_DAY) < 9) { + nextCerberus.set(Calendar.HOUR_OF_DAY, 9); + } else if(current.get(Calendar.HOUR_OF_DAY) < 15) { + nextCerberus.set(Calendar.HOUR_OF_DAY, 15); + } else if(current.get(Calendar.HOUR_OF_DAY) <= 21) { + nextCerberus.set(Calendar.HOUR_OF_DAY, 21); + } else { + nextCerberus.set(Calendar.HOUR_OF_DAY, 21); + return ( nextCerberus.getTimeInMillis() + (21600*1000)); + } + return nextCerberus.getTimeInMillis(); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/commands/AdminEventsCommand.java b/Events/src/main/java/net/crankedpvp/events/commands/AdminEventsCommand.java new file mode 100644 index 0000000..ef03c8c --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/commands/AdminEventsCommand.java @@ -0,0 +1,123 @@ +package net.crankedpvp.events.commands; + + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.MiniGame; +import net.crankedpvp.events.game.MiniGameRegister; +import net.crankedpvp.events.game.MiniGameType; +import net.crankedpvp.events.utils.Utils; +import net.crankedpvp.events.utils.configuration.ConfigManager; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +@Command("aevent") +@Alias({"aevents", "adminevent", "adminevents"}) +public class AdminEventsCommand extends CommandBase { + + private final MiniGameRegister miniGameRegister; + private final ConfigManager languageFile; + private final EventsPlugin plugin; + + public AdminEventsCommand(EventsPlugin plugin) { + this.plugin = plugin; + this.miniGameRegister = plugin.getMiniGameRegister(); + this.languageFile = plugin.getConfigManager(); + } + + @SubCommand("start") + @Permission("cranked.admin") + public void startEvent(CommandSender sender, String eventName) { + if (Arrays.stream(MiniGameType.values()).noneMatch(miniGameType -> miniGameType.name().equals(eventName.toUpperCase(Locale.ROOT)))) { + sender.sendMessage(Utils.color(languageFile.getConfig(ConfigManager.ConfigFile.LANGUAGE).getString("messages.invalid-event-name"))); + return; + } + + MiniGameType miniGameType = MiniGameType.valueOf(eventName.toUpperCase(Locale.ROOT)); + MiniGame miniGame = this.miniGameRegister.getMiniGame(miniGameType); + if (miniGame == null) { + sender.sendMessage(Utils.color("&cThat event is unavailable because its world is not loaded.")); + return; + } + miniGame.startMiniGameCountDown(); + } + + @SubCommand("stop") + @Permission("cranked.admin") + public void stopEvent(CommandSender sender, String eventName) { + if (Arrays.stream(MiniGameType.values()).noneMatch(miniGameType -> miniGameType.name().equals(eventName.toUpperCase(Locale.ROOT)))) { + sender.sendMessage(Utils.color(languageFile.getConfig(ConfigManager.ConfigFile.LANGUAGE).getString("messages.invalid-event-name"))); + return; + } + + MiniGameType miniGameType = MiniGameType.valueOf(eventName.toUpperCase(Locale.ROOT)); + MiniGame miniGame = miniGameRegister.getMiniGame(miniGameType); + if (miniGame == null) { + sender.sendMessage(Utils.color("&cThat event is unavailable because its world is not loaded.")); + return; + } + miniGame.stopMiniGame(); + } + + @SubCommand("list") + @Permission("cranked.admin") + public void listEvent(CommandSender sender) { + sender.sendMessage(Utils.color(languageFile.getConfig(ConfigManager.ConfigFile.LANGUAGE).getString("messages.event.list-header"))); + + Arrays.stream(MiniGameType.values()).forEach(game -> { + sender.sendMessage(Utils.color(languageFile.getConfig(ConfigManager.ConfigFile.LANGUAGE).getString("messages.event.list-format").replace("{event}", Utils.toNiceString(game.name())))); + }); + } + + @SubCommand("info") + @Permission("cranked.admin") + public void eventInformation(CommandSender sender, String eventName) { + if (Arrays.stream(MiniGameType.values()).noneMatch(miniGameType -> miniGameType.name().equals(eventName.toUpperCase(Locale.ROOT)))) { + sender.sendMessage(Utils.color(languageFile.getConfig(ConfigManager.ConfigFile.LANGUAGE).getString("messages.invalid-event-name"))); + return; + } + + MiniGameType miniGameType = MiniGameType.valueOf(eventName.toUpperCase(Locale.ROOT)); + MiniGame miniGame = miniGameRegister.getMiniGame(miniGameType); + if (miniGame == null) { + sender.sendMessage(Utils.color("&cThat event is unavailable because its world is not loaded.")); + return; + } + Location spawnLocation = miniGame.getSpawnLocation(); + sender.sendMessage(Utils.color( + "\n" + + "&a* &7Minigame &8- &a" + Utils.toNiceString(miniGameType.name()) + "\n" + + "&a* &7World name: &a" + miniGame.getGameWorld().getName() + "\n" + + "&a* &7Spawn location: &7X: &a" + spawnLocation.getX() + " &7Y: &a" + spawnLocation.getY() + " &7Z: &a" + spawnLocation.getZ() + "\n" + + "&a* &7Event state: &a" + Utils.toNiceString(miniGame.getMiniGameState().name()) + "\n" + + "&a* &7Min/Max players: &a" + miniGame.getMinPlayers() + "&8/&a" + miniGame.getMaxPlayers() + "\n" + + "&a* &7Amount of participants: &a" + miniGame.getParticipants().size() + "\n" + )); + } + + @SubCommand("reload") + @Permission("cranked.admin") + public void reloadEvent(CommandSender sender) { + this.plugin.getConfigManager().reloadFiles(); + this.miniGameRegister.reloadMiniGames(); + /*this.plugin.getCommands().forEach(baseCommand -> this.plugin.getCommandManager().(baseCommand)); + this.plugin.initNewCommands(); + this.plugin.getCommands().forEach(baseCommand -> this.plugin.getCommandManager().registerCommand(baseCommand));*/ + sender.sendMessage(Utils.color("&aReload Successful")); + sender.sendMessage(Utils.color("&cWarning: &7Reloading the events will interrupt any ongoing events")); + } + + @Default + @Permission("cranked.admin") + public void doHelp(CommandSender sender) { + List helpMessageList = languageFile.getConfig(ConfigManager.ConfigFile.LANGUAGE).getStringList("messages.events-help-message"); + String[] helpMessage = new String[helpMessageList.size()]; + helpMessage = Utils.color(helpMessageList.toArray(helpMessage)); + sender.sendMessage(helpMessage); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/commands/CerberusCommand.java b/Events/src/main/java/net/crankedpvp/events/commands/CerberusCommand.java new file mode 100644 index 0000000..33f7553 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/commands/CerberusCommand.java @@ -0,0 +1,30 @@ +package net.crankedpvp.events.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.events.EventsPlugin; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("cerberus") +public class CerberusCommand extends CommandBase { + + private final EventsPlugin plugin; + public CerberusCommand(EventsPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getCerberusInventory().getUI().open(player); + } + + @SubCommand("start") + @Permission("events.start") + public void startCommand(final CommandSender commandSender) { + this.plugin.getCerberusManager().startEvent(); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/commands/CitadelCommand.java b/Events/src/main/java/net/crankedpvp/events/commands/CitadelCommand.java new file mode 100644 index 0000000..8d35f63 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/commands/CitadelCommand.java @@ -0,0 +1,30 @@ +package net.crankedpvp.events.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.events.EventsPlugin; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("citadel") +public class CitadelCommand extends CommandBase { + + private final EventsPlugin plugin; + public CitadelCommand(EventsPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getCitadelInventory().getUI().open(player); + } + + @SubCommand("start") + @Permission("events.start") + public void startCommand(final CommandSender commandSender) { + this.plugin.getCitadelManager().startEvent(); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/commands/EventsCommand.java b/Events/src/main/java/net/crankedpvp/events/commands/EventsCommand.java new file mode 100644 index 0000000..940f746 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/commands/EventsCommand.java @@ -0,0 +1,31 @@ +package net.crankedpvp.events.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.inventories.MainEventsUI; +import org.bukkit.entity.Player; + +@Command("event") +@Alias("events") +public class EventsCommand extends CommandBase { + + private final EventsPlugin plugin; + + public EventsCommand(EventsPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void baseCommand(Player sender) { + this.plugin.getEventsInventory().getNewEventsUI().open(sender); + /* + MainEventsUI mainEventsUI = new MainEventsUI(plugin, sender); + mainEventsUI.getEventsUI().open(sender); + + */ + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/commands/ParkourEventCommand.java b/Events/src/main/java/net/crankedpvp/events/commands/ParkourEventCommand.java new file mode 100644 index 0000000..23a8b58 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/commands/ParkourEventCommand.java @@ -0,0 +1,110 @@ +package net.crankedpvp.events.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.MiniGameRegister; +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.MiniGameType; +import net.crankedpvp.events.game.games.ParkourMiniGame; +import net.crankedpvp.events.utils.Utils; +import net.crankedpvp.events.utils.configuration.ConfigManager; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +@Command("parkour") +public class ParkourEventCommand extends CommandBase { + + private final MiniGameRegister miniGameRegister; + private final FileConfiguration languageFile; + + public ParkourEventCommand(EventsPlugin plugin) { + this.miniGameRegister = plugin.getMiniGameRegister(); + this.languageFile = plugin.getConfigManager() + .getConfig(ConfigManager.ConfigFile.LANGUAGE); + } + + + @SubCommand("join") + public void joinParkour(Player sender) { + + if (miniGameRegister.getMiniGame(MiniGameType.PARKOUR) == null) return; + + ParkourMiniGame parkourMiniGame = (ParkourMiniGame) miniGameRegister.getMiniGame(MiniGameType.PARKOUR); + + if (parkourMiniGame.getMiniGameState() == MiniGameState.IN_PROGRESS) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.already-in-progress").replace("{game}", "Parkour"))); + return; + } + + if (parkourMiniGame.getMiniGameState() == MiniGameState.NOT_STARTED) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.not-started").replace("{game}", "Parkour"))); + return; + } + + if (parkourMiniGame.isFull()) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.full").replace("{game}", "Parkour"))); + return; + } + + if (!Utils.isInventoryEmpty(sender)) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.inventory-empty"))); + return; + } + + parkourMiniGame.joinMiniGame(sender); + parkourMiniGame.sendMessageToAllParticipants(languageFile.getString("messages.event.player-joined") + .replace("{game}", "Parkour") + .replace("{player}", sender.getName()) + .replace("{amount}", String.valueOf(parkourMiniGame.getParticipants().size())) + .replace("{max}", String.valueOf(parkourMiniGame.getMaxPlayers())) + ); + } + + @SubCommand("leave") + public void leaveParkour(Player sender) { + if (miniGameRegister.getMiniGame(MiniGameType.PARKOUR) == null) return; + + ParkourMiniGame parkourMiniGame = (ParkourMiniGame) miniGameRegister.getMiniGame(MiniGameType.PARKOUR); + + if (!parkourMiniGame.isParticipant(sender)) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.not-participant").replace("{game}", "Parkour"))); + return; + } + + parkourMiniGame.leaveMiniGame(sender); + parkourMiniGame.sendMessageToAllParticipants(languageFile.getString("messages.event.player-left") + .replace("{game}", "Parkour") + .replace("{player}", sender.getName()) + .replace("{amount}", String.valueOf(parkourMiniGame.getParticipants().size())) + .replace("{max}", String.valueOf(parkourMiniGame.getMaxPlayers())) + ); + } + + @SubCommand("checkpoint") + public void checkpointParkour(Player sender) { + if (miniGameRegister.getMiniGame(MiniGameType.PARKOUR) == null) return; + + ParkourMiniGame parkourMiniGame = (ParkourMiniGame) miniGameRegister.getMiniGame(MiniGameType.PARKOUR); + + if (!parkourMiniGame.isParticipant(sender)) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.not-participant").replace("{game}", "Parkour"))); + return; + } + + parkourMiniGame.teleportParticipantToCheckpoint(sender); + } + + @Default + public void doHelp(CommandSender sender) { + List helpMessageList = languageFile.getStringList("messages.parkour-help-message"); + String[] helpMessage = new String[helpMessageList.size()]; + helpMessage = Utils.color(helpMessageList.toArray(helpMessage)); + sender.sendMessage(helpMessage); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/commands/SumoEventCommand.java b/Events/src/main/java/net/crankedpvp/events/commands/SumoEventCommand.java new file mode 100644 index 0000000..044ee99 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/commands/SumoEventCommand.java @@ -0,0 +1,96 @@ +package net.crankedpvp.events.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.MiniGameRegister; +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.MiniGameType; +import net.crankedpvp.events.game.games.SumoMiniGame; +import net.crankedpvp.events.utils.Utils; +import net.crankedpvp.events.utils.configuration.ConfigManager; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +@Command("sumo") +public class SumoEventCommand extends CommandBase { + + private final MiniGameRegister miniGameRegister; + private final FileConfiguration languageFile; + + public SumoEventCommand(EventsPlugin plugin) { + this.miniGameRegister = plugin.getMiniGameRegister(); + this.languageFile = plugin.getConfigManager() + .getConfig(ConfigManager.ConfigFile.LANGUAGE); + } + + + @SubCommand("join") + public void joinSumo(Player sender) { + + if (miniGameRegister.getMiniGame(MiniGameType.SUMO) == null) return; + + SumoMiniGame sumoMiniGame = (SumoMiniGame) miniGameRegister.getMiniGame(MiniGameType.SUMO); + + if (sumoMiniGame.getMiniGameState() == MiniGameState.IN_PROGRESS) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.already-in-progress").replace("{game}", "Sumo"))); + return; + } + + if (sumoMiniGame.getMiniGameState() == MiniGameState.NOT_STARTED) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.not-started").replace("{game}", "Sumo"))); + return; + } + + if (sumoMiniGame.isFull()) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.full").replace("{game}", "Sumo"))); + return; + } + + if (!Utils.isInventoryEmpty(sender)) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.inventory-empty"))); + return; + } + + sumoMiniGame.joinMiniGame(sender); + sumoMiniGame.sendMessageToAllParticipants(languageFile.getString("messages.event.player-joined") + .replace("{game}", "Sumo") + .replace("{player}", sender.getName()) + .replace("{amount}", String.valueOf(sumoMiniGame.getParticipants().size())) + .replace("{max}", String.valueOf(sumoMiniGame.getMaxPlayers())) + ); + } + + @SubCommand("leave") + public void leaveSumo(Player sender) { + if (miniGameRegister.getMiniGame(MiniGameType.SUMO) == null) return; + + SumoMiniGame sumoMiniGame = (SumoMiniGame) miniGameRegister.getMiniGame(MiniGameType.SUMO); + + if (!sumoMiniGame.isParticipant(sender) && !sumoMiniGame.isSpectator(sender)) { + sender.sendMessage(Utils.color(languageFile.getString("messages.event.not-participant").replace("{game}", "Sumo"))); + return; + } + + sumoMiniGame.leaveMiniGame(sender); + sumoMiniGame.sendMessageToAllParticipants(languageFile.getString("messages.event.player-left") + .replace("{game}", "Sumo") + .replace("{player}", sender.getName()) + .replace("{amount}", String.valueOf(sumoMiniGame.getParticipants().size())) + .replace("{max}", String.valueOf(sumoMiniGame.getMaxPlayers())) + ); + } + + @Default + public void doHelp(CommandSender sender) { + List helpMessageList = languageFile.getStringList("messages.sumo-help-message"); + String[] helpMessage = new String[helpMessageList.size()]; + helpMessage = Utils.color(helpMessageList.toArray(helpMessage)); + sender.sendMessage(helpMessage); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/commands/WarpKothCommand.java b/Events/src/main/java/net/crankedpvp/events/commands/WarpKothCommand.java new file mode 100644 index 0000000..f8a501c --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/commands/WarpKothCommand.java @@ -0,0 +1,34 @@ +package net.crankedpvp.events.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("warpkoth") +public class WarpKothCommand extends CommandBase { + + private final EventsPlugin plugin; + public WarpKothCommand(EventsPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getWarpKothInventory().getUI().open(player); + } + + @SubCommand("start") + @Permission("events.start") + public void startCommand(final CommandSender commandSender) { + this.plugin.getWarpKothManager().startEvent(); + if (!this.plugin.getWarpKothManager().isActive()) { + commandSender.sendMessage(CC.translate("&cWarp KOTH could not start. Check WARP_KOTH_NAME and the FactionsKore KOTH arena configuration; see the console for details.")); + } + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/MiniGame.java b/Events/src/main/java/net/crankedpvp/events/game/MiniGame.java new file mode 100644 index 0000000..76bb59d --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/MiniGame.java @@ -0,0 +1,267 @@ +package net.crankedpvp.events.game; + +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.utils.Utils; +import net.crankedpvp.events.utils.configuration.AbstractConfig; +import org.bukkit.*; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.*; +import org.bukkit.potion.PotionEffect; +import org.json.simple.parser.ParseException; + +import java.io.IOException; +import java.util.*; + +@Getter +public abstract class MiniGame implements Listener { + + private final byte minPlayers; + private final byte maxPlayers; + private final Location spawnLocation; + private final AbstractConfig abstractConfig; + private final ConfigurationSection configuration; + private final Map participants; + private final MiniGameType miniGameType; + private final String countdownMessage; + private final World gameWorld; + private final MiniGameOptions miniGamesOptions; + private final int countdownTime; + private final List rewardCommands; + private final Set spectators; + private final Material guiMaterial; + + @Setter + private MiniGameState miniGameState; + + @SneakyThrows + protected MiniGame(EventsPlugin plugin, MiniGameType miniGameType, Map participantsMap, MiniGameOptions miniGamesOptions, Material guiMaterial) { + this.miniGameType = miniGameType; + this.miniGameState = MiniGameState.NOT_STARTED; + this.miniGamesOptions = miniGamesOptions; + this.participants = participantsMap; + this.spectators = new HashSet<>(); + this.abstractConfig = plugin.getConfigManager().getAbstractConfig(miniGameType.getConfigFile()); + + this.configuration = abstractConfig.getConfig().getConfigurationSection("minigame"); + this.gameWorld = Bukkit.getWorld(this.configuration.getString("world")); + this.countdownMessage = Utils.color(this.configuration.getString("countdown-message")); + this.minPlayers = (byte) this.configuration.getInt("min-players"); + this.maxPlayers = (byte) this.configuration.getInt("max-players"); + this.countdownTime = this.configuration.getInt("countdown-time"); + + this.spawnLocation = this.getLocationFromConfig(configuration.getConfigurationSection("spawn-location")); + this.rewardCommands = this.configuration.getStringList("rewards"); + this.guiMaterial = guiMaterial; + + } + + protected MiniGame(EventsPlugin plugin, MiniGameType miniGameType) { + this(plugin, miniGameType, new HashMap<>(), MiniGameOptions.builder().build(), Material.STONE); + } + + public void addParticipant(T participant) { + this.participants.put(participant.getUUID(), participant); + } + + protected void removeParticipant(Player player) { + this.participants.remove(player.getUniqueId()); + } + + protected void removeParticipant(T participant) { + this.participants.remove(participant.getPlayer().getUniqueId()); + } + + protected void clearParticipants() { + this.participants.clear(); + } + + public boolean isParticipant(Player player) { + return this.participants.containsKey(player.getUniqueId()); + } + + public T getParticipant(Player player) { + return this.getParticipants().get(player.getUniqueId()); + } + + public boolean isFull() { + return this.maxPlayers <= this.participants.size(); + } + + public abstract void startMiniGame(); + public abstract void startMiniGameCountDown(); + public abstract void stopMiniGame(); + public abstract void joinMiniGame(Player player); + public abstract void leaveMiniGame(Player player); + + public void leaveMiniGame(T miniGamePlayer) { + this.leaveMiniGame(miniGamePlayer.getPlayer()); + } + + @EventHandler + public void onPlayerLeave(PlayerQuitEvent event) { + if (!isParticipant(event.getPlayer()) && !isSpectator(event.getPlayer())) return; + leaveMiniGame(event.getPlayer()); + } + + @EventHandler + public void onFoodLossWhileInGame(FoodLevelChangeEvent event) { + if (!isValidParticipant(event.getEntity())) return; + if (miniGamesOptions.isFoodLoss()) return; + ((Player) event.getEntity()).setFoodLevel(20); + event.setCancelled(true); + } + + @EventHandler + public void onPickUpWhileInGame(PlayerPickupItemEvent event) { + if (!isValidParticipant(event.getPlayer())) return; + if (miniGamesOptions.isItemPickUp()) return; + + event.setCancelled(true); + } + + @EventHandler + public void onBlockPlaceWhileInGame(BlockPlaceEvent event) { + if (!isValidParticipant(event.getPlayer())) return; + if (miniGamesOptions.isBlockPlace()) return; + + event.setCancelled(true); + } + + @EventHandler + public void onBlockBreakWhileInGame(BlockBreakEvent event) { + if (!isValidParticipant(event.getPlayer())) return; + if (miniGamesOptions.isBlockBreak()) return; + + event.setCancelled(true); + } + + @EventHandler + public void onPickUpWhileInGame(PlayerDropItemEvent event) { + if (!isValidParticipant(event.getPlayer())) return; + if (miniGamesOptions.isItemDrop()) return; + + event.setCancelled(true); + } + + @EventHandler + public void onFallDamageToPlayerWhileInGame(EntityDamageEvent event) { + if (!isValidParticipant(event.getEntity())) return; + if (miniGamesOptions.isFallDamage()) return; + if (event.getCause() != EntityDamageEvent.DamageCause.FALL) return; + event.setCancelled(true); + } + + @EventHandler + public void onInventoryInteract(InventoryClickEvent event) { + if (!isValidParticipant(event.getWhoClicked())) return; + if (miniGamesOptions.isInventoryInteract()) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onCommandWhileInGame(PlayerCommandPreprocessEvent event) { + if (!isValidParticipant(event.getPlayer())) return; + + if (!miniGamesOptions.isBlockCommands()) return; + + String command = event.getMessage().replace("/", "").toLowerCase(Locale.ROOT); + + if (Arrays.stream(this.miniGamesOptions.getExcludedBlockedCommands()).noneMatch(command::startsWith)) + event.setCancelled(true); + } + + private boolean isValidParticipant(Player player) { + if (!this.isParticipant(player) && !this.isSpectator(player)) return false; + if (player.isOp()) return false; + return !player.hasPermission("astro.admin"); + } + + private boolean isValidParticipant(Entity entity) { + if (!(entity instanceof Player)) return false; + return isValidParticipant((Player) entity); + } + + public void giveWinnerRewards(Player player) { + this.getRewardCommands().forEach(command -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName()))); + } + + public void giveWinnerRewards(T miniGamePlayer) { + this.giveWinnerRewards(miniGamePlayer.getPlayer()); + } + + protected void clearInventory(Player player){ + player.getInventory().setHelmet(null); + player.getInventory().setChestplate(null); + player.getInventory().setLeggings(null); + player.getInventory().setBoots(null); + player.getInventory().clear(); + player.updateInventory(); + } + + protected void clearPotionEffects(Player player){ + for(PotionEffect effect:player.getActivePotionEffects()){ + player.removePotionEffect(effect.getType()); + } + } + + + protected void addSpectator(T player) { + if (player == null) return; + this.spectators.add(player); + if (this.isParticipant(player.getPlayer())) this.removeParticipant(player); + player.getPlayer().teleport(this.getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.getPlayer().setGameMode(GameMode.SPECTATOR); + } + + protected Optional getSpectator(Player player) { + return this.spectators.stream().filter(spectator -> spectator.getPlayer().equals(player)).findFirst(); + } + + public boolean isSpectator(Player player) { + if (player == null) return false; + return this.spectators.stream().anyMatch(spectator -> spectator.getPlayer().equals(player)); + } + + public void sendMessageToAllParticipants(String message) { + this.getParticipants().forEach((uuid, player) -> player.sendMessage(message)); + } + + public boolean isSpectator(T sumoPlayer) { + return this.spectators.contains(sumoPlayer); + } + + protected void clearSpectators() { + this.spectators.clear(); + } + + protected void removeSpectator(T player) { + this.spectators.remove(player); + } + + protected void removeSpectator(Player player) { + this.spectators.removeIf(spectator -> spectator.getPlayer().equals(player)); + } + + protected Location getLocationFromConfig(ConfigurationSection configSection) { + double x = configSection.getDouble("x"); + double y = configSection.getDouble("y"); + double z = configSection.getDouble("z"); + float yaw = Utils.defaultIfNull((float) configSection.getDouble("yaw"), (float) 0.0); + float pitch = Utils.defaultIfNull((float) configSection.getDouble("pitch"), (float) 0.0); + return new Location(this.gameWorld, x, y, z, yaw, pitch); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/MiniGameManager.java b/Events/src/main/java/net/crankedpvp/events/game/MiniGameManager.java new file mode 100644 index 0000000..31ad5d8 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/MiniGameManager.java @@ -0,0 +1,45 @@ +package net.crankedpvp.events.game; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.tasks.AutoMiniGameTask; +import net.crankedpvp.events.utils.Utils; + + +@Getter +@Setter +public class MiniGameManager { + + private static final long TIME_BETWEEN_EVENTS_IN_SECS = 7200; + + private long lastMiniGameTime; + private final MiniGameRegister miniGameRegister; + private final EventsPlugin plugin; + private AutoMiniGameTask autoMiniGameTask; + private MiniGameType previousMiniGame; + + public MiniGameManager(EventsPlugin plugin) { + this.miniGameRegister = plugin.getMiniGameRegister(); + this.previousMiniGame = MiniGameType.SUMO; + this.plugin = plugin; + } + + public void startAutoMiniGameTask() { + this.autoMiniGameTask = new AutoMiniGameTask(this, this.miniGameRegister); + this.autoMiniGameTask.runTaskTimer(plugin, TIME_BETWEEN_EVENTS_IN_SECS * 20, TIME_BETWEEN_EVENTS_IN_SECS * 20); + this.lastMiniGameTime = System.currentTimeMillis(); + } + + public MiniGameType getNextMiniGame() { + return previousMiniGame == MiniGameType.PARKOUR ? MiniGameType.SUMO : MiniGameType.PARKOUR; + } + + public long getTimeInMsUntilNextMiniGame() { + return (lastMiniGameTime + TIME_BETWEEN_EVENTS_IN_SECS * 1000) - System.currentTimeMillis(); + } + + public String getTimeUntilNextMiniGame() { + return Utils.getSecondsAsString(this.getTimeInMsUntilNextMiniGame() / 1000); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/MiniGameOptions.java b/Events/src/main/java/net/crankedpvp/events/game/MiniGameOptions.java new file mode 100644 index 0000000..b91a900 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/MiniGameOptions.java @@ -0,0 +1,28 @@ +package net.crankedpvp.events.game; + +import lombok.Builder; +import lombok.Getter; + +@Builder +@Getter +public class MiniGameOptions { + + @Builder.Default + private final boolean foodLoss = false; + @Builder.Default + private final boolean blockPlace = false; + @Builder.Default + private final boolean blockBreak = false; + @Builder.Default + private final boolean fallDamage = false; + @Builder.Default + private final boolean itemPickUp = false; + @Builder.Default + private final boolean itemDrop = false; + @Builder.Default + private final boolean blockCommands = true; + @Builder.Default + private final boolean inventoryInteract = false; + @Builder.Default + private final String[] excludedBlockedCommands = {"parkour"}; +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/MiniGamePlayer.java b/Events/src/main/java/net/crankedpvp/events/game/MiniGamePlayer.java new file mode 100644 index 0000000..0ac90af --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/MiniGamePlayer.java @@ -0,0 +1,35 @@ +package net.crankedpvp.events.game; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.events.utils.PlayerInventoryContents; +import net.crankedpvp.events.utils.Utils; +import org.bukkit.entity.Player; + +import java.util.UUID; + +@Getter +public class MiniGamePlayer { + + private final Player player; + @Setter + private long joinGameTime; + private final PlayerInventoryContents playerInventoryContents; + @Setter + private boolean damageEnabled; + + public MiniGamePlayer(Player player) { + this.player = player; + this.joinGameTime = System.currentTimeMillis(); + this.playerInventoryContents = new PlayerInventoryContents(player.getInventory().getContents().clone(), player.getInventory().getArmorContents().clone()); + this.damageEnabled = false; + } + + public void sendMessage(String text) { + this.player.sendMessage(Utils.color(text)); + } + + public UUID getUUID() { + return this.player.getUniqueId(); + } +} \ No newline at end of file diff --git a/Events/src/main/java/net/crankedpvp/events/game/MiniGameRegister.java b/Events/src/main/java/net/crankedpvp/events/game/MiniGameRegister.java new file mode 100644 index 0000000..a9432fb --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/MiniGameRegister.java @@ -0,0 +1,72 @@ +package net.crankedpvp.events.game; + +import lombok.Getter; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.games.ParkourMiniGame; +import net.crankedpvp.events.game.games.SumoMiniGame; +import org.bukkit.event.HandlerList; + +import java.util.HashMap; +import java.util.Map; + +public class MiniGameRegister { + + private final EventsPlugin plugin; + @Getter + private final Map> miniGames; + + public MiniGameRegister(EventsPlugin plugin) { + this.plugin = plugin; + this.miniGames = new HashMap<>(); + } + + public void initialize() { + this.registerAll(new ParkourMiniGame(plugin), new SumoMiniGame(plugin)); + } + + private void registerAll(MiniGame... miniGames) { + for (MiniGame miniGame : miniGames) { + register(miniGame); + } + } + + private void register(MiniGame miniGame) { + try { + if (miniGame.getGameWorld() == null) { + plugin.getLogger().warning("Skipping " + miniGame.getMiniGameType().name() + + " minigame because world '" + miniGame.getConfiguration().getString("world") + + "' is not loaded."); + return; + } + this.miniGames.put(miniGame.getMiniGameType(), miniGame); + + plugin.getServer().getPluginManager().registerEvents(miniGame, plugin); + + } catch (Exception exception) { + System.err.println("Failed to register minigame: " + miniGame.getMiniGameType().name()); + } + } + + public void unregisterAll() { + this.miniGames.forEach(((miniGameType, miniGame) -> { + miniGame.stopMiniGame(); + HandlerList.unregisterAll(miniGame); + })); + this.miniGames.clear(); + } + + private void unregister(MiniGame miniGame) { + miniGame.stopMiniGame(); + HandlerList.unregisterAll(miniGame); + this.miniGames.remove(miniGame.getMiniGameType()); + } + + public void reloadMiniGames() { + this.unregisterAll(); + this.initialize(); + } + + public MiniGame getMiniGame(MiniGameType miniGameType) { + return this.miniGames.get(miniGameType); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/MiniGameState.java b/Events/src/main/java/net/crankedpvp/events/game/MiniGameState.java new file mode 100644 index 0000000..6d7da1e --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/MiniGameState.java @@ -0,0 +1,8 @@ +package net.crankedpvp.events.game; + +public enum MiniGameState { + + NOT_STARTED(), + STARTING(), + IN_PROGRESS() +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/MiniGameType.java b/Events/src/main/java/net/crankedpvp/events/game/MiniGameType.java new file mode 100644 index 0000000..bc269bd --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/MiniGameType.java @@ -0,0 +1,17 @@ +package net.crankedpvp.events.game; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.events.utils.configuration.ConfigManager; + +@AllArgsConstructor +@Getter +public enum MiniGameType { + + PARKOUR(ConfigManager.ConfigFile.PARKOUR), + SUMO(ConfigManager.ConfigFile.SUMO), + SPLEEF(ConfigManager.ConfigFile.SPLEEF) + ; + + private final ConfigManager.ConfigFile configFile; +} \ No newline at end of file diff --git a/Events/src/main/java/net/crankedpvp/events/game/games/ParkourMiniGame.java b/Events/src/main/java/net/crankedpvp/events/game/games/ParkourMiniGame.java new file mode 100644 index 0000000..bb9d3a6 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/games/ParkourMiniGame.java @@ -0,0 +1,275 @@ +package net.crankedpvp.events.game.games; + +import com.gmail.filoghost.holographicdisplays.api.Hologram; +import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.ImmutableBiMap; +import lombok.Getter; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.MiniGame; +import net.crankedpvp.events.game.MiniGameOptions; +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.MiniGameType; +import net.crankedpvp.events.game.players.ParkourPlayer; +import net.crankedpvp.events.game.tasks.MiniGameCountDown; +import net.crankedpvp.events.game.tasks.MiniGameFlyDisableTask; +import net.crankedpvp.events.game.tasks.ParkourTimeTask; +import net.crankedpvp.events.utils.Clickable; +import net.crankedpvp.events.utils.Utils; +import net.crankedpvp.events.utils.configuration.ConfigParser; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +public class ParkourMiniGame extends MiniGame { + + @Getter + private long startTime; + private final BiMap parkourCheckpoints; + private final Map parkourYawCheckpoints; + private final EventsPlugin plugin; + private final Location endLocation; + @Getter + private final String parkourTimeMessage; + private final ItemStack checkpointItem; + private final ItemStack leaveItem; + private boolean checkpointsLoaded; + + public ParkourMiniGame(EventsPlugin plugin) { + super(plugin, MiniGameType.PARKOUR, new HashMap<>(), MiniGameOptions.builder().excludedBlockedCommands(new String[]{"parkour"}).build(), Material.FEATHER); + this.plugin = plugin; + + this.startTime = 0; + this.parkourCheckpoints = HashBiMap.create(); + this.parkourYawCheckpoints = new HashMap<>(); + + ConfigurationSection checkpointsConfigSection = super.getConfiguration().getConfigurationSection("checkpoints"); + + checkpointsConfigSection.getKeys(false).forEach((s -> { + ConfigurationSection checkpointSection = checkpointsConfigSection.getConfigurationSection(s); + Location location = super.getLocationFromConfig(checkpointSection); + Byte number = Byte.parseByte(s); + this.parkourYawCheckpoints.put(number, location.getYaw()); + location.setYaw((float) 0.0); + parkourCheckpoints.put(location, Byte.parseByte(s)); + })); + + this.endLocation = super.getLocationFromConfig(super.getConfiguration().getConfigurationSection("end-location")); + this.parkourTimeMessage = Utils.color(this.getConfiguration().getString("parkour-time-message")); + this.leaveItem = ConfigParser.parseItem(super.getConfiguration().getConfigurationSection("items.leave-item")); + this.checkpointItem = ConfigParser.parseItem(super.getConfiguration().getConfigurationSection("items.checkpoint-item")); + } + + public Byte getCheckPoint(Location location) { + return this.parkourCheckpoints.get(location); + + } + + public boolean isCheckPoint(Location location) { + return this.getCheckpoints().containsKey(location); + } + + @Override + public void startMiniGame() { + this.startTime = System.currentTimeMillis(); + super.setMiniGameState(MiniGameState.IN_PROGRESS); + super.getParticipants().forEach((playerUUID, participant) -> { + Player player = participant.getPlayer(); + player.getInventory().setItem(3, this.getCheckpointItem()); + player.getInventory().setItem(5, this.getLeaveItem()); + if (this.getCheckpoints().inverse().containsKey((byte) 0)) + player.teleport(this.getCheckpoints().inverse().get((byte) 0), PlayerTeleportEvent.TeleportCause.UNKNOWN); + }); + new ParkourTimeTask(this).runTaskTimer(plugin, 0L, 20L); + } + + @Override + public void startMiniGameCountDown() { + this.loadCheckpoints(); + super.setMiniGameState(MiniGameState.STARTING); + new MiniGameCountDown(this).runTaskTimer(plugin, 0L, 20L); + new MiniGameFlyDisableTask(this).runTaskTimer(plugin, 0L, 10L); + } + + @Override + public void stopMiniGame() { + this.unLoadCheckpoints(); + super.getParticipants().forEach((player, participant) -> { + this.leaveMiniGame(participant.getPlayer(), true); + }); + super.clearParticipants(); + super.setMiniGameState(MiniGameState.NOT_STARTED); + } + + @Override + public void joinMiniGame(Player player) { + if (isParticipant(player)) return; + super.addParticipant(new ParkourPlayer(player)); + player.teleport(super.getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.setHealth(20); + player.setFoodLevel(20); + player.setAllowFlight(false); + player.setFlying(false); + super.clearPotionEffects(player); + super.clearInventory(player); + } + + @Override + public void leaveMiniGame(Player player) { + if (this.getParticipants().size() <= 1 && this.getMiniGameState() == MiniGameState.IN_PROGRESS) { + this.stopMiniGame(); + return; + } + this.leaveMiniGame(player, false); + } + + private void leaveMiniGame(Player player, boolean stopMiniGame) { + if (!isParticipant(player)) return; + player.teleport(Bukkit.getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + super.clearInventory(player); + super.clearPotionEffects(player); + super.getParticipant(player).getPlayerInventoryContents().restore(player); + if (stopMiniGame) return; + super.removeParticipant(player); + } + + @EventHandler + public void onDamageWhileInParkour(EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!super.isParticipant((Player) event.getEntity())) return; + + if (event.getCause() == EntityDamageEvent.DamageCause.VOID) { + teleportParticipantToCheckpoint((Player) event.getEntity()); + } + + event.setCancelled(true); + } + + @EventHandler + public void checkpointCross(PlayerInteractEvent event) { + if (event.getAction() != Action.PHYSICAL) return; + if (!super.isParticipant(event.getPlayer())) return; + + Location location = event.getClickedBlock().getLocation(); + ParkourPlayer parkourPlayer = super.getParticipant(event.getPlayer()); + + if (this.endLocation.equals(location)) { + this.announceWinner(event.getPlayer()); + this.stopMiniGame(); + super.giveWinnerRewards(event.getPlayer()); + return; + } + + if (!isCheckPoint(location)) return; + + Byte locationCheckpoint = this.getCheckPoint(location); + + if (parkourPlayer.getCurrentCheckpoint() >= locationCheckpoint) return; + + parkourPlayer.sendMessage(super.getConfiguration().getString("checkpoint-reached-message").replace("{number}", String.valueOf(locationCheckpoint))); + parkourPlayer.setCurrentCheckpoint(locationCheckpoint); + + } + + @EventHandler + public void parkourItemClick(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK ) return; + if (!super.isParticipant(event.getPlayer())) return; + if (event.getItem() == null) return; + + if (event.getItem().getType() == this.checkpointItem.getType()) { + teleportParticipantToCheckpoint(event.getPlayer()); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ITEM_PICKUP, 1.0F, 1.0F); + } + + if (event.getItem().getType() == this.leaveItem.getType()) { + Clickable parkourLeaveClickable = new Clickable(""); + parkourLeaveClickable.add(Utils.color(super.getConfiguration().getString("parkour-confirm-leave-message")), Utils.color("&7click to confirm"), "/parkour leave"); + parkourLeaveClickable.sendToPlayer(event.getPlayer()); + } + } + + public void announceWinner(Player player) { + String time = Utils.getTimeFromSecsToMins((System.currentTimeMillis() - this.getStartTime()) / 1000); + Bukkit.broadcastMessage(Utils.color(super.getConfiguration().getString("win-message").replace("{player}", player.getName()).replace("{time}", time))); + } + + public void teleportParticipantToCheckpoint(Player player) { + Byte checkpoint = super.getParticipant(player).getCurrentCheckpoint(); + Location location = this.getCheckpoints().inverse().get(checkpoint); + + if (location != null) { + location = location.clone(); + location.add(0.5, 0.0, 0.5); + location.setYaw(parkourYawCheckpoints.get(checkpoint)); + } + + player.teleport(Utils.defaultIfNull(location, getSpawnLocation()), PlayerTeleportEvent.TeleportCause.UNKNOWN); + } + + private void createCheckpointHolo(byte number, Location location) { + location.getBlock().setType(Material.GOLD_PLATE); + Hologram hologram = HologramsAPI.createHologram(plugin, location.add(0.5, 2.0, 0.5)); + hologram.appendTextLine(Utils.color("&aCheckpoint #" + number)); + + } + + private void createEndCheckpoint() { + this.endLocation.getBlock().setType(Material.GOLD_PLATE); + Hologram hologram = HologramsAPI.createHologram(plugin, this.endLocation.clone().add(0.5, 2.0, 0.5)); + hologram.appendTextLine(Utils.color("&aParkour End")); + } + + private void loadCheckpoints() { + if (checkpointsLoaded) return; + this.getCheckpoints().forEach(((location, number) -> { + this.createCheckpointHolo(number, location.clone()); + })); + createEndCheckpoint(); + checkpointsLoaded = true; + } + + private void unLoadCheckpoints() { + if (!checkpointsLoaded) return; + checkpointsLoaded = false; + World gameWorld = super.getGameWorld(); + if (gameWorld == null || Bukkit.getWorld(gameWorld.getName()) == null) return; + this.getCheckpoints().forEach(((location, number) -> { + location.getBlock().setType(Material.AIR); + })); + + this.endLocation.getBlock().setType(Material.AIR); + + for (Hologram hologram : HologramsAPI.getHolograms(plugin)) { + if (!gameWorld.equals(hologram.getWorld())) continue; + //if (!parkourCheckpoints.containsKey(hologram.getLocation().add(0.5, 3.0, 0.5))) return; + hologram.delete(); + } + } + + public ImmutableBiMap getCheckpoints() { + return ImmutableBiMap.copyOf(this.parkourCheckpoints); + } + + private ItemStack getCheckpointItem() { + return this.checkpointItem; + } + + private ItemStack getLeaveItem() { + return this.leaveItem; + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/games/SpleefMiniGame.java b/Events/src/main/java/net/crankedpvp/events/game/games/SpleefMiniGame.java new file mode 100644 index 0000000..228025e --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/games/SpleefMiniGame.java @@ -0,0 +1,162 @@ +package net.crankedpvp.events.game.games; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.MiniGame; +import net.crankedpvp.events.game.MiniGameOptions; +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.MiniGameType; +import net.crankedpvp.events.game.players.SpleefPlayer; +import net.crankedpvp.events.game.tasks.MiniGameCountDown; +import net.crankedpvp.events.game.tasks.MiniGameFlyDisableTask; +import net.crankedpvp.events.utils.BlockUtil; +import net.crankedpvp.events.utils.Pair; +import net.crankedpvp.events.utils.Utils; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class SpleefMiniGame extends MiniGame { + + private final EventsPlugin plugin; + private final List> platformCorners; + + protected SpleefMiniGame(EventsPlugin plugin) { + super(plugin, + MiniGameType.SPLEEF, + new HashMap<>(), + MiniGameOptions.builder() + .blockBreak(true) + .itemPickUp(true) + .build(), + Material.SNOW_BALL + ); + this.plugin = plugin; + this.platformCorners = new ArrayList<>(); + + ConfigurationSection platformCornersConfigSection = this.getConfiguration().getConfigurationSection("minigame.platform-corners"); + + platformCornersConfigSection.getKeys(false).forEach(str -> { + Location cornerOne = super.getLocationFromConfig(platformCornersConfigSection.getConfigurationSection(str + ".corner-one")); + Location cornerTwo = super.getLocationFromConfig(platformCornersConfigSection.getConfigurationSection(str + ".corner-two")); + Pair corners = new Pair<>(cornerOne, cornerTwo); + this.platformCorners.add(corners); + }); + } + + @Override + public void startMiniGame() { + super.setMiniGameState(MiniGameState.IN_PROGRESS); + + super.getParticipants().forEach(((uuid, spleefPlayer) -> { + Utils.sendTitle(spleefPlayer.getPlayer(), CC.Aqua + "Start!", "", 10, 40, 10); + })); + } + + @Override + public void startMiniGameCountDown() { + super.setMiniGameState(MiniGameState.STARTING); + new MiniGameCountDown(this).runTaskTimer(plugin, 0L, 20L); + new MiniGameFlyDisableTask(this).runTaskTimer(plugin, 0L, 10L); + } + + @Override + public void stopMiniGame() { + super.getParticipants().forEach((player, participant) -> { + this.leaveMiniGame(participant.getPlayer(), true); + }); + + super.clearParticipants(); + super.setMiniGameState(MiniGameState.NOT_STARTED); + this.fixAllPlatforms(); + } + + @Override + public void joinMiniGame(Player player) { + if (isParticipant(player)) return; + super.addParticipant(new SpleefPlayer(player)); + player.teleport(super.getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.setHealth(20); + player.setFoodLevel(20); + super.clearPotionEffects(player); + super.clearInventory(player); + player.setAllowFlight(false); + player.setFlying(false); + } + + + @Override + public void leaveMiniGame(Player player) { + if (this.getParticipants().size() <= 1 && this.getMiniGameState() == MiniGameState.IN_PROGRESS) { + this.stopMiniGame(); + return; + } + + this.leaveMiniGame(player, false); + } + + private void leaveMiniGame(Player player, boolean stopMiniGame) { + if (!isParticipant(player) && !isSpectator(player)) return; + + player.setGameMode(GameMode.SURVIVAL); + player.teleport(Bukkit.getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.setWalkSpeed((float) 0.2); + super.clearInventory(player); + super.clearPotionEffects(player); + + if (super.isParticipant(player)) { + super.getParticipant(player).getPlayerInventoryContents().restore(player); + } + + if (stopMiniGame) return; + + if (isParticipant(player)) { + super.removeParticipant(player); + } + + //TODO: finish spleef, choose winner + } + + @EventHandler + public void onDamageWhileInSpleef(EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!super.isParticipant((Player) event.getEntity())) return; + + event.setCancelled(true); + } + + @EventHandler + public void onBlockBreakWhileSpleefIsStarting(BlockBreakEvent event) { + if (!super.isParticipant(event.getPlayer())) return; + if (super.getMiniGameState() != MiniGameState.IN_PROGRESS) return; + + event.setCancelled(true); + } + + private void fixAllPlatforms() { + for (Pair locationPair : this.platformCorners) { + this.fixPlatform(locationPair.getLeft(), locationPair.getRight()); + } + } + + private void fixPlatform(Location cornerOne, Location cornerTwo) { + final int y = (int) cornerOne.getY(); + + for (int i = (int) cornerOne.getX(); i < cornerTwo.getX(); i++) { + for (int j = (int) cornerOne.getZ(); j < cornerTwo.getZ(); j++) { + BlockUtil.setBlockFast(this.getGameWorld(), i, y, j, 80, (byte) 0, false); + } + } + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/games/SumoMiniGame.java b/Events/src/main/java/net/crankedpvp/events/game/games/SumoMiniGame.java new file mode 100644 index 0000000..a95df57 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/games/SumoMiniGame.java @@ -0,0 +1,235 @@ +package net.crankedpvp.events.game.games; + +import lombok.Getter; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.MiniGame; +import net.crankedpvp.events.game.MiniGameOptions; +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.MiniGameType; +import net.crankedpvp.events.game.players.SumoPlayer; +import net.crankedpvp.events.utils.Pair; +import net.crankedpvp.events.utils.Utils; +import net.crankedpvp.events.game.tasks.*; +import org.apache.commons.collections4.map.LinkedMap; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + + +public class SumoMiniGame extends MiniGame { + + @Getter + private final Location fightLocationOne; + @Getter + private final Location fightLocationTwo; + private final EventsPlugin plugin; + @Getter + private final Pair duelPlayers; + private final Map tempMap; + + public SumoMiniGame(EventsPlugin plugin) { + super(plugin, MiniGameType.SUMO, new LinkedMap<>(), MiniGameOptions.builder().excludedBlockedCommands(new String[]{"sumo"}).build(), Material.STICK); + this.plugin = plugin; + this.duelPlayers = new Pair<>(null, null); + this.tempMap = new HashMap<>(); + + ConfigurationSection fightLocationOneSection = super.getConfiguration().getConfigurationSection("fight-location-one"); + Optional possibleFightLocationOne = Optional.of(super.getLocationFromConfig(fightLocationOneSection)); + + this.fightLocationOne = possibleFightLocationOne.orElseThrow(() -> new IllegalArgumentException("Invalid fight one location")); + + ConfigurationSection fightLocationTwoSection = super.getConfiguration().getConfigurationSection("fight-location-two"); + Optional possibleFightLocationTwo = Optional.of(super.getLocationFromConfig(fightLocationTwoSection)); + + this.fightLocationTwo = possibleFightLocationTwo.orElseThrow(() -> new IllegalArgumentException("Invalid fight two location"));; + } + + @Override + public void startMiniGame() { + super.setMiniGameState(MiniGameState.IN_PROGRESS); + this.fight(); + new SumoDeathCheckTask(this).runTaskTimer(plugin, 0L, 20L); + new SpectatorTeleportBackTask(this).runTaskTimer(plugin, 0L, 20L); + } + + @Override + public void startMiniGameCountDown() { + super.setMiniGameState(MiniGameState.STARTING); + new MiniGameCountDown(this).runTaskTimer(plugin, 0L, 20L); + new MiniGameFlyDisableTask(this).runTaskTimer(plugin, 0L, 10L); + } + + @Override + public void stopMiniGame() { + super.getParticipants().forEach((player, participant) -> { + this.leaveMiniGame(participant.getPlayer(), true); + }); + + super.getSpectators().forEach(spectator -> { + this.leaveMiniGame(spectator.getPlayer(), true); + }); + + super.clearParticipants(); + super.clearSpectators(); + super.setMiniGameState(MiniGameState.NOT_STARTED); + } + + @Override + public void joinMiniGame(Player player) { + if (isParticipant(player)) return; + super.addParticipant(new SumoPlayer(player)); + player.teleport(super.getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.setHealth(20); + player.setFoodLevel(20); + super.clearPotionEffects(player); + super.clearInventory(player); + player.setAllowFlight(false); + player.setFlying(false); + } + + @Override + public void leaveMiniGame(Player player) { + if (this.getParticipants().size() <= 1 && this.getMiniGameState() == MiniGameState.IN_PROGRESS) { + this.stopMiniGame(); + return; + } + this.leaveMiniGame(player, false); + } + + private void leaveMiniGame(Player player, boolean stopMiniGame) { + if (!isParticipant(player) && !isSpectator(player)) return; + + player.setGameMode(GameMode.SURVIVAL); + player.teleport(Bukkit.getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.setWalkSpeed((float) 0.2); + super.clearInventory(player); + super.clearPotionEffects(player); + + if (super.isParticipant(player)) { + super.getParticipant(player).getPlayerInventoryContents().restore(player); + } + + if (super.isSpectator(player)) { + Optional sumoPlayer = super.getSpectator(player); + sumoPlayer.ifPresent(participant -> participant.getPlayerInventoryContents().restore(player)); + } + + if (stopMiniGame) return; + + if (isParticipant(player)) { + super.removeParticipant(player); + } + + if (isSpectator(player)) { + super.removeSpectator(player); + } + + if (this.isInDuel(player)) { + this.choseWinner(this.getOpposingPlayer(player).getPlayer(), player); + } + } + + @EventHandler + public void onDamageWhileInGame(EntityDamageByEntityEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!(event.getDamager() instanceof Player)) return; + if (!isParticipant((Player) event.getEntity())) return; + if (!isParticipant((Player) event.getDamager())) return; + + if (super.getMiniGameState() == MiniGameState.STARTING) { + event.setCancelled(true); + return; + } + + if (super.getMiniGameState() == MiniGameState.IN_PROGRESS) { + event.setDamage(0.0); + } + + if (!this.isInDuel(super.getParticipant((Player) event.getEntity()))) { + event.setCancelled(true); + } + } + + public void choseWinner(Player winner, Player loser) { + this.getDuelPlayers().clear(); + + if (loser.isOnline()) { + SumoPlayer sumoPlayer = super.getParticipant(loser); + this.addSpectator(sumoPlayer); + } + + if (this.getParticipants().size() <= 1) { + this.stopMiniGame(); + this.giveWinnerRewards(winner); + Bukkit.broadcastMessage(Utils.color(super.getConfiguration().getString("win-message").replace("{player}", winner.getName()))); + return; + } + + winner.teleport(this.getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + + this.nextFight(); + } + + public void fight() { + this.duelPlayers.setLeft(this.getParticipantsQueue().getValue(0)); + this.duelPlayers.setRight(this.getParticipantsQueue().getValue(1)); + + this.duelPlayers.getLeft().getPlayer().setAllowFlight(false); + this.duelPlayers.getLeft().getPlayer().setFlying(false); + + this.duelPlayers.getRight().getPlayer().setAllowFlight(false); + this.duelPlayers.getRight().getPlayer().setFlying(false); + + this.duelPlayers.getLeft().getPlayer().teleport(fightLocationOne, PlayerTeleportEvent.TeleportCause.UNKNOWN); + this.duelPlayers.getRight().getPlayer().teleport(fightLocationTwo, PlayerTeleportEvent.TeleportCause.UNKNOWN); + new SumoStartDuelTask(this).runTaskTimer(plugin, 10, 10); + } + + public void nextFight() { + this.moveToEndOfQueue(); + this.moveToEndOfQueue(); + + this.fight(); + } + + public void moveToEndOfQueue() { + this.tempMap.put(this.getParticipantsQueue().get(0), this.getParticipantsQueue().getValue(0)); + this.getParticipantsQueue().remove(0); + this.getParticipants().putAll(this.tempMap); + this.tempMap.clear(); + } + + public boolean isInDuel(SumoPlayer sumoPlayer) { + return this.duelPlayers.contains(sumoPlayer); + } + + public SumoPlayer getOpposingPlayer(SumoPlayer sumoPlayer) { + return this.getOpposingPlayer(sumoPlayer.getPlayer()); + } + + public SumoPlayer getOpposingPlayer(Player player) { + if (!this.isInDuel(player)) return null; + return player.equals(this.duelPlayers.getLeft().getPlayer()) ? this.duelPlayers.getRight() : this.duelPlayers.getLeft(); + } + + public boolean isInDuel(Player sumoPlayer) { + if (this.duelPlayers.getLeft() == null) return false; + if (this.duelPlayers.getRight() == null) return false; + return this.duelPlayers.getLeft().getPlayer().equals(sumoPlayer) || this.duelPlayers.getRight().getPlayer().equals(sumoPlayer); + } + + public LinkedMap getParticipantsQueue() { + return ((LinkedMap) super.getParticipants()); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/players/ParkourPlayer.java b/Events/src/main/java/net/crankedpvp/events/game/players/ParkourPlayer.java new file mode 100644 index 0000000..5616855 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/players/ParkourPlayer.java @@ -0,0 +1,18 @@ +package net.crankedpvp.events.game.players; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.events.game.MiniGamePlayer; +import org.bukkit.entity.Player; + +@Getter +public class ParkourPlayer extends MiniGamePlayer { + + @Setter + private Byte currentCheckpoint; + + public ParkourPlayer(Player player) { + super(player); + this.currentCheckpoint = 0; + } +} \ No newline at end of file diff --git a/Events/src/main/java/net/crankedpvp/events/game/players/SpleefPlayer.java b/Events/src/main/java/net/crankedpvp/events/game/players/SpleefPlayer.java new file mode 100644 index 0000000..4625a37 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/players/SpleefPlayer.java @@ -0,0 +1,10 @@ +package net.crankedpvp.events.game.players; + +import net.crankedpvp.events.game.MiniGamePlayer; +import org.bukkit.entity.Player; + +public class SpleefPlayer extends MiniGamePlayer { + public SpleefPlayer(Player player) { + super(player); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/players/SumoPlayer.java b/Events/src/main/java/net/crankedpvp/events/game/players/SumoPlayer.java new file mode 100644 index 0000000..0d4fe6a --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/players/SumoPlayer.java @@ -0,0 +1,10 @@ +package net.crankedpvp.events.game.players; + +import net.crankedpvp.events.game.MiniGamePlayer; +import org.bukkit.entity.Player; + +public class SumoPlayer extends MiniGamePlayer { + public SumoPlayer(Player player) { + super(player); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/tasks/AutoMiniGameTask.java b/Events/src/main/java/net/crankedpvp/events/game/tasks/AutoMiniGameTask.java new file mode 100644 index 0000000..04999a3 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/tasks/AutoMiniGameTask.java @@ -0,0 +1,35 @@ +package net.crankedpvp.events.game.tasks; + +import lombok.AllArgsConstructor; +import net.crankedpvp.events.game.MiniGameManager; +import net.crankedpvp.events.game.MiniGameRegister; +import net.crankedpvp.events.game.MiniGameType; +import net.crankedpvp.events.game.MiniGame; +import org.bukkit.Bukkit; +import org.bukkit.scheduler.BukkitRunnable; + +@AllArgsConstructor +public class AutoMiniGameTask extends BukkitRunnable { + + private final MiniGameManager miniGameManager; + private final MiniGameRegister miniGameRegister; + + @Override + public void run() { + if (Bukkit.getOnlinePlayers().size() == 0) { + Bukkit.getConsoleSender().sendMessage("&6[AstroEvents] Not enough online players to start the event"); + this.miniGameManager.setLastMiniGameTime(System.currentTimeMillis()); + return; + } + + MiniGameType nextMiniGame = this.miniGameManager.getNextMiniGame(); + MiniGame miniGame = this.miniGameRegister.getMiniGame(nextMiniGame); + if (miniGame == null) { + this.miniGameManager.setLastMiniGameTime(System.currentTimeMillis()); + return; + } + miniGame.startMiniGameCountDown(); + this.miniGameManager.setLastMiniGameTime(System.currentTimeMillis()); + this.miniGameManager.setPreviousMiniGame(nextMiniGame); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/tasks/MiniGameCountDown.java b/Events/src/main/java/net/crankedpvp/events/game/tasks/MiniGameCountDown.java new file mode 100644 index 0000000..8adf3eb --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/tasks/MiniGameCountDown.java @@ -0,0 +1,50 @@ +package net.crankedpvp.events.game.tasks; + +import net.crankedpvp.events.game.MiniGame; +import net.crankedpvp.events.game.MiniGameState; +import org.bukkit.Bukkit; +import org.bukkit.scheduler.BukkitRunnable; + +public class MiniGameCountDown extends BukkitRunnable { + + private final MiniGame miniGame; + private int countdown; + private int disableCountdown; + + public MiniGameCountDown(MiniGame miniGame) { + this.miniGame = miniGame; + this.countdown = miniGame.getCountdownTime(); + this.disableCountdown = 300; + } + + @Override + public void run() { + + if (miniGame.getMiniGameState() != MiniGameState.STARTING) { + this.cancel(); + return; + } + + if (disableCountdown <= 0) { + this.miniGame.stopMiniGame(); + this.cancel(); + return; + } + + if (countdown == this.miniGame.getCountdownTime() || countdown == 120 || countdown == 60 || countdown == 45 || countdown == 30 || countdown == 15 || countdown == 10 || countdown == 5 || countdown == 3 || countdown == 2 || countdown == 1) + Bukkit.broadcastMessage(this.miniGame.getCountdownMessage().replace("{time}", countdown + "s")); + + if (countdown == 1) { + if (this.miniGame.getParticipants().size() >= this.miniGame.getMinPlayers()) { + this.miniGame.startMiniGame(); + this.cancel(); + return; + } else { + countdown = this.miniGame.getCountdownTime() + 1; + } + } + + countdown--; + disableCountdown--; + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/tasks/MiniGameFlyDisableTask.java b/Events/src/main/java/net/crankedpvp/events/game/tasks/MiniGameFlyDisableTask.java new file mode 100644 index 0000000..3f21ede --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/tasks/MiniGameFlyDisableTask.java @@ -0,0 +1,34 @@ +package net.crankedpvp.events.game.tasks; + +import net.crankedpvp.events.game.MiniGame; +import net.crankedpvp.events.game.MiniGameState; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +public class MiniGameFlyDisableTask extends BukkitRunnable { + + private final MiniGame miniGame; + + public MiniGameFlyDisableTask(MiniGame miniGame) { + this.miniGame = miniGame; + } + + @Override + public void run() { + if (this.miniGame.getMiniGameState() == MiniGameState.NOT_STARTED) { + this.cancel(); + return; + } + + this.miniGame.getParticipants().forEach((uuid, t) -> { + Player player = Bukkit.getPlayer(uuid); + if (player.getAllowFlight() && !player.isOp()) { + player.setAllowFlight(false); + } + if (player.isFlying() && !player.isOp()) { + player.setFlying(false); + } + }); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/tasks/ParkourTimeTask.java b/Events/src/main/java/net/crankedpvp/events/game/tasks/ParkourTimeTask.java new file mode 100644 index 0000000..4bd5f02 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/tasks/ParkourTimeTask.java @@ -0,0 +1,30 @@ +package net.crankedpvp.events.game.tasks; + +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.games.ParkourMiniGame; +import net.crankedpvp.events.utils.Utils; +import org.bukkit.scheduler.BukkitRunnable; + +public class ParkourTimeTask extends BukkitRunnable { + + private final ParkourMiniGame miniGame; + + public ParkourTimeTask(ParkourMiniGame miniGame) { + this.miniGame = miniGame; + } + + @Override + public void run() { + + if (miniGame.getMiniGameState() != MiniGameState.IN_PROGRESS || miniGame.getParticipants().isEmpty()) { + this.cancel(); + return; + } + + String time = Utils.getTimeFromSecsToMins((System.currentTimeMillis() - miniGame.getStartTime()) / 1000); + + miniGame.getParticipants().forEach((player, parkourPlayer) -> { + Utils.sendActionBarMessage(parkourPlayer.getPlayer(), Utils.color(miniGame.getParkourTimeMessage().replace("{time}", time))); + }); + } +} \ No newline at end of file diff --git a/Events/src/main/java/net/crankedpvp/events/game/tasks/SpectatorTeleportBackTask.java b/Events/src/main/java/net/crankedpvp/events/game/tasks/SpectatorTeleportBackTask.java new file mode 100644 index 0000000..a57482d --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/tasks/SpectatorTeleportBackTask.java @@ -0,0 +1,32 @@ +package net.crankedpvp.events.game.tasks; + +import net.crankedpvp.events.game.MiniGame; +import net.crankedpvp.events.game.MiniGameState; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.scheduler.BukkitRunnable; + +public class SpectatorTeleportBackTask extends BukkitRunnable { + + private final MiniGame game; + + public SpectatorTeleportBackTask(MiniGame game) { + this.game = game; + } + + @Override + public void run() { + if (this.game.getMiniGameState() == MiniGameState.NOT_STARTED) { + this.cancel(); + return; + } + + this.game.getSpectators().forEach(spectator -> { + if (spectator.getPlayer() == null) { + return; + } + if (!spectator.getPlayer().getWorld().getName().equals(this.game.getGameWorld().getName())) return; + if (this.game.getSpawnLocation().distance(spectator.getPlayer().getLocation()) > 200) + spectator.getPlayer().teleport(this.game.getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + }); + } +} \ No newline at end of file diff --git a/Events/src/main/java/net/crankedpvp/events/game/tasks/SpleefDeathCheckTask.java b/Events/src/main/java/net/crankedpvp/events/game/tasks/SpleefDeathCheckTask.java new file mode 100644 index 0000000..34333ca --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/tasks/SpleefDeathCheckTask.java @@ -0,0 +1,34 @@ +package net.crankedpvp.events.game.tasks; + +import lombok.AllArgsConstructor; +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.games.SpleefMiniGame; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +@AllArgsConstructor +public class SpleefDeathCheckTask extends BukkitRunnable { + + private final SpleefMiniGame miniGame; + + + @Override + public void run() { + if (this.miniGame.getMiniGameState() != MiniGameState.IN_PROGRESS) { + this.cancel(); + return; + } + + this.miniGame.getParticipants().forEach((uuid, spleefPlayer) -> { + if (isPlayerInWater(spleefPlayer.getPlayer())) { + this.miniGame.leaveMiniGame(spleefPlayer.getPlayer()); + } + }); + } + + private boolean isPlayerInWater(Player spleefPlayer) { + Material material = spleefPlayer.getLocation().getBlock().getType(); + return material == Material.WATER || material == Material.STATIONARY_WATER; + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/game/tasks/SumoDeathCheckTask.java b/Events/src/main/java/net/crankedpvp/events/game/tasks/SumoDeathCheckTask.java new file mode 100644 index 0000000..0202504 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/tasks/SumoDeathCheckTask.java @@ -0,0 +1,41 @@ +package net.crankedpvp.events.game.tasks; + +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.games.SumoMiniGame; +import net.crankedpvp.events.game.players.SumoPlayer; +import org.bukkit.Material; +import org.bukkit.scheduler.BukkitRunnable; + +public class SumoDeathCheckTask extends BukkitRunnable { + + private final SumoMiniGame miniGame; + + public SumoDeathCheckTask(SumoMiniGame miniGame) { + this.miniGame = miniGame; + } + + @Override + public void run() { + if (this.miniGame.getMiniGameState() != MiniGameState.IN_PROGRESS) { + this.cancel(); + return; + } + + if (this.miniGame.getDuelPlayers().getLeft() == null || miniGame.getDuelPlayers().getRight() == null) return; + if (this.miniGame.getDuelPlayers().getLeft().getPlayer() == null || miniGame.getDuelPlayers().getRight().getPlayer() == null) return; + if (!this.miniGame.getDuelPlayers().getLeft().getPlayer().isOnline() || !this.miniGame.getDuelPlayers().getLeft().getPlayer().isOnline()) return; + + if (this.isPlayerInWater(this.miniGame.getDuelPlayers().getLeft())) { + this.miniGame.choseWinner(this.miniGame.getDuelPlayers().getRight().getPlayer(), this.miniGame.getDuelPlayers().getLeft().getPlayer()); + } + + if (this.isPlayerInWater(this.miniGame.getDuelPlayers().getRight())) { + this.miniGame.choseWinner(this.miniGame.getDuelPlayers().getLeft().getPlayer(), this.miniGame.getDuelPlayers().getRight().getPlayer()); + } + } + + private boolean isPlayerInWater(SumoPlayer sumoPlayer) { + Material material = sumoPlayer.getPlayer().getLocation().getBlock().getType(); + return material == Material.WATER || material == Material.STATIONARY_WATER; + } +} \ No newline at end of file diff --git a/Events/src/main/java/net/crankedpvp/events/game/tasks/SumoStartDuelTask.java b/Events/src/main/java/net/crankedpvp/events/game/tasks/SumoStartDuelTask.java new file mode 100644 index 0000000..ca2d9b7 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/game/tasks/SumoStartDuelTask.java @@ -0,0 +1,56 @@ +package net.crankedpvp.events.game.tasks; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.games.SumoMiniGame; +import net.crankedpvp.events.game.players.SumoPlayer; +import net.crankedpvp.events.utils.Utils; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.scheduler.BukkitRunnable; + +public class SumoStartDuelTask extends BukkitRunnable { + + private final SumoMiniGame miniGame; + private int countdown; + private final SumoPlayer left; + private final SumoPlayer right; + + public SumoStartDuelTask(SumoMiniGame miniGame) { + this.miniGame = miniGame; + this.countdown = 5; + this.left = this.miniGame.getDuelPlayers().getLeft(); + this.right = this.miniGame.getDuelPlayers().getRight(); + } + + @Override + public void run() { + if (this.miniGame.getMiniGameState() != MiniGameState.IN_PROGRESS) { + this.cancel(); + return; + } + + if (this.miniGame.getDuelPlayers().getLeft() == null || miniGame.getDuelPlayers().getRight() == null) { + this.cancel(); + return; + } + + if (this.countdown <= 0) { + Utils.sendTitle(left.getPlayer(), CC.YellowB + "GO!", "", 10, 40, 10); + Utils.sendTitle(right.getPlayer(), CC.YellowB + "GO!", "", 10, 40, 10); + this.cancel(); + return; + } + + left.getPlayer().teleport(this.miniGame.getFightLocationOne(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + right.getPlayer().teleport(this.miniGame.getFightLocationTwo(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + + String color = countdown >= 4 ? CC.GreenB : CC.RedB; + + Utils.sendTitle(left.getPlayer(), color + countdown, "", 10, 40, 10); + Utils.sendTitle(right.getPlayer(), color + countdown, "", 10, 40, 10); + + this.countdown--; + } + + +} diff --git a/Events/src/main/java/net/crankedpvp/events/inventories/CerberusInventory.java b/Events/src/main/java/net/crankedpvp/events/inventories/CerberusInventory.java new file mode 100644 index 0000000..d1750d1 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/inventories/CerberusInventory.java @@ -0,0 +1,94 @@ +package net.crankedpvp.events.inventories; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class CerberusInventory { + + + @Getter + private ItemStack cerberusItemStack; + + @Getter + private final EventsPlugin plugin; + + private final Gui cerberusInventory; + + public Gui getUI() { + return this.cerberusInventory; + } + + public CerberusInventory(EventsPlugin plugin) { + this.plugin = plugin; + this.cerberusInventory = new Gui(3, "Cerberus"); + this.cerberusInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.buildCerberusItem(); + + ItemStack howToPlay = new ItemBuilder(Material.SIGN, "&b&lHow to Play?", + "" + ).colorize().build(); + + + ItemStack viewAllEvents = new ItemBuilder(Material.ARROW, "&d&lAll Events", + "&fClick here to view all of the", + "&fevents currently active on Cranked" + ).colorize().build(); + this.cerberusInventory.setItem(2, 5, new GuiItem(this.getCerberusItemStack())); + this.cerberusInventory.setItem(2, 3, new GuiItem(howToPlay)); + this.cerberusInventory.setItem(2, 7, new GuiItem(viewAllEvents, event -> { + event.getWhoClicked().closeInventory(); + if(event.getWhoClicked() instanceof Player) { + ((Player)event.getWhoClicked()).performCommand("events"); + } + })); + } + + private String getNextCerberusString() { + return this.plugin.getCerberusManager().isActive() ? "Now" : TimeUtils.formatMillisecondsInFull(this.plugin.getTimeUntilNextCerberus()); + } + + private String getActiveString() { + return this.plugin.getCerberusManager().isActive() ? "&a&lACTIVE" : "&c&lINACTIVE"; + } + + + public void updateInformationItem() { + this.buildCerberusItem(); + this.cerberusInventory.updateItem(2, 5, new GuiItem(this.getCerberusItemStack())); + } + + public void buildCerberusItem() { + this.cerberusItemStack = new ItemBuilder(Material.MONSTER_EGG, "&6&lCerberus &7(Information)", + "&fThe Cerberus is the most challenging", + "&fboss on Cranked. Group up with your", + "&ffaction to take it on. It is difficult!", + "", + "&6Information:", + " &f• Located in the &6Warzone", + " &f• Cerberus has &61,000 HP", + "", + "&6Rewards &7(Upon capture)", + " &f• 3x Cerberus Lootbags", + " &f• Gain &6+" + FactionData.Points.CERBERUS_KILLED.getPoints() + " &fFaction Points", + "", + "&6Cerberus:", + " &f• Event Status: " + this.getActiveString(), + " &f• Next Event: &a" + this.getNextCerberusString(), + " &f• Killed Last: &6" + this.getLastFactionWon() + ).colorize().build(); + } + + private String getLastFactionWon() { + return (this.plugin.getCerberusManager().getLastFactionCaptured() == null || !this.plugin.getCerberusManager().getLastFactionCaptured().isNormal()) ? "None" : this.plugin.getCerberusManager().getLastFactionCaptured().getTag(); + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/inventories/CitadelInventory.java b/Events/src/main/java/net/crankedpvp/events/inventories/CitadelInventory.java new file mode 100644 index 0000000..7c059b4 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/inventories/CitadelInventory.java @@ -0,0 +1,119 @@ +package net.crankedpvp.events.inventories; + + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class CitadelInventory { + + @Getter + private ItemStack citadelItemStack; + + @Getter + private final EventsPlugin plugin; + + private final Gui citadelInventory; + + public Gui getUI() { + return this.citadelInventory; + } + + public CitadelInventory(EventsPlugin plugin) { + this.plugin = plugin; + this.citadelInventory = new Gui(3, "Citadel"); + this.citadelInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.buildCitadelItem(); + + ItemStack howToPlay = new ItemBuilder(Material.SIGN, "&b&lHow to Play?", + "&fThis is a competitive event which will", + "&fstart twice per day, where factions compete", + "&fto control, and destroy the chest", + "", + "&fThe objective is to destroy the chest,", + "&fhowever you can &c&lONLY &fbreak the", + "&fchest if your faction is the only faction", + "&finside of the capture zone which surrounds", + "&fthe dead mans chest.", + "", + "&fYour faction must work together to clear", + "&fenemy players from the capture zone before", + "&fyou can attempt to break the chest." + ).colorize().build(); + + + ItemStack viewAllEvents = new ItemBuilder(Material.ARROW, "&d&lAll Events", + "&fClick here to view all of the", + "&fevents currently active on Cranked" + ).colorize().build(); + this.citadelInventory.setItem(2, 5, new GuiItem(this.getCitadelItemStack())); + this.citadelInventory.setItem(2, 3, new GuiItem(howToPlay)); + this.citadelInventory.setItem(2, 7, new GuiItem(viewAllEvents, event -> { + event.getWhoClicked().closeInventory(); + if(event.getWhoClicked() instanceof Player) { + ((Player)event.getWhoClicked()).performCommand("events"); + } + })); + } + + private String getNextCitadelString() { + return this.plugin.getCitadelManager().isActive() ? "Now" : TimeUtils.formatMillisecondsInFull(this.plugin.getTimeUntilNextCitadel()); + } + + private String getActiveString() { + return this.plugin.getCitadelManager().isActive() ? "&a&lACTIVE" : "&c&lINACTIVE"; + } + + + public void updateInformationItem() { + this.buildCitadelItem(); + this.citadelInventory.updateItem(2, 5, new GuiItem(this.getCitadelItemStack())); + } + + public void buildCitadelItem() { + this.citadelItemStack = new ItemBuilder(Material.BEACON, "&e&lCitadel &7(Information)", + "&fOne of the most competitive events on", + "&fCranked. Similar to a KOTH, team up with", + "&fyour faction to take control of the capture", + "&fzone located at /warp citadel.", + "", + "&eInformation:", + " &f• Located at &e/warp citadel", + " &f• Capture Time is &e10 Minutes", + " &f• Ender Pearls are &cdisabled &fat this event", + " &f• Enchants are &cdisabled &fat this event", + " &f• Masks are &cdisabled &fat this event", + " &f• Pets are &cdisabled &fat this event", + " &f• Star Items are &cdisabled &fat this event", + " &f• Armor Sets are &cdisabled &fat this event", + " &f• Bard Sets are &aenabled &fat this event", + "", + "&eRewards &7(Upon capture)", + " &f• 5x Citadel Lootbags", + " &f• Gain &e+" + FactionData.Points.CITADEL_CAPTURE.getPoints() + " &fFaction Points", + "", + "&eRewards &7(Until next capture)", + " &f• Grinding EXP Multiplier &7(2.25x)", + " &f• Underworld EXP Multiplier &7(1.25x)", + " &f• Underworld Chest Loot Multiplier &7(1.25x)", + "", + "&eCitadel:", + " &f• Event Status: " + this.getActiveString(), + " &f• Next Event: &a" + this.getNextCitadelString(), + " &f• Captured Last: &e" + this.getLastFactionWon() + ).colorize().build(); + } + + private String getLastFactionWon() { + return (this.plugin.getCitadelManager().getLastFactionCaptured() == null || !this.plugin.getCitadelManager().getLastFactionCaptured().isNormal()) ? "None" : this.plugin.getCitadelManager().getLastFactionCaptured().getTag(); + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/inventories/EventsInventory.java b/Events/src/main/java/net/crankedpvp/events/inventories/EventsInventory.java new file mode 100644 index 0000000..185deee --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/inventories/EventsInventory.java @@ -0,0 +1,130 @@ +package net.crankedpvp.events.inventories; + +import com.golfing8.kore.FactionsKore; +import com.golfing8.kore.feature.KothFeature; +import com.golfing8.kore.object.Koth; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.deadmanschest.DeadmansChestPlugin; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.utils.item.ItemBuilder; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class EventsInventory { + + private EventsPlugin plugin; + + @Getter + private final Gui newEventsUI; + + public EventsInventory(EventsPlugin plugin) { + this.plugin = plugin; + this.newEventsUI = new Gui(1, "Cranked Events"); + this.newEventsUI.setDefaultClickAction(event -> event.setCancelled(true)); + + this.addAndScheduleCerberusItemStack(); + this.addAndScheduleWarpKothItemStack(); + this.addAndScheduleCitadelItemStack(); + this.addAndScheduleDeadMansChestItemStack(); + this.addKothItemStack(); + + } + + private void addAndScheduleDeadMansChestItemStack() { + this.newEventsUI.setItem(1, 3, new GuiItem(DeadmansChestPlugin.getInstance().getDeadmansChestInventory().getDeadMansChestItemStack(), event -> { + event.getWhoClicked().closeInventory(); + DeadmansChestPlugin.getInstance().getDeadmansChestInventory().getUI().open(event.getWhoClicked()); + })); + Bukkit.getScheduler().runTaskTimer(plugin, () -> this.newEventsUI.updateItem(1, 3, new GuiItem(DeadmansChestPlugin.getInstance().getDeadmansChestInventory().getDeadMansChestItemStack(), event -> { + event.getWhoClicked().closeInventory(); + DeadmansChestPlugin.getInstance().getDeadmansChestInventory().getUI().open(event.getWhoClicked()); + })), 20L, 20L); + } + + private void addAndScheduleCitadelItemStack() { + this.newEventsUI.setItem(1, 5, new GuiItem(EventsPlugin.getInstance().getCitadelInventory().getCitadelItemStack(), event -> { + event.getWhoClicked().closeInventory(); + EventsPlugin.getInstance().getCitadelInventory().getUI().open(event.getWhoClicked()); + })); + Bukkit.getScheduler().runTaskTimer(plugin, () -> this.newEventsUI.updateItem(1, 5, new GuiItem(EventsPlugin.getInstance().getCitadelInventory().getCitadelItemStack(), event -> { + event.getWhoClicked().closeInventory(); + EventsPlugin.getInstance().getCitadelInventory().getUI().open(event.getWhoClicked()); + })), 20L, 20L); + } + + private void addAndScheduleWarpKothItemStack() { + this.newEventsUI.setItem(1, 1, new GuiItem(EventsPlugin.getInstance().getWarpKothInventory().getWarpKothItemstack(), event -> { + event.getWhoClicked().closeInventory(); + EventsPlugin.getInstance().getWarpKothInventory().getUI().open(event.getWhoClicked()); + })); + Bukkit.getScheduler().runTaskTimer(plugin, () -> this.newEventsUI.updateItem(1, 1, new GuiItem(EventsPlugin.getInstance().getWarpKothInventory().getWarpKothItemstack(), event -> { + event.getWhoClicked().closeInventory(); + EventsPlugin.getInstance().getWarpKothInventory().getUI().open(event.getWhoClicked()); + })), 20L, 20L); + } + + private void addAndScheduleCerberusItemStack() { + this.newEventsUI.setItem(1, 7, new GuiItem(EventsPlugin.getInstance().getCerberusInventory().getCerberusItemStack(), event -> { + event.getWhoClicked().closeInventory(); + EventsPlugin.getInstance().getCerberusInventory().getUI().open(event.getWhoClicked()); + })); + Bukkit.getScheduler().runTaskTimer(plugin, () -> this.newEventsUI.updateItem(1, 7, new GuiItem(EventsPlugin.getInstance().getCerberusInventory().getCerberusItemStack(), event -> { + event.getWhoClicked().closeInventory(); + EventsPlugin.getInstance().getCerberusInventory().getUI().open(event.getWhoClicked()); + })), 20L, 20L); + } + + private void addKothItemStack() { + this.newEventsUI.setItem(1, 9, new GuiItem(this.buildKothItemStack(), event -> { + event.getWhoClicked().closeInventory(); + if(event.getWhoClicked() instanceof Player) { + ((Player)event.getWhoClicked()).performCommand("koth gui"); + } + })); + } + + public void updateKothItem() { + this.newEventsUI.updateItem(1, 9, new GuiItem(this.buildKothItemStack(), event -> { + event.getWhoClicked().closeInventory(); + if(event.getWhoClicked() instanceof Player) { + ((Player)event.getWhoClicked()).performCommand("koth gui"); + } + })); + } + + private ItemStack buildKothItemStack() { + return new ItemBuilder(Material.WOOL, 1, DyeColor.RED.getWoolData(), "&c&lKing of the Hill", + "&fCapture a zone for a certain amount of", + "&ftime without leaving the zone to become", + "&fthe King of the Hill with your team.", + "", + "&cInformation:", + " &f• First player on the &cZone &fis the Capper", + " &f• Capper leaving the Zone &cresets &fprogress", + " &f• Multiple &cKOTH &flocations.", + "", + "&cRewards:", + " &f• 1x KOTH Lootbag", + " &f• 1x Random KOTH Piece", + " &f• 1x Gain &c+" + FactionData.Points.KOTH_CAPTURE.getPoints() + " &fFaction Points", + "", + "&cKoth Event", + " &f• Status: " + getKothIsActive(), + " &f• Koth Schedule: &cEvery 2 Hours" + ).colorize().build(); + } + + private String getKothIsActive() { + for(Koth koth : FactionsKore.get().getFeature(KothFeature.class).getKoths()) { + if(koth.isActive()) return "&a&lACTIVE &7(" + koth.getName() + "&7)"; + } + return "&c&lINACTIVE"; + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/inventories/LootPreviewUI.java b/Events/src/main/java/net/crankedpvp/events/inventories/LootPreviewUI.java new file mode 100644 index 0000000..0c64900 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/inventories/LootPreviewUI.java @@ -0,0 +1,39 @@ +package net.crankedpvp.events.inventories; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import lombok.SneakyThrows; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.MiniGame; +import net.crankedpvp.events.utils.Utils; +import net.crankedpvp.events.utils.item.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Optional; + +public class LootPreviewUI { + @Getter + private final PaginatedGui eventsUI; + + @SneakyThrows + public LootPreviewUI(EventsPlugin plugin, Player player, MiniGame miniGame) { + this.eventsUI = new PaginatedGui(1, 9, Utils.toNiceString(miniGame.getMiniGameType().name()) + " Loot Preview"); + + this.eventsUI.setDefaultClickAction(event -> event.setCancelled(true)); + /*Optional mysteryChest = Optional.of(miniGame.getMysteryChest().createClaimableItem(false)) ; + this.eventsUI.setItem(4, new GuiItem(mysteryChest.orElseThrow(() -> new Exception("Mystery Chest has not been found"))));*/ + + ItemStack homePage = new ItemBuilder(Material.BED).setName("&c&lMain Menu").addLore("&7Click to return to the main menu.").colorize().build(); + eventsUI.setItem(1, 1, new GuiItem(homePage, event -> { + MainEventsUI teamListGUI = new MainEventsUI(plugin, player); + teamListGUI.getEventsUI().open(player); + })); + + + } + + +} diff --git a/Events/src/main/java/net/crankedpvp/events/inventories/MainEventsUI.java b/Events/src/main/java/net/crankedpvp/events/inventories/MainEventsUI.java new file mode 100644 index 0000000..b57c62e --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/inventories/MainEventsUI.java @@ -0,0 +1,116 @@ +package net.crankedpvp.events.inventories; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.game.MiniGameState; +import net.crankedpvp.events.game.MiniGameType; +import net.crankedpvp.events.utils.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitTask; + +public class MainEventsUI { + + + + @Getter + private final PaginatedGui eventsUI; + + public MainEventsUI(EventsPlugin plugin, Player player) { + this.eventsUI = new PaginatedGui(3, 27, "Events Menu"); + this.eventsUI.setDefaultClickAction(event -> event.setCancelled(true)); + + BukkitTask runnable = Bukkit.getScheduler().runTaskTimer(plugin, () -> eventsUI.updateItem(4, new GuiItem( + new ItemBuilder(Material.CHEST) + .setName("&6&lAstro Events Menu") + .addLore( + "&7In this menu you can find out when the next event", + "&7will happen as well as which event is currently active", + "", + "&6* &7Next event: &6" + Utils.toNiceString(plugin.getMiniGameManager().getNextMiniGame().name()), + "&6* &7Next event will happen in &6" + plugin.getMiniGameManager().getTimeUntilNextMiniGame() + ) + .colorize() + .build())), 20L, 20L); + + this.eventsUI.setCloseGuiAction(event -> runnable.cancel()); + + plugin.getMiniGameRegister().getMiniGames().forEach(((miniGameType, miniGame) -> { + + ItemStack itemStack; + if (miniGame.getMiniGameState() != MiniGameState.NOT_STARTED) { + + itemStack = new ItemBuilder(miniGame.getGuiMaterial()) + .setName("&a&l" + Utils.toNiceString(miniGameType.name() + " Event")) + .addLore("&a* &7Event state: &a\"" + Utils.toNiceString(miniGame.getMiniGameState().name()), + "&a* &7Min/Max players: &a" + miniGame.getMinPlayers() + "&8/&a" + miniGame.getMaxPlayers(), + "&a* &7Amount of participants: &a" + miniGame.getParticipants().size(), + "", + "&7&nLeft-Click&7 to join the " + Utils.toNiceString(miniGameType.name() + " Minigame!"), + "&7&nRight-Click&7 to preview the loot.") + .colorize() + .build(); + + + } else { + itemStack = new ItemBuilder(Material.BARRIER) + .setName("&a&l" + Utils.toNiceString(miniGameType.name() + " Event")) + .addLore("&cThis event is currently not running.", + "&cJoin the /discord and react to #events", + "&cto stay updated when we do event like these.", + "", + "&7&nRight-Click&7 to preview the loot.") + .colorize() + .build(); + } + + this.eventsUI.setItem(4, new GuiItem( + new ItemBuilder(Material.CHEST) + .setName("&6&lAstro Events Menu") + .addLore( + "&7In this menu you can find out when the next event", + "&7will happen as well as which event is currently active", + "", + "&6* &7Next event: &6" + Utils.toNiceString(plugin.getMiniGameManager().getNextMiniGame().name()), + "&6* &7Next event will happen in &6" + plugin.getMiniGameManager().getTimeUntilNextMiniGame() + ) + .colorize() + .build() + )); + + if (miniGameType == MiniGameType.PARKOUR) { + this.eventsUI.setItem(23, new GuiItem(itemStack, event -> { + if (event.isLeftClick()) { + if (miniGame.getMiniGameState() == MiniGameState.STARTING) + miniGame.joinMiniGame(player); + } else { + LootPreviewUI lootPreviewUI = new LootPreviewUI(plugin, player, miniGame); + lootPreviewUI.getEventsUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2, 2); + } + })); + } else { + this.eventsUI.setItem(21, new GuiItem(itemStack, event -> { + if (event.isLeftClick()) { + if (miniGame.getMiniGameState() == MiniGameState.STARTING) + miniGame.joinMiniGame(player); + } else { + LootPreviewUI lootPreviewUI = new LootPreviewUI(plugin, player, miniGame); + lootPreviewUI.getEventsUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2, 2); + } + + })); + } + })); + } + + + +} diff --git a/Events/src/main/java/net/crankedpvp/events/inventories/WarpKothInventory.java b/Events/src/main/java/net/crankedpvp/events/inventories/WarpKothInventory.java new file mode 100644 index 0000000..68df80a --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/inventories/WarpKothInventory.java @@ -0,0 +1,106 @@ +package net.crankedpvp.events.inventories; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class WarpKothInventory { + + @Getter + private ItemStack warpKothItemstack; + + @Getter + private final EventsPlugin plugin; + + private final Gui warpKothInventory; + + public Gui getUI() { + return this.warpKothInventory; + } + + public WarpKothInventory(EventsPlugin plugin) { + this.plugin = plugin; + this.warpKothInventory = new Gui(3, "Warp Koth"); + this.warpKothInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.buildWarpKothItem(); + + ItemStack howToPlay = new ItemBuilder(Material.SIGN, "&b&lHow to Play?", + "&fThis is a competitive event where", + "&fplayers all meet at &c/warp koth &fin", + "&fattempt to control the point.", + "", + "&fThe objective is to take control of", + "&fthe capture zone for the required amount", + "&fof time. However, there are extra rules", + "&fat the /warp koth.", + "", + "&fFor example, you will only get one life.", + "&fIf you die at /warp koth, you cannot return", + "&fto the warp until the next /warp koth starts.", + "&fHowever, if you die, you will not lose any items." + ).colorize().build(); + + + ItemStack viewAllEvents = new ItemBuilder(Material.ARROW, "&d&lAll Events", + "&fClick here to view all of the", + "&fevents currently active on Cranked" + ).colorize().build(); + this.warpKothInventory.setItem(2, 5, new GuiItem(this.getWarpKothItemstack())); + this.warpKothInventory.setItem(2, 3, new GuiItem(howToPlay)); + this.warpKothInventory.setItem(2, 7, new GuiItem(viewAllEvents, event -> { + event.getWhoClicked().closeInventory(); + if(event.getWhoClicked() instanceof Player) { + ((Player)event.getWhoClicked()).performCommand("events"); + } + })); + } + + private String getNextWarpKothString() { + return this.plugin.getWarpKothManager().isActive() ? "Now" : TimeUtils.formatMillisecondsInFull(this.plugin.getTimeUntilNextWarpKoth()); + } + + private String getActiveString() { + return this.plugin.getWarpKothManager().isActive() ? "&a&lACTIVE" : "&c&lINACTIVE"; + } + + + public void updateInformationItem() { + this.buildWarpKothItem(); + this.warpKothInventory.updateItem(2, 5, new GuiItem(this.getWarpKothItemstack())); + } + + public void buildWarpKothItem() { + this.warpKothItemstack = new ItemBuilder(Material.ENDER_PORTAL_FRAME, "&5&lWarp Koth &7(Information)", + "&fThis is a KOTH that runs in an alternate", + "&fworld. Keep inventory is enabled, but if", + "&fyou die, you cannot return until the next koth", + "", + "&5Information:", + " &f• Located at &5/warp koth", + " &f• Limited to &51 Life", + " &f• Keep Inventory Enabled", + "", + "&5Rewards &7(Upon capture)", + " &f• 1x Warp Koth Lootbag", + " &f• Gain &5+" + FactionData.Points.WARP_KOTH_CAPTURE.getPoints() + " &fFaction Points", + "", + "&5Warp Koth:", + " &f• Event Status: " + this.getActiveString(), + " &f• Next Event: &a" + this.getNextWarpKothString(), + " &f• Captured Last: &5" + this.getLastFactionWon() + ).colorize().build(); + } + + private String getLastFactionWon() { + return (this.plugin.getWarpKothManager().getLastFactionCaptured() == null || !this.plugin.getWarpKothManager().getLastFactionCaptured().isNormal()) ? "None" : this.plugin.getWarpKothManager().getLastFactionCaptured().getTag(); + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/listeners/CerberusDeathListener.java b/Events/src/main/java/net/crankedpvp/events/listeners/CerberusDeathListener.java new file mode 100644 index 0000000..c6499af --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/listeners/CerberusDeathListener.java @@ -0,0 +1,53 @@ +package net.crankedpvp.events.listeners; + +import com.massivecraft.factions.Faction; +import net.crankedpvp.bosses.bosses.Cerberus; +import net.crankedpvp.bosses.events.BossDeathEvent; +import net.crankedpvp.bosses.struct.Boss; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.pvptop.PvPTopAPI; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class CerberusDeathListener implements Listener { + + private final EventsPlugin plugin; + public CerberusDeathListener(EventsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onBossDeath(BossDeathEvent event) { + if(event.getEntity() == null) return; + + Boss boss = event.getBoss(); + if(!(boss instanceof Cerberus)) return; + + if(event.getKiller() == null) { + event.setCancelled(true); + return; + } + + Player killer = event.getKiller(); + Faction killerFaction = FactionUtils.getFaction(killer); + this.plugin.getCerberusManager().setLastFactionCaptured(killerFaction); + this.plugin.getCerberusManager().setActive(false); + + for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.ZOMBIE_DEATH, 3.0f, 2.0f); + onlinePlayer.sendMessage(CC.translate("")); + onlinePlayer.sendMessage(CC.translate("&6&lCerberus has been Slain")); + onlinePlayer.sendMessage(CC.translate(" &f• Slain By: &6" + killer.getName())); + onlinePlayer.sendMessage(CC.translate(" &f• Killers Faction: &6" + killerFaction.getTag())); + onlinePlayer.sendMessage(CC.translate(" &f• Faction Points: &6" + FactionData.Points.CERBERUS_KILLED.getPoints() + " Gained")); + onlinePlayer.sendMessage(CC.translate("")); + } + PvPTopAPI.getFactionData(killer).addPoint(FactionData.Points.CERBERUS_KILLED); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/listeners/KothStateChangeListener.java b/Events/src/main/java/net/crankedpvp/events/listeners/KothStateChangeListener.java new file mode 100644 index 0000000..6567bd7 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/listeners/KothStateChangeListener.java @@ -0,0 +1,65 @@ +package net.crankedpvp.events.listeners; + +import com.golfing8.kore.event.KothCaptureEvent; +import com.golfing8.kore.event.KothEndEvent; +import com.golfing8.kore.event.KothStartEvent; +import com.golfing8.kore.object.Koth; +import com.massivecraft.factions.Faction; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +public class KothStateChangeListener implements Listener { + + private final EventsPlugin plugin; + public KothStateChangeListener(EventsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void checkKothStart(KothStartEvent event) { + if(event.getKoth() == null) return; + if(event.getKoth().getName().equals("Citadel")) { + this.plugin.getCitadelManager().setActive(true); + return; + } + if(this.plugin.getWarpKothManager().isWarpKoth(event.getKoth())) { + // FactionsKore marks the KOTH active after firing its start event. + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> { + boolean active = event.getKoth().isActive(); + if (this.plugin.getWarpKothManager().isActive() != active) { + this.plugin.getWarpKothManager().setActive(active); + } + }, 1L); + return; + } + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> this.plugin.getEventsInventory().updateKothItem(), 5L); + } + + @EventHandler(priority = EventPriority.HIGH) + public void checkKothEnd(KothEndEvent event) { + if(event.getKoth() == null) return; + if(event.getKoth().getName().equals("Citadel")) { + this.plugin.getCitadelManager().setActive(false); + return; + } + if(this.plugin.getWarpKothManager().isWarpKoth(event.getKoth())) { + this.plugin.getWarpKothManager().setActive(false); + return; + } + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> this.plugin.getEventsInventory().updateKothItem(), 5L); + } + + @EventHandler + public void onKothCapture(KothCaptureEvent event) { + if(event.getPlayerCapper() == null) return; + Faction faction = FactionUtils.getFaction(event.getPlayerCapper()); + if(this.plugin.getWarpKothManager().isWarpKoth(event.getKoth())) { + this.plugin.getWarpKothManager().setLastFactionCaptured(faction); + } + + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/listeners/PlayerDeathListener.java b/Events/src/main/java/net/crankedpvp/events/listeners/PlayerDeathListener.java new file mode 100644 index 0000000..d5d74ff --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/listeners/PlayerDeathListener.java @@ -0,0 +1,41 @@ +package net.crankedpvp.events.listeners; + +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.EventsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.PlayerDeathEvent; + +public class PlayerDeathListener implements Listener { + + private final EventsPlugin plugin; + public PlayerDeathListener(EventsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void playerDeath(PlayerDeathEvent event) { + if(event.getEntity() == null) return; + if(!event.getEntity().getWorld().getName().equals(EventsPlugin.WARP_KOTH_WORLD_NAME)) return; + event.getEntity().sendMessage(CC.translate("&5&lWarp Koth &8" + Arrow.arrow() + " &cYou have been death banned from /warp koth until the next event")); + this.plugin.getWarpKothManager().getRecentlyDied().add(event.getEntity()); + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> this.plugin.getWarpKothManager().getRecentlyDied().remove(event.getEntity()), 3 * 20L); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void playerTakeDamageFromVoid(EntityDamageEvent event) { + if(event.getEntity() == null || !(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if(!player.getWorld().equals(Bukkit.getWorld(EventsPlugin.WARP_KOTH_WORLD_NAME))) return; + if(!event.getCause().equals(EntityDamageEvent.DamageCause.VOID)) return; + event.setCancelled(true); + player.sendMessage(CC.translate("&5&lWarp Koth &8" + Arrow.arrow() + " &cYou have been death banned from /warp koth until the next event")); + this.plugin.getWarpKothManager().getRecentlyDied().add(player); + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> this.plugin.getWarpKothManager().getRecentlyDied().remove(player), 3 * 20L); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/listeners/PlayerTeleportListener.java b/Events/src/main/java/net/crankedpvp/events/listeners/PlayerTeleportListener.java new file mode 100644 index 0000000..b08410b --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/listeners/PlayerTeleportListener.java @@ -0,0 +1,60 @@ +package net.crankedpvp.events.listeners; + +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.EventsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerTeleportEvent; + +public class PlayerTeleportListener implements Listener { + + private final EventsPlugin plugin; + public PlayerTeleportListener(EventsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void playerTeleport(PlayerTeleportEvent event) { + if(event.getFrom() == null || event.getTo() == null) return; + if(event.getCause().equals(PlayerTeleportEvent.TeleportCause.ENDER_PEARL)) return; + + + if(!event.getFrom().getWorld().getName().equals(EventsPlugin.WARP_KOTH_WORLD_NAME) && event.getTo().getWorld().getName().equals(EventsPlugin.WARP_KOTH_WORLD_NAME)) { + + if(!this.plugin.getWarpKothManager().isActive()) { + if(!event.getPlayer().isOp()) { + event.setCancelled(true); + event.getPlayer().sendMessage(CC.translate("&5&lWarp Koth &8" + Arrow.arrow() + " &cThis koth is not currently active")); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ANVIL_LAND, 1.0f, 1.0f); + } else { + event.getPlayer().sendMessage(CC.translate("&5&lWarp Koth &8" + Arrow.arrow() + " &cKoth is not active, but OPs bypass!")); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + return; + } + + if(this.plugin.getWarpKothManager().isPlayerBannedFromWarpKoth(event.getPlayer())) { + if(!event.getPlayer().isOp()) { + event.setCancelled(true); + event.getPlayer().sendMessage(CC.translate("&5&lWarp Koth &8" + Arrow.arrow() + " &cYou are currently death banned from this warp!")); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ANVIL_LAND, 1.0f, 1.0f); + } else { + event.getPlayer().sendMessage(CC.translate("&5&lWarp Koth &8" + Arrow.arrow() + " &cYou are deathbanned, but OPs bypass!")); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + return; + } + this.plugin.getWarpKothManager().banPlayerFromWarpKoth(event.getPlayer()); + return; + } + + if(event.getFrom().getWorld().getName().equals(EventsPlugin.WARP_KOTH_WORLD_NAME) && !event.getTo().getWorld().getName().equals(EventsPlugin.WARP_KOTH_WORLD_NAME)) { + if(this.plugin.getWarpKothManager().getRecentlyDied().contains(event.getPlayer())) return; + this.plugin.getWarpKothManager().unbanPlayerFromWarpKoth(event.getPlayer()); + } + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/managers/CerberusManager.java b/Events/src/main/java/net/crankedpvp/events/managers/CerberusManager.java new file mode 100644 index 0000000..addac38 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/managers/CerberusManager.java @@ -0,0 +1,45 @@ +package net.crankedpvp.events.managers; + +import com.massivecraft.factions.Faction; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.EventsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +public class CerberusManager { + + private final static Location spawnLocation = new Location(Bukkit.getWorld("world_nether"), -8, 36, -124); + private final EventsPlugin plugin; + public CerberusManager(EventsPlugin plugin) { + this.plugin = plugin; + this.active = false; + } + + @Getter + @Setter + private Faction lastFactionCaptured; + + @Getter @Setter + private boolean active; + + + public void startEvent() { + if(this.isActive()) return; + BossPlugin.getInstance().getBossRegister().getBossFromID("cerberus").spawnBoss(spawnLocation); + this.setActive(true); + for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.ENDERDRAGON_GROWL, 2.0f, 2.0f); + onlinePlayer.sendMessage(CC.translate("")); + onlinePlayer.sendMessage(CC.translate("&6&lCerberus Boss")); + onlinePlayer.sendMessage(CC.translate("&fThe &6Cerberus &fhas just spawned")); + onlinePlayer.sendMessage(CC.translate("&fin the &6Nether &fat &6x: -8, y: 36, z: -124")); + onlinePlayer.sendMessage(CC.translate("")); + } + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/managers/CitadelManager.java b/Events/src/main/java/net/crankedpvp/events/managers/CitadelManager.java new file mode 100644 index 0000000..6354555 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/managers/CitadelManager.java @@ -0,0 +1,33 @@ +package net.crankedpvp.events.managers; + +import com.massivecraft.factions.Faction; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.bosses.BossPlugin; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.EventsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +public class CitadelManager { + + private final EventsPlugin plugin; + public CitadelManager(EventsPlugin plugin) { + this.plugin = plugin; + this.active = false; + } + + @Getter @Setter + private Faction lastFactionCaptured; + + @Getter @Setter + private boolean active; + + public void startEvent() { + if(this.isActive()) return; + //KothFeature kothFeature = FactionsKore.get().getFeature(KothFeature.class); + //kothFeature.startKoth(kothFeature.getKoth("Citadel")); + //this.setActive(true); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/managers/WarpKothManager.java b/Events/src/main/java/net/crankedpvp/events/managers/WarpKothManager.java new file mode 100644 index 0000000..843aa40 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/managers/WarpKothManager.java @@ -0,0 +1,133 @@ +package net.crankedpvp.events.managers; + +import com.golfing8.kore.FactionsKore; +import com.golfing8.kore.feature.KothFeature; +import com.golfing8.kore.object.Koth; +import com.massivecraft.factions.Faction; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.EventsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.stream.Collectors; + +public class WarpKothManager { + + private final EventsPlugin plugin; + public WarpKothManager(EventsPlugin plugin) { + this.plugin = plugin; + this.active = false; + this.blockedIPs = new ArrayList<>(); + this.blockedPlayers = new ArrayList<>(); + } + + @Getter + private final List recentlyDied = new ArrayList<>(); + + private final List blockedIPs; + private final List blockedPlayers; + + public void banPlayerFromWarpKoth(Player player) { + this.blockedIPs.add(player.getAddress().getAddress().getHostAddress()); + this.blockedPlayers.add(player.getUniqueId()); + } + + public void unbanPlayerFromWarpKoth(Player player) { + this.blockedIPs.remove(player.getAddress().getAddress().getHostAddress()); + this.blockedPlayers.remove(player.getUniqueId()); + } + + public boolean isPlayerBannedFromWarpKoth(Player player) { + return blockedIPs.contains(player.getAddress().getAddress().getHostAddress()) || blockedPlayers.contains(player.getUniqueId()); + } + + @Getter @Setter + private Faction lastFactionCaptured; + + @Getter + private boolean active; + + public void setActive(boolean active) { + this.active = active; + this.blockedIPs.clear(); + } + + + public void startEvent() { + if(this.isActive()) return; + FactionsKore kore = FactionsKore.get(); + KothFeature kothFeature = kore == null ? null : kore.getFeature(KothFeature.class); + if (kothFeature == null || !kothFeature.isOn()) { + this.plugin.getLogger().warning("Cannot start Warp KOTH: the FactionsKore KOTH feature is unavailable or disabled."); + return; + } + + String kothName = this.getKothName(); + Koth koth = kothFeature.getKoth(kothName); + if (koth == null) { + koth = kothFeature.getKoths().stream() + .filter(this::isWarpKoth) + .findFirst().orElse(null); + } + if (koth == null) { + String available = kothFeature.getKoths().stream() + .filter(Objects::nonNull) + .map(Koth::getName) + .collect(Collectors.joining(", ")); + this.plugin.getLogger().warning("Cannot start Warp KOTH: no FactionsKore KOTH named '" + kothName + + "'. Set WARP_KOTH_NAME in CrankedEvents/config.yml to your warp KOTH's name. Available KOTHs: " + + (available.isEmpty() ? "none" : available)); + return; + } + + Location first = koth.getAnchorOne(); + Location second = koth.getAnchorTwo(); + if (first == null || second == null || first.getWorld() == null || second.getWorld() == null + || !first.getWorld().equals(second.getWorld()) + || !first.getWorld().equals(Bukkit.getWorld(first.getWorld().getName()))) { + this.plugin.getLogger().warning("Cannot start Warp KOTH '" + koth.getName() + + "': configure both arena corners in the same loaded world in FactionsKore."); + return; + } + if (koth.isActive()) { + this.setActive(true); + return; + } + + kothFeature.startKoth(koth); + if (!koth.isActive()) { + this.setActive(false); + this.plugin.getLogger().warning("Warp KOTH '" + koth.getName() + "' did not start; its start may have been cancelled."); + return; + } + this.setActive(true); + + for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.ENDERDRAGON_GROWL, 2.0f, 2.0f); + onlinePlayer.sendMessage(CC.translate("")); + onlinePlayer.sendMessage(CC.translate("&5&lWarp Koth Event")); + onlinePlayer.sendMessage(CC.translate("&fA koth event has just started at")); + onlinePlayer.sendMessage(CC.translate("&5/warp koth&f. In this world, you")); + onlinePlayer.sendMessage(CC.translate("&fonly get &51 life&f, but you do not")); + onlinePlayer.sendMessage(CC.translate("&flose any items when you die!")); + onlinePlayer.sendMessage(CC.translate("")); + } + } + + public String getKothName() { + return this.plugin.getConfig().getString("WARP_KOTH_NAME", "End").trim(); + } + + public boolean isWarpKoth(Koth koth) { + return koth != null && this.getKothName().equalsIgnoreCase(koth.getName()); + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextCerberusTimerTask.java b/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextCerberusTimerTask.java new file mode 100644 index 0000000..a60fed9 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextCerberusTimerTask.java @@ -0,0 +1,26 @@ +package net.crankedpvp.events.tasks; + +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.inventories.CerberusInventory; +import org.bukkit.scheduler.BukkitRunnable; + +public class UpdateNextCerberusTimerTask extends BukkitRunnable { + + private final CerberusInventory cerberusInventory; + private final EventsPlugin plugin; + + public UpdateNextCerberusTimerTask(EventsPlugin plugin) { + this.plugin = plugin; + this.cerberusInventory = plugin.getCerberusInventory(); + } + + @Override + public void run() { + if(this.plugin.getTimeUntilNextCerberus() < -1000L) return; + if(this.plugin.getTimeUntilNextCerberus() <= 0L) { + this.plugin.getCerberusManager().startEvent(); + } + cerberusInventory.updateInformationItem(); + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextCitadelTimerTask.java b/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextCitadelTimerTask.java new file mode 100644 index 0000000..6f09de6 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextCitadelTimerTask.java @@ -0,0 +1,29 @@ +package net.crankedpvp.events.tasks; + +import com.golfing8.kore.FactionsKore; +import com.golfing8.kore.feature.KothFeature; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.inventories.CitadelInventory; +import org.bukkit.Bukkit; +import org.bukkit.scheduler.BukkitRunnable; + +public class UpdateNextCitadelTimerTask extends BukkitRunnable { + + private final CitadelInventory citadelInventory; + private final EventsPlugin plugin; + + public UpdateNextCitadelTimerTask(EventsPlugin plugin) { + this.plugin = plugin; + this.citadelInventory = plugin.getCitadelInventory(); + } + + @Override + public void run() { + if(this.plugin.getTimeUntilNextCitadel() < -1000L) return; + if(this.plugin.getTimeUntilNextCitadel() <= 0L) { + this.plugin.getCitadelManager().startEvent(); + } + citadelInventory.updateInformationItem(); + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextWarpKothTimerTask.java b/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextWarpKothTimerTask.java new file mode 100644 index 0000000..2362f00 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/tasks/UpdateNextWarpKothTimerTask.java @@ -0,0 +1,32 @@ +package net.crankedpvp.events.tasks; + +import com.golfing8.kore.FactionsKore; +import com.golfing8.kore.feature.KothFeature; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.events.EventsPlugin; +import net.crankedpvp.events.inventories.WarpKothInventory; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +public class UpdateNextWarpKothTimerTask extends BukkitRunnable { + + private final WarpKothInventory warpKothInventory; + private final EventsPlugin plugin; + + public UpdateNextWarpKothTimerTask(EventsPlugin plugin) { + this.plugin = plugin; + this.warpKothInventory = plugin.getWarpKothInventory(); + } + + @Override + public void run() { + if(this.plugin.getTimeUntilNextWarpKoth() < -1000L) return; + if(this.plugin.getTimeUntilNextWarpKoth() <= 0L) { + this.plugin.getWarpKothManager().startEvent(); + } + warpKothInventory.updateInformationItem(); + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/utils/BlockUtil.java b/Events/src/main/java/net/crankedpvp/events/utils/BlockUtil.java new file mode 100644 index 0000000..5274074 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/BlockUtil.java @@ -0,0 +1,41 @@ +package net.crankedpvp.events.utils; + +import net.minecraft.server.v1_8_R3.BlockPosition; +import net.minecraft.server.v1_8_R3.Blocks; +import net.minecraft.server.v1_8_R3.IBlockData; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; + +public final class BlockUtil { + + private final static IBlockData AIR = Blocks.AIR.getBlockData(); + + public static void setBlockFast(Block b, int blockId, byte data, boolean physics) { + setBlockFast(b.getWorld(), b.getX(), b.getY(), b.getZ(), blockId, data, physics); + } + + public static void setBlockFast(org.bukkit.World world, int x, int y, int z, int blockId, byte data, boolean physics) { + net.minecraft.server.v1_8_R3.World w = ((CraftWorld) world).getHandle(); + BlockPosition bp = new BlockPosition(x, y, z); + IBlockData ibd = net.minecraft.server.v1_8_R3.Block.getByCombinedId(blockId + (data << 12)); + w.setTypeAndData(bp, ibd, physics ? 3 : 2); + (w.getChunkAt(x >> 4, z >> 4)).a(bp, ibd); + } + + public static void setAir(Block b, boolean physics) { + setAir(b.getWorld(), b.getX(), b.getY(), b.getZ(), physics); + } + + public static void setAir(org.bukkit.World world, int x, int y, int z, boolean physics) { + BlockPosition position = new BlockPosition(x, y, z); + ((CraftWorld) world).getHandle().setTypeAndData(position, AIR, physics ? 3 : 2); + } + + public static void updatePhysics(org.bukkit.World world, int x, int y, int z) { + net.minecraft.server.v1_8_R3.World w = ((CraftWorld) world).getHandle(); + BlockPosition bp = new BlockPosition(x, y, z); + w.applyPhysics(bp, w.getType(bp).getBlock()); + } + + +} diff --git a/Events/src/main/java/net/crankedpvp/events/utils/Clickable.java b/Events/src/main/java/net/crankedpvp/events/utils/Clickable.java new file mode 100644 index 0000000..d299c40 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/Clickable.java @@ -0,0 +1,52 @@ +package net.crankedpvp.events.utils; + + +import net.md_5.bungee.api.chat.*; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + + +public class Clickable { + private final List components = new ArrayList<>(); + + public Clickable(String msg) { + TextComponent message = new TextComponent(msg); + this.components.add(message); + } + + public Clickable(String msg, String hoverMsg) { + this(msg, hoverMsg, ""); + } + + public Clickable(String msg, String hoverMsg, String clickString) { + add(msg, hoverMsg, clickString); + } + + public TextComponent add(String msg, String hoverMsg) { + return add(msg, hoverMsg, ""); + } + + public TextComponent add(String msg, String hoverMsg, String clickString) { + TextComponent message = new TextComponent(Utils.color(msg)); + if (hoverMsg != null && !hoverMsg.isEmpty()) + message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, (new ComponentBuilder(Utils.color(hoverMsg))).create())); + if (clickString != null && !clickString.isEmpty()) + message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, clickString)); + this.components.add(message); + return message; + } + + public void add(String message) { + this.components.add(new TextComponent(Utils.color(message))); + } + + public void sendToPlayer(Player player) { + player.spigot().sendMessage(this.asComponents()); + } + + public TextComponent[] asComponents() { + return this.components.toArray(new TextComponent[0]); + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/utils/Pair.java b/Events/src/main/java/net/crankedpvp/events/utils/Pair.java new file mode 100644 index 0000000..674b9c8 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/Pair.java @@ -0,0 +1,24 @@ +package net.crankedpvp.events.utils; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class Pair { + + private L left; + private R right; + + public boolean contains(L value) { + return left.equals(value) || right.equals(value); + } + + public void clear() { + this.setLeft(null); + this.setRight(null); + } +} + diff --git a/Events/src/main/java/net/crankedpvp/events/utils/PlayerInventoryContents.java b/Events/src/main/java/net/crankedpvp/events/utils/PlayerInventoryContents.java new file mode 100644 index 0000000..77c453a --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/PlayerInventoryContents.java @@ -0,0 +1,31 @@ +package net.crankedpvp.events.utils; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@AllArgsConstructor +@Getter +@Setter +public class PlayerInventoryContents { + + public ItemStack[] inventoryContents; + public ItemStack[] armorContents; + + public void restoreInventory(Player player) { + player.getInventory().setContents(inventoryContents); + } + + public void restoreArmor(Player player) { + player.getInventory().setArmorContents(armorContents); + } + + public void restore(Player player) { + restoreInventory(player); + restoreArmor(player); + player.updateInventory(); + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/utils/Utils.java b/Events/src/main/java/net/crankedpvp/events/utils/Utils.java new file mode 100644 index 0000000..d40bd24 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/Utils.java @@ -0,0 +1,144 @@ +package net.crankedpvp.events.utils; + +import net.minecraft.server.v1_8_R3.IChatBaseComponent; +import net.minecraft.server.v1_8_R3.PacketPlayOutChat; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; + +import java.lang.reflect.Constructor; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +public class Utils { + + public static String color(String string) { + char[] b = string.toCharArray(); + + for (int i = 0; i < b.length - 1; ++i) { + if (b[i] == '&' && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { + b[i] = 167; + b[i + 1] = Character.toLowerCase(b[i + 1]); + } + } + + return new String(b); + } + + public static List color(List stringList) { + stringList.replaceAll(Utils::color); + return stringList; + } + + public static String[] color(String[] stringArray) { + for (int i = 0; i < stringArray.length; i++) { + stringArray[i] = color(stringArray[i]); + } + return stringArray; + } + + public static T defaultIfNull(T val, T def) { + return val != null ? val : def; + } + + public static String defaultIfEmpty(String val, String def) { + return !val.isEmpty() ? val : def; + } + + public static String getTimeFromSecsToMins(long seconds) { + int mins = (int) seconds / 60; + int remainder = (int) seconds - mins * 60; + return mins + "m " + remainder + "s "; + } + + public static void sendActionBarMessage(Player player, String text) { + PacketPlayOutChat packet = new PacketPlayOutChat(IChatBaseComponent.ChatSerializer.a("{\"text\":\"" + text + "\"}"), (byte)2); + (((CraftPlayer)player).getHandle()).playerConnection.sendPacket(packet); + } + + public static String toNiceString(String string) { + string = ChatColor.stripColor(string).replace('_', ' ').toLowerCase(); + StringBuilder sb = new StringBuilder(); + + for(int i = 0; i < string.toCharArray().length; ++i) { + char c = string.toCharArray()[i]; + if (i > 0) { + char prev = string.toCharArray()[i - 1]; + if ((prev == ' ' || prev == '[' || prev == '(') && (i == string.toCharArray().length - 1 || c != 'x' || !Character.isDigit(string.toCharArray()[i + 1]))) { + c = Character.toUpperCase(c); + } + } else if (c != 'x' || !Character.isDigit(string.toCharArray()[i + 1])) { + c = Character.toUpperCase(c); + } + + sb.append(c); + } + + return sb.toString(); + } + + public static void sendTitle(Player player, String title, String subtitle, int fadeInTime, int showTime, int fadeOutTime) { + try { + Object chatTitle = Objects.requireNonNull(getNMSClass("IChatBaseComponent")).getDeclaredClasses()[0].getMethod("a", new Class[] { String.class }).invoke(null, "{\"text\": \"" + title + "\"}"); + Constructor titleConstructor = Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getConstructor(Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), + int.class, int.class, int.class); + Object packet = titleConstructor.newInstance(Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getDeclaredClasses()[0].getField("TITLE").get(null), chatTitle, + fadeInTime, showTime, fadeOutTime); + Object chatsTitle = Objects.requireNonNull(getNMSClass("IChatBaseComponent")).getDeclaredClasses()[0].getMethod("a", new Class[] { String.class }).invoke(null, "{\"text\": \"" + subtitle + "\"}"); + Constructor timingTitleConstructor = Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getConstructor(Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), + int.class, int.class, int.class); + Object timingPacket = timingTitleConstructor.newInstance(Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getDeclaredClasses()[0].getField("SUBTITLE").get(null), chatsTitle, + fadeInTime, showTime, fadeOutTime); + sendPacket(player, packet); + sendPacket(player, timingPacket); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void sendPacket(Player player, Object packet) { + try { + Object handle = player.getClass().getMethod("getHandle", new Class[0]).invoke(player); + Object playerConnection = handle.getClass().getField("playerConnection").get(handle); + playerConnection.getClass().getMethod("sendPacket", new Class[] { getNMSClass("Packet") }).invoke(playerConnection, packet); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Class getNMSClass(String name) { + try { + return Class.forName("net.minecraft.server." + + Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "." + name); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + public static boolean isInventoryEmpty(Player player) { + return Stream.of(player.getInventory().getContents()).allMatch(itemStack -> itemStack == null || itemStack.getType() == Material.AIR) && + Stream.of(player.getInventory().getArmorContents()).allMatch(itemStack -> itemStack == null || itemStack.getType() == Material.AIR); + } + + public static String getSecondsAsString(long seconds) { + int day = (int)TimeUnit.SECONDS.toDays(seconds); + long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24L); + long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toHours(seconds) * 60L; + long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toMinutes(seconds) * 60L; + if (day > 0) { + return day + "d " + hours + "h " + minute + "m " + second + "s"; + } + if (hours > 0L) { + return hours + "h " + minute + "m " + second + "s"; + } + if (minute > 0L) { + return minute + "m " + second + "s"; + } + return second + "s"; + } +} diff --git a/Events/src/main/java/net/crankedpvp/events/utils/configuration/AbstractConfig.java b/Events/src/main/java/net/crankedpvp/events/utils/configuration/AbstractConfig.java new file mode 100644 index 0000000..3b8c99f --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/configuration/AbstractConfig.java @@ -0,0 +1,107 @@ +package net.crankedpvp.events.utils.configuration; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class AbstractConfig { + + private final JavaPlugin plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + + public AbstractConfig(JavaPlugin plugin, String path) { + this.plugin = plugin; + this.path = path; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public void setupConfigFile() { + boolean copyDefaults = !configFile.exists(); + + this.saveDefaultConfig(); + config = YamlConfiguration.loadConfiguration(configFile); + + if (copyDefaults) this.copyDefaults(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path + "!"); + e.printStackTrace(); + } + return false; + } + + public void saveDefaultConfig() { + if (!configFile.exists()) { + InputStream defConfig = plugin.getResource(path); + if (defConfig != null) { + plugin.saveResource(path,false); + } else { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path); + e.printStackTrace(); + } + } + } + } + + + public boolean reloadConfig() { + boolean copyDefaults = !configFile.exists(); + + this.saveDefaultConfig(); + config = YamlConfiguration.loadConfiguration(configFile); + + if (copyDefaults) this.copyDefaults(); + + this.saveConfig(); + return this.loadConfigFromDisk(); + } + + public boolean loadConfigFromDisk() { + try { + config.load(configFile); + return true; + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path); + e.printStackTrace(); + } + return false; + } + + public void copyDefaults() { + InputStream defConfig = plugin.getResource(path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + public FileConfiguration getConfig() { + return config; + } + + public String getPath() { + return path; + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/utils/configuration/ConfigManager.java b/Events/src/main/java/net/crankedpvp/events/utils/configuration/ConfigManager.java new file mode 100644 index 0000000..8bdd222 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/configuration/ConfigManager.java @@ -0,0 +1,51 @@ +package net.crankedpvp.events.utils.configuration; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; + +public class ConfigManager { + + private final Map configs = new HashMap<>(); + + public ConfigManager(JavaPlugin plugin) { + for (ConfigFile configFile : ConfigFile.values()) { + AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName()); + configs.put(configFile, abstractConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AbstractConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AbstractConfig::reloadConfig); + } + + public AbstractConfig getAbstractConfig(ConfigFile configFile) { + return configs.get(configFile); + } + + public FileConfiguration getConfig(ConfigFile configFile) { + return getAbstractConfig(configFile).getConfig(); + } + + @Getter + @RequiredArgsConstructor + public enum ConfigFile { + PARKOUR("events/parkour.yml"), + SUMO("events/sumo.yml"), + SPLEEF("events/spleef.yml"), + LANGUAGE("language.yml") + ; + + private final String fileName; + + } + +} diff --git a/Events/src/main/java/net/crankedpvp/events/utils/configuration/ConfigParser.java b/Events/src/main/java/net/crankedpvp/events/utils/configuration/ConfigParser.java new file mode 100644 index 0000000..aa48cd3 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/configuration/ConfigParser.java @@ -0,0 +1,70 @@ +package net.crankedpvp.events.utils.configuration; + +import net.crankedpvp.events.utils.item.ItemBuilder; +import net.crankedpvp.events.utils.item.SkullUtils; +import org.apache.commons.lang.math.NumberUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public final class ConfigParser { + + public static ItemStack parseItem(ConfigurationSection itemSection) { + Material itemType = Material.matchMaterial(itemSection.getString("type")); + short data = (short) itemSection.getInt("data"); + ItemBuilder itemBuilder = new ItemBuilder(itemType, itemSection.getInt("amount", 1), data); + + if (itemSection.contains("name")) { + itemBuilder.setName(itemSection.getString("name")); + } + + if (itemSection.contains("lore")) { + itemBuilder.setLore(itemSection.getStringList("lore")); + } + + itemBuilder.addUnsafeEnchantments(parseEnchants(itemSection.getStringList("enchants"))); + itemBuilder.addItemFlags(itemSection.getStringList("flags")); + + if (itemSection.getBoolean("glowing")) { + itemBuilder.setGlowing(); + } + + if (itemSection.getBoolean("unbreakable")) { + itemBuilder.setUnbreakable(true); + } + + ItemStack item = itemBuilder.colorize().build(); + + if (itemSection.contains("skull-texture") && itemType == Material.SKULL_ITEM && data == 3) { + item = SkullUtils.getSkull(item, itemSection.getString("skull-texture")); + } + + return item; + } + + public static Map parseEnchants(List toParse) { + Map enchantments = new HashMap<>(); + for (String line : toParse) { + String[] separation = line.split(":"); + if (separation.length == 0) continue; + Enchantment enchant = Enchantment.getByName(separation[0].toUpperCase()); + if (enchant == null) { + Bukkit.getLogger().warning(separation[0] + " is an invalid enchantment. Here are the options: " + Arrays.stream(Enchantment.values()).map(Enchantment::getName).collect(Collectors.joining(", "))); + continue; + } + + int level = separation.length > 1 ? NumberUtils.toInt(separation[1], 1) : 1; + enchantments.put(enchant, level); + } + return enchantments; + } + +} \ No newline at end of file diff --git a/Events/src/main/java/net/crankedpvp/events/utils/item/ItemBuilder.java b/Events/src/main/java/net/crankedpvp/events/utils/item/ItemBuilder.java new file mode 100644 index 0000000..90efc07 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/item/ItemBuilder.java @@ -0,0 +1,267 @@ +package net.crankedpvp.events.utils.item; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import net.crankedpvp.events.utils.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.SkullMeta; + +public class ItemBuilder { + + private ItemMeta itemMeta; + private final ItemStack itemStack; + + public ItemBuilder(String material) { + this(Material.valueOf(material)); + } + + public ItemBuilder(Material material) { + this(material,1); + } + + public ItemBuilder(Material material, int amount) { + this(new ItemStack(material, amount)); + } + + public ItemBuilder(Material material, String name, String... lore) { + this(material, 1, (short) 0, name, lore); + } + + public ItemBuilder(Material material, String name, List lore) { + this(material, 1, (short) 0, name); + setLore(lore); + } + + public ItemBuilder(Material material, int amount, short durability) { + this(new ItemStack(material, amount, durability)); + } + + public ItemBuilder(Material material, int amount, short durability, String name, String... lore) { + this(new ItemStack(material, amount, durability)); + setName(name); + setLore(lore); + } + + public ItemBuilder(ItemBuilder itemBuilder) { + this.itemStack = itemBuilder.itemStack; + this.itemMeta = itemBuilder.itemMeta; + } + + public ItemBuilder(ConfigurationSection section) { + this(new ItemBuilder(section.getString("name")) + .setLore(section.getStringList("lore")) + .setDurability((short) section.getInt("damage")) + .setUnbreakable(section.getBoolean("unbreakable")) + ); + } + + public ItemBuilder(ItemStack itemStack) { + this.itemStack = itemStack; + this.itemMeta = itemStack.getItemMeta(); + } + + public ItemBuilder clone() { + return new ItemBuilder(build()); + } + + public ItemBuilder setMaterial(String material) { + itemStack.setType(Material.valueOf(material)); + return this; + } + + public ItemBuilder setMaterial(Material material) { + itemStack.setType(material); + return this; + } + + public ItemBuilder setDurability(short durability) { + itemStack.setDurability(durability); + return this; + } + + public ItemBuilder setName(String name) { + itemMeta.setDisplayName(name); + return this; + } + + public ItemBuilder addUnsafeEnchantment(Enchantment enchantment, int level) { + itemMeta.addEnchant(enchantment, level, true); + return this; + } + + public ItemBuilder addUnsafeEnchantments(Map enchantments) { + enchantments.forEach((enchantment, level) -> itemMeta.addEnchant(enchantment, level, true)); + return this; + } + + public ItemBuilder addEnchantment(Enchantment enchantment, int level) { + itemMeta.addEnchant(enchantment, level,false); + return this; + } + + public ItemBuilder addEnchantments(Map enchantments) { + enchantments.forEach((enchantment, level) -> itemMeta.addEnchant(enchantment, level, false)); + return this; + } + + public ItemBuilder removeEnchantment(Enchantment enchantment) { + itemMeta.removeEnchant(enchantment); + return this; + } + + public ItemBuilder removeEnchantments(Collection enchantments) { + enchantments.forEach(itemMeta::removeEnchant); + return this; + } + + public ItemBuilder setGlowing() { + if (!itemMeta.hasEnchants()) { + itemMeta.addEnchant(Enchantment.DURABILITY,1,true); + } + return addItemFlag(ItemFlag.HIDE_ENCHANTS); + } + + public ItemBuilder colorize() { + colorizeName(); + return colorizeLore(); + } + + public ItemBuilder colorizeLore() { + if (itemMeta.hasLore()) { + List lore = getItemMeta().getLore(); + lore.replaceAll(Utils::color); + return setLore(lore); + } + return this; + } + + public ItemBuilder colorizeName() { + if (itemMeta.hasDisplayName()) setName(Utils.color(getItemMeta().getDisplayName())); + return this; + } + + public ItemBuilder setUnbreakable(boolean unbreakable) { + itemMeta.spigot().setUnbreakable(unbreakable); + return this; + } + + public List getLore() { + return itemMeta.getLore(); + } + + public ItemBuilder setLore(String... lore) { + return setLore(Arrays.asList(lore)); + } + + public ItemBuilder setLore(List lore) { + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder removeLoreLine(String line) { + List lore = new ArrayList<>(itemMeta.getLore()); + lore.remove(line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder removeLoreLine(int index) { + if (index < 0) return this; + List lore = new ArrayList<>(itemMeta.getLore()); + if (index > lore.size()) return this; + lore.remove(index); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addLore(String ...lore) { + return addLore(Arrays.asList(lore)); + } + + public ItemBuilder addLore(List lore) { + lore.forEach(this::addLoreLine); + return this; + } + + public ItemBuilder addLoreLine(String line) { + List lore = itemMeta.hasLore() ? new ArrayList<>(itemMeta.getLore()) : new ArrayList<>(); + lore.add(line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addLoreLine(String line, int pos) { + List lore = new ArrayList<>(itemMeta.getLore()); + if (pos >= lore.size()) return this; + lore.set(pos, line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addItemFlags(List itemFlags) { + for (String itemFlagStr : itemFlags) { + try { + ItemFlag itemFlag = ItemFlag.valueOf(itemFlagStr); + addItemFlag(itemFlag); + } catch (IllegalArgumentException ignored) {} + } + return this; + } + + public ItemBuilder setItemFlags(List itemFlags) { + itemMeta.addItemFlags(itemFlags.toArray(new ItemFlag[0])); + return this; + } + + public ItemBuilder addItemFlag(ItemFlag itemFlag) { + itemMeta.addItemFlags(itemFlag); + return this; + } + + @SuppressWarnings("deprecation") + public ItemBuilder setColor(DyeColor color) { + itemStack.setDurability(color.getData()); + return this; + } + + public ItemBuilder setLeatherArmorColor(Color color) { + LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; + if (Bukkit.getItemFactory().isApplicable(leatherArmorMeta, itemStack)) { + leatherArmorMeta.setColor(color); + itemMeta = leatherArmorMeta; + } + return this; + } + + public ItemBuilder setSkullOwner(String owner) { + SkullMeta skullMeta = (SkullMeta) itemMeta; + if (Bukkit.getItemFactory().isApplicable(skullMeta, itemStack)) { + skullMeta.setOwner(owner); + itemMeta = skullMeta; + } + return this; + } + + public ItemMeta getItemMeta() { + return itemMeta; + } + + public ItemStack build() { + itemStack.setItemMeta(itemMeta); + return itemStack; + } + +} \ No newline at end of file diff --git a/Events/src/main/java/net/crankedpvp/events/utils/item/SkullUtils.java b/Events/src/main/java/net/crankedpvp/events/utils/item/SkullUtils.java new file mode 100644 index 0000000..d3d5eb8 --- /dev/null +++ b/Events/src/main/java/net/crankedpvp/events/utils/item/SkullUtils.java @@ -0,0 +1,64 @@ +package net.crankedpvp.events.utils.item; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.lang.reflect.Field; +import java.util.UUID; + +public class SkullUtils { + + private final static ItemStack DEFAULT_SKULL = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); + + public static ItemStack getSkullFromSkin(String skinURL) { + ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)3); + if (skinURL == null || skinURL.isEmpty()) + return skull; + SkullMeta skullMeta = (SkullMeta)skull.getItemMeta(); + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", Base64Coder.encodeString("{textures:{SKIN:{\"url\":\"http://textures.minecraft.net/texture/" + skinURL + "\"}}}"))); + Field profileField; + try { + profileField = skullMeta.getClass().getDeclaredField("profile"); + } catch (NoSuchFieldException|SecurityException e) { + e.printStackTrace(); + return null; + } + profileField.setAccessible(true); + try { + profileField.set(skullMeta, profile); + } catch (IllegalArgumentException|IllegalAccessException e) { + e.printStackTrace(); + } + skull.setItemMeta(skullMeta); + return skull; + } + + public static ItemStack getSkull(ItemStack item, String skullTexture) { + if (skullTexture == null) throw new IllegalStateException("Skull Texture cannot be null!"); + + NBTItem nbtItem = new NBTItem(item); + + NBTCompound skullOwnerCompound = nbtItem.addCompound("SkullOwner"); + + String uuid = UUID.randomUUID().toString(); + skullOwnerCompound.setString("Id", uuid); + + skullOwnerCompound.addCompound("Properties").getCompoundList("textures").addCompound().setString("Value", skullTexture); + + return nbtItem.getItem(); + } + + public static ItemStack getSkull(String skullTexture) { + if (skullTexture == null) throw new IllegalStateException("Skull Texture cannot be null!"); + + return getSkull(DEFAULT_SKULL, skullTexture); + } + +} diff --git a/Events/src/main/resources/config.yml b/Events/src/main/resources/config.yml new file mode 100644 index 0000000..c290330 --- /dev/null +++ b/Events/src/main/resources/config.yml @@ -0,0 +1,5 @@ +CITADEL_LAST_WON: 0 +WARP_KOTH_LAST_WON: 0 +# FactionsKore KOTH used for Warp KOTH events; capitalization is ignored. +WARP_KOTH_NAME: End +CERBERUS_LAST_WON: 0 diff --git a/Events/src/main/resources/events/parkour.yml b/Events/src/main/resources/events/parkour.yml new file mode 100644 index 0000000..e19c8c7 --- /dev/null +++ b/Events/src/main/resources/events/parkour.yml @@ -0,0 +1,67 @@ +minigame: + countdown-message: '&8(&4!&8) &7Parkour event starts in &4{time}' + checkpoint-reached-message: '&8(&4!&8) &7You have reached checkpoint &a#{number}' + win-message: '&8(&4!&8) &4{player}&4 has won the parkour event in &4{time}' + parkour-time-message: '&8(&a!&8) &7Parkour time: &a{time}' + parkour-confirm-leave-message: '&7Click to &a&lCONFIRM &7you would like to leave' + min-players: 1 + max-players: 16 + countdown-time: 60 + world: events_world + checkpoints: + '1': + x: 126.0 + y: 33.0 + z: 812.0 + yaw: 90.0 + pitch: 0.0 + '2': + x: 48.0 + y: 37.0 + z: 781.0 + yaw: 120.0 + pitch: 0.0 + '3': + x: 74.0 + y: 58.0 + z: 702.0 + yaw: -160.0 + pitch: 0.0 + '4': + x: 160.0 + y: 73.0 + z: 738.0 + yaw: 0.0 + pitch: 0.0 + '5': + x: 94.0 + y: 82.0 + z: 789.0 + yaw: 130.0 + pitch: 0.0 + spawn-location: + x: 168.5 + y: 18.0 + z: 755.5 + yaw: 48.0 + pitch: 0.0 + end-location: + x: 126.0 + y: 119.0 + z: 767.0 + rewards: + - 'give {player} stone 1' + - 'eco give {player} 10' + items: + checkpoint-item: + type: GOLD_PLATE + name: '&aTeleport to Last Checkpoint' + lore: + - '' + - '&7&oClick this to be sent to your, &7&omost recent checkpoint' + leave-item: + type: BARRIER + name: '&aLeave Parkour Event' + lore: + - '' + - '&7&oClick this to be sent to, &7&othe server spawn' \ No newline at end of file diff --git a/Events/src/main/resources/events/spleef.yml b/Events/src/main/resources/events/spleef.yml new file mode 100644 index 0000000..62d253c --- /dev/null +++ b/Events/src/main/resources/events/spleef.yml @@ -0,0 +1,44 @@ +minigame: + countdown-message: '&8(&4!&8) &7Spleef event starts in &4{time}' + win-message: '&8(&4!&8) &4{player}&4 has won the spleef event' + min-players: 2 + max-players: 16 + countdown-time: 60 + world: events_world + spawn-location: + x: 0.5 + y: 100.0 + z: 0.5 + yaw: 48.0 + pitch: 0.0 + platform-corners: + 1: + corner-one: + x: 0.5 + y: 100.0 + z: 0.5 + corner-two: + x: 0.5 + y: 100.0 + z: 0.5 + 2: + corner-one: + x: 0.5 + y: 100.0 + z: 0.5 + corner-two: + x: 0.5 + y: 100.0 + z: 0.5 + 3: + corner-one: + x: 0.5 + y: 100.0 + z: 0.5 + corner-two: + x: 0.5 + y: 100.0 + z: 0.5 + rewards: + - 'give {player} stone 1' + - 'eco give {player} 10' \ No newline at end of file diff --git a/Events/src/main/resources/events/sumo.yml b/Events/src/main/resources/events/sumo.yml new file mode 100644 index 0000000..c84a750 --- /dev/null +++ b/Events/src/main/resources/events/sumo.yml @@ -0,0 +1,28 @@ +minigame: + countdown-message: '&8(&4!&8) &7Sumo event starts in &4{time}' + win-message: '&8(&4!&8) &4{player}&4 has won the sumo event' + min-players: 2 + max-players: 16 + countdown-time: 60 + world: events_world + spawn-location: + x: 0.5 + y: 100.0 + z: 0.5 + yaw: 48.0 + pitch: 0.0 + fight-location-one: + x: 0.5 + y: 100.0 + z: 0.5 + yaw: 48.0 + pitch: 0.0 + fight-location-two: + x: 0.5 + y: 100.0 + z: 0.5 + yaw: 48.0 + pitch: 0.0 + rewards: + - 'give {player} stone 1' + - 'eco give {player} 10' \ No newline at end of file diff --git a/Events/src/main/resources/language.yml b/Events/src/main/resources/language.yml new file mode 100644 index 0000000..d27d551 --- /dev/null +++ b/Events/src/main/resources/language.yml @@ -0,0 +1,27 @@ +messages: + invalid-event-name: '&cInvalid event name' + events-help-message: + - '&7-- &aAstro Events &7--' + - '&astart &7 &8- &7starts an event' + - '&astop &7 &8- &7stops an event' + - '&alist &8- &7list of events' + parkour-help-message: + - '&7-- &aAstro Events &7--' + - '&aparkour join &8- &7teleport to the starting point' + - '&aparkour leave &8- &7leave the parkour event' + sumo-help-message: + - '&7-- &aAstro Events &7--' + - '&asumo join &8- &7teleport to the starting point' + - '&asumo leave &8- &7leave the sumo event' + event: + player-joined: '&6{player} &7Joined the {game} Event &8(&6{amount}&7/&6{max}&8)' + player-left: '&6{player} &7Left the {game} Event &8(&6{amount}&7/&6{max}&8)' + inventory-empty: '&8(&c!&8) &7You have to empty your inventory before joining + this event' + not-participant: '&8(&c!&8) &7You aren''t currently participating in this {game} + event' + full: '&8(&c!&8) &7The {game} event is currently full' + already-in-progress: '&8(&c!&8) &7The {game} event is already in progress' + not-started: '&8(&c!&8) &7The {game} event has not yet started' + list-header: '&8(&a!&8) &7Minigame List' + list-format: '&a* &7{event}' diff --git a/Events/src/main/resources/plugin.yml b/Events/src/main/resources/plugin.yml new file mode 100644 index 0000000..849de03 --- /dev/null +++ b/Events/src/main/resources/plugin.yml @@ -0,0 +1,12 @@ +name: CrankedEvents +main: net.crankedpvp.events.EventsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - HolographicDisplays + - FactionsKore + - CrankedDeadMansChest + - CrankedPvPTop + - CrankedBosses \ No newline at end of file diff --git a/FactionLogs/pom.xml b/FactionLogs/pom.xml new file mode 100644 index 0000000..4a93a6c --- /dev/null +++ b/FactionLogs/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + net.crankedpvp + ProjectCranked + 1.0 + + + FactionLogs + + + 8 + 8 + UTF-8 + + + + + Utils + net.crankedpvp + + + com.massivecraft + Factions + + + net.crankedpvp + Spawners + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/FactionLogsPlugin.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/FactionLogsPlugin.java new file mode 100644 index 0000000..6012d43 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/FactionLogsPlugin.java @@ -0,0 +1,60 @@ +package net.crankedpvp.factionlogs; + +import lombok.Getter; +import net.crankedpvp.factionlogs.commands.FactionLogsCommand; +import net.crankedpvp.factionlogs.data.FactionLogsData; +import net.crankedpvp.factionlogs.data.FactionLogsManager; +import net.crankedpvp.factionlogs.listeners.FactionListeners; +import net.crankedpvp.factionlogs.struct.typeadapters.FactionLogDeserializer; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.gson.Gson; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + + +@Getter +public class FactionLogsPlugin extends JavaPlugin { + + public FactionLogsManager logManager; + private static FactionLogsPlugin instance; + private Gson gson; + + + public void onEnable() { + instance = this; + + this.gson = StorageUtils.getInstance() + .getGson() + .newBuilder() + .registerTypeAdapter(FactionLogsData.class, new FactionLogDeserializer()).setLenient() + .create(); + + this.logManager = new FactionLogsManager(); + this.logManager.loadAll(); + loadListeners(); + loadCommands(); + Bukkit.getScheduler().runTaskTimer(this, () -> { + this.logManager.saveAll(); + }, 100L, 20 * 60 * 15); + } + + public void onDisable() { + //this.logManager.purge(); + this.logManager.saveAll(); + instance = null; + } + + + public void loadListeners() { + Bukkit.getPluginManager().registerEvents(new FactionListeners(), this); + } + + public void loadCommands() { + Bukkit.getPluginManager().registerEvents(new FactionLogsCommand(), this); + + } + + public static FactionLogsPlugin getInstance() { + return instance; + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/commands/FactionLogsCommand.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/commands/FactionLogsCommand.java new file mode 100644 index 0000000..7618d4b --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/commands/FactionLogsCommand.java @@ -0,0 +1,37 @@ +package net.crankedpvp.factionlogs.commands; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Role; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.factionlogs.gui.FactionLogsGUI; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +public class FactionLogsCommand implements Listener { + + @EventHandler(priority = EventPriority.LOWEST) + public void onCommand(PlayerCommandPreprocessEvent event) { + if (event.getMessage().equalsIgnoreCase("/f logs") || event.getMessage().equalsIgnoreCase("/f log")) { + event.setMessage("/null"); + event.setCancelled(true); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (!fPlayer.hasFaction()) { + fPlayer.sendMessage(CC.translate("&a&lFactions &8" + Arrow.arrow() + " &cError&8: &7You need a faction to type this command!")); + return; + } + + if (!fPlayer.getRole().isAtLeast(Role.MODERATOR)) { + fPlayer.sendMessage(CC.translate("&a&lFactions &8" + Arrow.arrow() + " &cError&8: &7You need to be atleast a mod to type this command!")); + return; + } + FactionLogsGUI factionLogsGUI = new FactionLogsGUI(event.getPlayer(), fPlayer.getFaction()); + factionLogsGUI.getFLogGui().open(event.getPlayer()); + fPlayer.sendMessage(CC.translate("&a&lFactions &8" + Arrow.arrow() + "&7 Opening the faction logs gui.")); + + } + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/data/FactionLogsData.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/data/FactionLogsData.java new file mode 100644 index 0000000..4963e44 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/data/FactionLogsData.java @@ -0,0 +1,43 @@ +package net.crankedpvp.factionlogs.data; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.storageutils.utils.KeyToSave; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Getter +public class FactionLogsData implements KeyToSave { + + private final Map> logs; + private String factionId; + + public FactionLogsData(String factionId) { + this.factionId = factionId; + this.logs = new HashMap<>(); + } + + public void addFactionLog(FactionLog factionLog) { + if (this.logs.containsKey(factionLog.getLogtype())) { + this.logs.get(factionLog.getLogtype()).add(factionLog); + } else { + List list = new ArrayList<>(); + list.add(factionLog); + this.logs.put(factionLog.getLogtype(), list); + } + } + + @Override + public String getKey() { + return factionId; + } + + @Override + public void setKey(String s) { + this.factionId = s; + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/data/FactionLogsManager.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/data/FactionLogsManager.java new file mode 100644 index 0000000..8fdcc45 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/data/FactionLogsManager.java @@ -0,0 +1,19 @@ +package net.crankedpvp.factionlogs.data; + +import net.crankedpvp.factionlogs.FactionLogsPlugin; +import net.crankedpvp.storageutils.utils.SaveLoadManager; + +public class FactionLogsManager extends SaveLoadManager { + + public FactionLogsManager() { + super(FactionLogsPlugin.getInstance(), FactionLogsPlugin.getInstance().getGson(), "data/", FactionLogsData.class); + } + + public FactionLogsData getFactionLogsData(String factionId) { + if (!super.containsKey(factionId)) { + FactionLogsData factionLogsData = new FactionLogsData(factionId); + addToCache(factionLogsData); + } + return getFromCache(factionId); + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/enums/LogType.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/enums/LogType.java new file mode 100644 index 0000000..f75ffdc --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/enums/LogType.java @@ -0,0 +1,32 @@ +package net.crankedpvp.factionlogs.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.struct.impl.*; +import org.bukkit.Material; + +@AllArgsConstructor +@Getter +public enum LogType { + + SPAWNER_PLACE("Spawner Place Logs", Material.MOB_SPAWNER, "&a&l", SpawnerPlace.class), + SPAWNER_BREAK("Spawner Break Logs", Material.MOB_SPAWNER, "&c&l", SpawnerBreak.class), + RELATION_EDITS("Relation Edits", Material.DIAMOND_CHESTPLATE, "&d&l", RelationEdits.class), + FACTION_RENAME("Rename Logs", Material.NAME_TAG, "&b&l", FactionRename.class), + PLAYER_LEAVE("Player Leaves", Material.WOOD_DOOR, "&c&l", PlayerLeave.class), + PLAYER_JOIN("Player Joins", Material.IRON_DOOR, "&a&l", PlayerJoin.class), + CLAIM("Claim Logs", Material.GRASS, "&a&l", LandClaim.class), + RADIUSCLAIM("Radius Claim Logs", Material.GRAVEL, "&e&l", RadiusLandClaim.class), + UNCLAIM("Unclaim Logs", Material.DIRT, "&c&l", LandUnclaim.class), + UNCLAIMALL("Unclaimall Logs", Material.REDSTONE_BLOCK, "&4&l", LandUnclaimAll.class), + CHUNKBUST("Chunkbust Logs", Material.ENDER_PORTAL_FRAME, "&3&l", ChunkBust.class); + + + + private final String displayName; + private final Material guiMaterial; + private final String guiColorCode; + private final Class logClass; + +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/gui/FactionLogsGUI.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/gui/FactionLogsGUI.java new file mode 100644 index 0000000..baf212b --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/gui/FactionLogsGUI.java @@ -0,0 +1,113 @@ +package net.crankedpvp.factionlogs.gui; + +import com.massivecraft.factions.Faction; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.factionlogs.FactionLogsPlugin; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.struct.impl.*; +import net.crankedpvp.factionlogs.utils.*; +import org.bukkit.Bukkit; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; + +import java.util.Collections; +import java.util.UUID; +import java.util.stream.Collectors; + +public class FactionLogsGUI { + + @Getter + private final PaginatedGui fLogGui; + + public FactionLogsGUI(Player player, Faction faction) { + this.fLogGui = new PaginatedGui(3, CC.translate(CC.DarkGray + faction.getTag() + " Faction Logs")); + + + for (LogType logType : LogType.values()) { + ItemBuilder item = new ItemBuilder(logType.getGuiMaterial(), CC.translate(logType.getGuiColorCode() + logType.getDisplayName())) + .addLoreLine(CC.translate("&7Below you can find the 10 latest logs:")) + .addLoreLine("") + .addLoreLine(CC.translate("&f&l" + logType.getDisplayName() + " &7(" + FactionsLogsAPI.getFactionLogs(faction, logType).size() + " total)")); + String prefix = logType.getGuiColorCode() + " * &e"; + + FactionsLogsAPI.getFactionLogs(faction, logType).sort(Collections.reverseOrder()); + for (FactionLog log : FactionsLogsAPI.getFactionLogs(faction, logType).stream().limit(10).collect(Collectors.toList())) { + try { + + + switch (logType) { + case CLAIM: + LandClaim landClaim = (LandClaim) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(landClaim.getUuid())).getName() + " &7claimed land at &d" + LocationUtils.locToString(landClaim.getFLocation()) + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case RADIUSCLAIM: + RadiusLandClaim radiusLandClaim = (RadiusLandClaim) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(radiusLandClaim.getUuid())).getName() + " &7claimed land in a &d" + radiusLandClaim.getRadius() + " &7radius at &d" + LocationUtils.locToString(radiusLandClaim.getFLocation()) + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case UNCLAIM: + LandUnclaim landUnClaim = (LandUnclaim) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(landUnClaim.getUuid())).getName() + " &7unclaimed land at &d" + LocationUtils.locToString(landUnClaim.getFLocation()) + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case UNCLAIMALL: + LandUnclaimAll landUnclaimAll = (LandUnclaimAll) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(landUnclaimAll.getUuid())).getName() + " &7unclaimed ALL land. " + "&8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case PLAYER_JOIN: + PlayerJoin playerJoin = (PlayerJoin) log; + if (playerJoin.getPlayerJoinReason() == null) break; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(playerJoin.getUuid())).getName() + " &7join the faction due to &e" + playerJoin.getPlayerJoinReason().name().toLowerCase() + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case PLAYER_LEAVE: + PlayerLeave playerLeave = (PlayerLeave) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(playerLeave.getUuid())).getName() + " &7left the faction due to &e" + playerLeave.getPlayerLeaveReason().name().toLowerCase() + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case CHUNKBUST: + ChunkBust chunkBust = (ChunkBust) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(chunkBust.getUuid())).getName() + " &7placed a chunkbuster at &d" + LocationUtils.locToString(chunkBust.getLocation()) + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case SPAWNER_BREAK: + SpawnerBreak spawnerBreak = (SpawnerBreak) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(spawnerBreak.getUuid())).getName() + " &7broke &ex" + spawnerBreak.getAmount() + " " + EntityUtils.getEntityName(EntityType.valueOf(spawnerBreak.getEntityType())) + "&7 at &d" + LocationUtils.locToString(spawnerBreak.getLocation()) + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case SPAWNER_PLACE: + SpawnerPlace spawnerPlace = (SpawnerPlace) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(spawnerPlace.getUuid())).getName() + " &7placed &ex" + spawnerPlace.getAmount() + " " + EntityUtils.getEntityName(EntityType.valueOf(spawnerPlace.getEntityType())) + "&7 at &d" + LocationUtils.locToString(spawnerPlace.getLocation()) + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case RELATION_EDITS: + RelationEdits relationEdits = (RelationEdits) log; + item.addLoreLine(CC.translate(prefix + relationEdits.getSender() + " &7changed relation: &d" + relationEdits.getOldRelation() + " &7-> &d" + relationEdits.getNewRelation() + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + case FACTION_RENAME: + FactionRename factionRename = (FactionRename) log; + item.addLoreLine(CC.translate(prefix + Bukkit.getOfflinePlayer(UUID.fromString(factionRename.getPlayer())).getName() + " &7renamed the faction tag &d" + factionRename.getOldTag() + " &7-> &d" + factionRename.getNewTag() + "&7. &8(&7" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - log.getTime()) / 1000) + "ago&8)")); + break; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + item.addLoreLine(""); + item.addLoreLine(CC.translate("&7&nClick&7 to view all the " + FactionsLogsAPI.getFactionLogs(faction, logType).size() + " " + logType.getDisplayName())); + this.fLogGui.addItem(new GuiItem(item.build(), event -> { + Bukkit.getScheduler().runTaskAsynchronously(FactionLogsPlugin.getInstance(), () -> { + if (FactionsLogsAPI.getFactionLogs(faction, logType).isEmpty()) { + player.sendMessage(CC.translate("&a&lFactions &8" + Arrow.arrow() + " &cError&8: &7There are no " + logType.getDisplayName() + " available!")); + return; + } + HastebinUtils.sendLog(player, faction.getId(), logType, false); + }); + })); + + } + + this.fLogGui.setDefaultClickAction(event -> event.setCancelled(true)); + + } + +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/listeners/FactionListeners.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/listeners/FactionListeners.java new file mode 100644 index 0000000..e46e68f --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/listeners/FactionListeners.java @@ -0,0 +1,84 @@ +package net.crankedpvp.factionlogs.listeners; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.event.*; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.factionlogs.struct.impl.*; +import net.crankedpvp.factionlogs.utils.FactionsLogsAPI; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; + +public class FactionListeners implements Listener { + + @EventHandler + public void onCBusterPlace(BlockPlaceEvent event) { + if (ItemUtils.isAirOrNull(event.getItemInHand())) return; + if (event.getItemInHand().getType() != Material.ENDER_PORTAL_FRAME) return; + NBTItem nbtItem = new NBTItem(event.getItemInHand()); + if(!nbtItem.hasKey("kore.chunkbuster.isbuster")) return; + Faction faction = FactionUtils.getFaction(event.getPlayer()); + FactionsLogsAPI.log(faction.getId(), new ChunkBust(event.getBlock().getLocation(), event.getPlayer().getUniqueId())); + } + + @EventHandler + public void onLandClaim(LandClaimEvent event) { + if (event.isCancelled()) return; + FactionsLogsAPI.log(event.getFactionId(), new LandClaim(event.getfPlayer().getPlayer().getUniqueId(), event.getPlayer().getLocation())); + } + + @EventHandler + public void onLandUnClaim(LandUnclaimEvent event) { + if (event.isCancelled()) return; + FactionsLogsAPI.log(event.getFactionId(), new LandUnclaim(event.getfPlayer().getPlayer().getUniqueId(), event.getPlayer().getLocation())); + } + + @EventHandler + public void onLandUnClaimAll(LandUnclaimAllEvent event) { + if (event.isCancelled()) return; + FactionsLogsAPI.log(event.getFactionId(), new LandUnclaimAll(event.getfPlayer().getPlayer().getUniqueId())); + } + + @EventHandler + public void onRadiusLandClaim(LandClaimRadiusEvent event) { + if (event.isCancelled()) return; + FactionsLogsAPI.log(event.getFactionId(), new RadiusLandClaim(event.getfPlayer().getPlayer().getUniqueId(), event.getfPlayer().getLocation(), event.getRadius())); + } + + + @EventHandler + public void onPlayerJoinFaction(FPlayerJoinEvent event) { + if (event.isCancelled()) return; + FactionsLogsAPI.log(event.getFaction().getId(), new PlayerJoin(event.getfPlayer().getPlayer().getUniqueId(), event.getReason())); + } + + @EventHandler + public void onPlayerLeaveFaction(FPlayerLeaveEvent event) { + if (event.isCancelled()) return; + if (event.getfPlayer() == null) return; + if (event.getfPlayer().getPlayer() == null) return; + if (event.getfPlayer().getPlayer().getUniqueId() == null) return; + if (event.getReason() == null) return; + FactionsLogsAPI.log(event.getFaction().getId(), new PlayerLeave(event.getfPlayer().getPlayer().getUniqueId(), event.getReason())); + } + + @EventHandler + public void onRelationChange(FactionRelationEvent event) { + FactionsLogsAPI.log(event.getFaction().getId(), new RelationEdits(event.getFaction(), event.getTargetFaction(), event.getOldRelation(), event.getRelation())); + FactionsLogsAPI.log(event.getTargetFaction().getId(), new RelationEdits(event.getFaction(), event.getTargetFaction(), event.getOldRelation(), event.getRelation())); + } + + @EventHandler + public void onFactionRename(FactionRenameEvent event) { + if (event.isCancelled()) return; + FactionsLogsAPI.log(event.getFaction().getId(), new FactionRename(event.getPlayer().getUniqueId(), event.getOldFactionTag(), event.getFactionTag())); + } + + @EventHandler + public void onFactionCreate(FactionCreateEvent event) { + FactionsLogsAPI.getFactionLogs(event.getFaction()).clear(); + } +} \ No newline at end of file diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/FactionLog.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/FactionLog.java new file mode 100644 index 0000000..f98b513 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/FactionLog.java @@ -0,0 +1,21 @@ +package net.crankedpvp.factionlogs.struct; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import net.crankedpvp.factionlogs.enums.LogType; + +@RequiredArgsConstructor +@Getter + +public abstract class FactionLog implements Comparable { + private final LogType logtype; + @Setter + private Long time = System.currentTimeMillis(); + + @Override + public int compareTo(FactionLog e) { + return this.getTime().compareTo(e.getTime()); + } + +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/ChunkBust.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/ChunkBust.java new file mode 100644 index 0000000..4732c3a --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/ChunkBust.java @@ -0,0 +1,38 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.LocationUtils; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; + +import java.util.UUID; + +@Getter +public class ChunkBust extends FactionLog { + private final Location location; + private final String uuid; + + public ChunkBust(Location location, UUID uuid) { + super(LogType.CHUNKBUST); + this.location = location; + this.uuid = uuid.toString(); + + } + + public ChunkBust(Location location, UUID uuid, long time) { + super(LogType.CHUNKBUST); + this.location = location; + this.uuid = uuid.toString(); + super.setTime(time); + + } + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(getUuid())).getName() + " chunkbusted at " + LocationUtils.locToString(getLocation()) + "&7."; + + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/FactionRename.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/FactionRename.java new file mode 100644 index 0000000..3c2698a --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/FactionRename.java @@ -0,0 +1,38 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; + +import java.util.UUID; + +@Getter +public class FactionRename extends FactionLog { + private final String player; + private final String oldTag; + private final String newTag; + + public FactionRename(UUID playerUUID, String oldTag, String newTag) { + super(LogType.FACTION_RENAME); + this.player = playerUUID.toString(); + this.oldTag = oldTag; + this.newTag = newTag; + } + + public FactionRename(UUID playerUUID, String oldTag, String newTag, long time) { + super(LogType.FACTION_RENAME); + this.player = playerUUID.toString(); + this.oldTag = oldTag; + this.newTag = newTag; + super.setTime(time); + } + + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(player)).getName() + " renamed the faction tag " + getOldTag() + " -> " + getNewTag() + "."; + + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandClaim.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandClaim.java new file mode 100644 index 0000000..6e60359 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandClaim.java @@ -0,0 +1,36 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.LocationUtils; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; + +import java.util.UUID; + +@Getter +public class LandClaim extends FactionLog { + private final String uuid; + private final Location fLocation; + + public LandClaim(UUID uuid, Location fLocation) { + super(LogType.CLAIM); + this.uuid = uuid.toString(); + this.fLocation = fLocation; + } + + public LandClaim(UUID uuid, Location fLocation, long time) { + super(LogType.CLAIM); + this.uuid = uuid.toString(); + this.fLocation = fLocation; + super.setTime(time); + } + + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(uuid)).getName() + " claimed land at " + LocationUtils.locToString(fLocation); + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandUnclaim.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandUnclaim.java new file mode 100644 index 0000000..8323c09 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandUnclaim.java @@ -0,0 +1,35 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.LocationUtils; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; + +import java.util.UUID; + +@Getter +public class LandUnclaim extends FactionLog { + private final String uuid; + private final Location fLocation; + + public LandUnclaim(UUID uuid, Location fLocation) { + super(LogType.UNCLAIM); + this.uuid = uuid.toString(); + this.fLocation = fLocation; + } + + public LandUnclaim(UUID uuid, Location fLocation, long time) { + super(LogType.UNCLAIM); + this.uuid = uuid.toString(); + this.fLocation = fLocation; + super.setTime(time); + } + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(uuid)).getName() + " unclaimed land at " + LocationUtils.locToString(fLocation); + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandUnclaimAll.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandUnclaimAll.java new file mode 100644 index 0000000..6770024 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/LandUnclaimAll.java @@ -0,0 +1,33 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; + +import java.util.UUID; + +@Getter +public class LandUnclaimAll extends FactionLog { + private final String uuid; + + public LandUnclaimAll(UUID uuid) { + super(LogType.UNCLAIMALL); + this.uuid = uuid.toString(); + + } + + public LandUnclaimAll(UUID uuid, long time) { + super(LogType.UNCLAIMALL); + this.uuid = uuid.toString(); + super.setTime(time); + } + + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(uuid)).getName() + " unclaimed ALL land"; + + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/PlayerJoin.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/PlayerJoin.java new file mode 100644 index 0000000..9ba0a75 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/PlayerJoin.java @@ -0,0 +1,38 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import com.massivecraft.factions.event.FPlayerJoinEvent; +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; + +import java.util.UUID; + +@Getter +public class PlayerJoin extends FactionLog { + private final String uuid; + private transient final FPlayerJoinEvent.PlayerJoinReason playerJoinReason; + + public PlayerJoin(UUID uuid, FPlayerJoinEvent.PlayerJoinReason playerJoinReason) { + super(LogType.PLAYER_JOIN); + this.uuid = uuid.toString(); + this.playerJoinReason = playerJoinReason; + + } + + public PlayerJoin(UUID uuid, FPlayerJoinEvent.PlayerJoinReason playerJoinReason, long time) { + super(LogType.PLAYER_JOIN); + this.uuid = uuid.toString(); + this.playerJoinReason = playerJoinReason; + super.setTime(time); + + } + + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(uuid)).getName() + " joined the faction because of: " + playerJoinReason; + + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/PlayerLeave.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/PlayerLeave.java new file mode 100644 index 0000000..7ccc5f8 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/PlayerLeave.java @@ -0,0 +1,38 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import com.massivecraft.factions.event.FPlayerLeaveEvent; +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; + +import java.util.UUID; + +@Getter +public class PlayerLeave extends FactionLog { + private final String uuid; + private final transient FPlayerLeaveEvent.PlayerLeaveReason playerLeaveReason; + + public PlayerLeave(UUID uuid, FPlayerLeaveEvent.PlayerLeaveReason playerLeaveReason) { + super(LogType.PLAYER_LEAVE); + this.uuid = uuid.toString(); + this.playerLeaveReason = playerLeaveReason; + } + + public PlayerLeave(UUID uuid, FPlayerLeaveEvent.PlayerLeaveReason playerLeaveReason, long time) { + super(LogType.PLAYER_LEAVE); + this.uuid = uuid.toString(); + this.playerLeaveReason = playerLeaveReason; + super.setTime(time); + } + + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(uuid)).getName() + " left the faction because of: " + playerLeaveReason; + + } + + +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/RadiusLandClaim.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/RadiusLandClaim.java new file mode 100644 index 0000000..0c2b097 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/RadiusLandClaim.java @@ -0,0 +1,39 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.LocationUtils; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; + +import java.util.UUID; + +@Getter +public class RadiusLandClaim extends FactionLog { + private final String uuid; + private final Location fLocation; + private final Integer radius; + + public RadiusLandClaim(UUID uuid, Location fLocation, int radius) { + super(LogType.RADIUSCLAIM); + this.uuid = uuid.toString(); + this.fLocation = fLocation; + this.radius = radius; + } + + public RadiusLandClaim(UUID uuid, Location fLocation,int radius, long time) { + super(LogType.RADIUSCLAIM); + this.uuid = uuid.toString(); + this.fLocation = fLocation; + this.radius = radius; + super.setTime(time); + } + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(uuid)).getName() + " claimed land in a radius of " + radius + " radius at " + LocationUtils.locToString(fLocation); + + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/RelationEdits.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/RelationEdits.java new file mode 100644 index 0000000..657fce2 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/RelationEdits.java @@ -0,0 +1,39 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.perms.Relation; +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; + +@Getter +public class RelationEdits extends FactionLog { + private final String sender; + private final String target; + private final String oldRelation; + private final String newRelation; + + public RelationEdits(Faction sender, Faction target, Relation oldRelation, Relation newRelation) { + super(LogType.RELATION_EDITS); + this.sender = sender.getTag(); + this.target = target.getTag(); + this.oldRelation = oldRelation.nicename; + this.newRelation = newRelation.nicename; + } + + public RelationEdits(Faction sender, Faction target, Relation oldRelation, Relation newRelation, long time) { + super(LogType.RELATION_EDITS); + this.sender = sender.getTag(); + this.target = target.getTag(); + this.oldRelation = oldRelation.nicename; + this.newRelation = newRelation.nicename; + super.setTime(time); + } + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + getSender() + " changed relation: " + getOldRelation() + " -> " + getNewRelation() + "."; + + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/SpawnerBreak.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/SpawnerBreak.java new file mode 100644 index 0000000..59b9e19 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/SpawnerBreak.java @@ -0,0 +1,47 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.EntityUtils; +import net.crankedpvp.factionlogs.utils.LocationUtils; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.EntityType; + +import java.util.UUID; + +@Getter +public class SpawnerBreak extends FactionLog { + private final Integer amount; + private final Location location; + private final String entityType; + private final String uuid; + + public SpawnerBreak(int amount, Location location, EntityType entityType, UUID uuid) { + super(LogType.SPAWNER_BREAK); + this.amount = amount; + this.location = location; + this.entityType = entityType.toString(); + this.uuid = uuid.toString(); + + } + + public SpawnerBreak(int amount, Location location, EntityType entityType, UUID uuid, long time) { + super(LogType.SPAWNER_BREAK); + this.amount = amount; + this.location = location; + this.entityType = entityType.toString(); + this.uuid = uuid.toString(); + super.setTime(time); + + } + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(getUuid())).getName() + " broke x" + getAmount() + " " + EntityUtils.getEntityName(EntityType.valueOf(getEntityType())) + " at " + LocationUtils.locToString(getLocation()) + "."; + + + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/SpawnerPlace.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/SpawnerPlace.java new file mode 100644 index 0000000..1dfabfa --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/impl/SpawnerPlace.java @@ -0,0 +1,45 @@ +package net.crankedpvp.factionlogs.struct.impl; + +import lombok.Getter; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import net.crankedpvp.factionlogs.utils.EntityUtils; +import net.crankedpvp.factionlogs.utils.LocationUtils; +import net.crankedpvp.factionlogs.utils.TimeDateUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.EntityType; + +import java.util.UUID; + +@Getter +public class SpawnerPlace extends FactionLog { + private final Integer amount; + private final Location location; + private final String entityType; + private final String uuid; + + + public SpawnerPlace(int amount, Location location, EntityType entityType, UUID uuid) { + super(LogType.SPAWNER_PLACE); + this.amount = amount; + this.location = location; + this.uuid = uuid.toString(); + this.entityType = entityType.toString(); + } + + public SpawnerPlace(int amount, Location location, EntityType entityType, UUID uuid, long time) { + super(LogType.SPAWNER_PLACE); + this.amount = amount; + this.location = location; + this.uuid = uuid.toString(); + this.entityType = entityType.toString(); + super.setTime(time); + } + + @Override + public String toString() { + return "(" + TimeDateUtils.splitToComponentTimes((System.currentTimeMillis() - getTime()) / 1000) + "ago) " + Bukkit.getOfflinePlayer(UUID.fromString(getUuid())).getName() + " placed x" + getAmount() + " " + EntityUtils.getEntityName(EntityType.valueOf(getEntityType())) + " at " + LocationUtils.locToString(getLocation()) + "."; + + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/typeadapters/FactionLogDeserializer.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/typeadapters/FactionLogDeserializer.java new file mode 100644 index 0000000..6a977dd --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/struct/typeadapters/FactionLogDeserializer.java @@ -0,0 +1,28 @@ +package net.crankedpvp.factionlogs.struct.typeadapters; + +import net.crankedpvp.factionlogs.data.FactionLogsData; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.storageutils.gson.*; + +import java.lang.reflect.Type; + +public class FactionLogDeserializer implements JsonDeserializer { + + @Override + public FactionLogsData deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = jsonElement.getAsJsonObject(); + FactionLogsData factionLogsData = new FactionLogsData(jsonObject.get("factionId").getAsString()); + + JsonObject logs = jsonObject.getAsJsonObject("logs"); + for (String key : logs.keySet()) { + JsonArray jsonArray = logs.getAsJsonArray(key); + LogType logType = LogType.valueOf(key); + + for (JsonElement element : jsonArray) { + factionLogsData.addFactionLog(context.deserialize(element, logType.getLogClass())); + } + } + + return factionLogsData; + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/EntityUtils.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/EntityUtils.java new file mode 100644 index 0000000..6d504d7 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/EntityUtils.java @@ -0,0 +1,16 @@ +package net.crankedpvp.factionlogs.utils; + +import org.bukkit.entity.EntityType; + +public class EntityUtils { + public static String getEntityName(EntityType type) { + if (type == null) return "null"; + if (type == EntityType.IRON_GOLEM) { + return "Iron Golem"; + } + if (type == EntityType.MUSHROOM_COW) { + return "Mushroom Cow"; + } + return type.getName(); + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/FactionsLogsAPI.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/FactionsLogsAPI.java new file mode 100644 index 0000000..25ecc4e --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/FactionsLogsAPI.java @@ -0,0 +1,53 @@ +package net.crankedpvp.factionlogs.utils; + + +import com.massivecraft.factions.Faction; +import net.crankedpvp.factionlogs.FactionLogsPlugin; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class FactionsLogsAPI { + public static void log(Faction faction, FactionLog factionLog) { + try { + FactionLogsPlugin.getInstance().getLogManager().getFactionLogsData(faction.getId()).addFactionLog(factionLog); + } catch (NullPointerException exception) { + exception.printStackTrace(); + } + } + + public static void log(String id, FactionLog factionLog) { + try { + FactionLogsPlugin.getInstance().getLogManager().getFactionLogsData(id).addFactionLog(factionLog); + } catch (NullPointerException exception) { + exception.printStackTrace(); + } } + + public static List getFactionLogs(String id, LogType logType) { + if (FactionLogsPlugin.getInstance().getLogManager().getFactionLogsData(id).getLogs().containsKey(logType)) { + return FactionLogsPlugin.getInstance().getLogManager().getFactionLogsData(id).getLogs().get(logType); + } + return Collections.emptyList(); + } + + public static List getFactionLogs(Faction faction, LogType logType) { + if (FactionLogsPlugin.getInstance().getLogManager().getFactionLogsData(faction.getId()).getLogs().containsKey(logType)) { + return FactionLogsPlugin.getInstance().getLogManager().getFactionLogsData(faction.getId()).getLogs().get(logType); + } + return Collections.emptyList(); + + } + + public static Map> getFactionLogs(Faction faction) { + return FactionLogsPlugin.getInstance().getLogManager().getFactionLogsData(faction.getId()).getLogs(); + } + + public static boolean hasEmptyLog(Faction faction) { + return FactionLogsPlugin.getInstance().getLogManager().getFactionLogsData(faction.getId()).getLogs().isEmpty(); + } + + +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/HastebinUtils.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/HastebinUtils.java new file mode 100644 index 0000000..0c47e1f --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/HastebinUtils.java @@ -0,0 +1,98 @@ +package net.crankedpvp.factionlogs.utils; + +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.factionlogs.enums.LogType; +import net.crankedpvp.factionlogs.struct.FactionLog; +import org.bukkit.entity.Player; + +import javax.net.ssl.HttpsURLConnection; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HastebinUtils { + + private static final DateTimeFormatter DATE_FORMATED = DateTimeFormatter.ofPattern("EEE, MMM dd | HH:mm"); + private static final Map clickCooldown = new HashMap<>(); + private static final String REQUEST_URL = "https://hastebin.com/documents"; + + + public static String post(String text, boolean raw) throws IOException { + byte[] postData = text.getBytes(StandardCharsets.UTF_8); + int postDataLength = postData.length; + + URL url = new URL(REQUEST_URL); + HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); + conn.setDoOutput(true); + conn.setInstanceFollowRedirects(false); + conn.setRequestMethod("POST"); + conn.setRequestProperty("User-Agent", "Hastebin Java Api"); + conn.setRequestProperty("content-type", "text/plain"); + conn.setRequestProperty("Authorization", "Bearer 2614226daf8202446aba715e2b25cdf80e38fd0fe35c758eaacad03a9198dc6cc2f76a7cabd09fd937e6f3fc7dc24dd36120432df2a1212c7ee8e014497cad59"); + conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); + conn.setUseCaches(false); + + String response = null; + DataOutputStream wr; + try { + wr = new DataOutputStream(conn.getOutputStream()); + wr.write(postData); + BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + response = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + + assert response != null; + if (response.contains("\"key\"")) { + response = response.substring(response.indexOf(":") + 2, response.length() - 2); + + String postURL = raw ? "https://hastebin.com/raw/" : "https://hastebin.com/share/"; + response = postURL + response; + } + + return response; + } + + public static void sendLog(Player sender, String factionId, LogType logType, boolean raw) { + long msCooldown = 300000; + if (clickCooldown.containsKey(factionId) && !sender.isOp()) { + if (clickCooldown.get(factionId) + msCooldown > System.currentTimeMillis()) { + sender.sendMessage(CC.translate("&a&lFactions &8" + Arrow.arrow() + " &cError&8: &7Your faction recently generated an f log URL, please wait another &7" + TimeDateUtils.fancy((clickCooldown.get(factionId) + msCooldown) - System.currentTimeMillis()))); + return; + } + } + clickCooldown.put(factionId, System.currentTimeMillis()); + sender.sendMessage(CC.translate("&a&lFactions &8" + Arrow.arrow() + " &7Generating " + logType.getDisplayName() + " faction logs...")); + + LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("America/New_York")); + String date = localDateTime.format(DATE_FORMATED); + StringBuilder text = new StringBuilder(); + text.append(logType.getDisplayName()).append(" Generated on ").append(date).append(" (EST)").append(" for faction ").append(FactionUtils.getFactionById(factionId).getTag()).append("\n"); + List factionLogsList = FactionsLogsAPI.getFactionLogs(factionId, logType); + for (FactionLog factionLog : factionLogsList) { + text.append(" ").append(factionLog.toString()).append("\n"); + } + + + try { + String url = post(text.toString(), raw); + sender.sendMessage(CC.translate("&a&lFactions &8" + Arrow.arrow() + " &7" + logType.getDisplayName() + " &7(Logs URL): &a&n" + url)); + } catch (IOException e) { + sender.sendMessage(CC.translate("&a&lFactions &8" + Arrow.arrow() + " &cError&8: &eAn error occurred, please try again!")); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/LocationSerializer.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/LocationSerializer.java new file mode 100644 index 0000000..e205496 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/LocationSerializer.java @@ -0,0 +1,30 @@ +package net.crankedpvp.factionlogs.utils; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + +public class LocationSerializer { + + public static String serialize(Location obj) { + if (obj == null) { + return ""; + } + return obj.getWorld().getName() + ":" + obj.getBlockX() + ":" + obj.getBlockY() + ":" + obj.getBlockZ(); + } + + public static Location deserialize(String s) { + if (s == null || s.trim().equals("")) { + return null; + } + final String[] parts = s.split(":"); + if (parts.length == 4) { + final World w = Bukkit.getServer().getWorld(parts[0]); + final int x = Integer.parseInt(parts[1]); + final int y = Integer.parseInt(parts[2]); + final int z = Integer.parseInt(parts[3]); + return new Location(w, x, y, z); + } + return null; + } +} \ No newline at end of file diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/LocationUtils.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/LocationUtils.java new file mode 100644 index 0000000..9c4a3c9 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/LocationUtils.java @@ -0,0 +1,9 @@ +package net.crankedpvp.factionlogs.utils; + +import org.bukkit.Location; + +public class LocationUtils { + public static String locToString(Location l) { + return "[" + l.getWorld().getName() + "," + l.getX() + "," + l.getY() + "," + l.getZ() + "]"; + } +} diff --git a/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/TimeDateUtils.java b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/TimeDateUtils.java new file mode 100644 index 0000000..48214a5 --- /dev/null +++ b/FactionLogs/src/main/java/net/crankedpvp/factionlogs/utils/TimeDateUtils.java @@ -0,0 +1,29 @@ +package net.crankedpvp.factionlogs.utils; + +import java.util.concurrent.TimeUnit; + +public class TimeDateUtils { + + public static String splitToComponentTimes(long seconds) { + int days = (int) seconds / 86400; + + int hours = (int) seconds / 3600; + + int remainder = (int) seconds - hours * 3600; + int mins = remainder / 60; + remainder = remainder - mins * 60; + int secs = remainder; + return days + "d " + hours + "h " + mins + "m " + secs + "s "; + } + + public static String fancy(long seconds) { + seconds = seconds / 1000; + int day = (int) TimeUnit.SECONDS.toDays(seconds); + long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24L); + long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60); + long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60); + + return day + "d " + hours + "h " + minute + "m " + second + "s "; + + } +} diff --git a/FactionLogs/src/main/resources/plugin.yml b/FactionLogs/src/main/resources/plugin.yml new file mode 100644 index 0000000..fc8d3a5 --- /dev/null +++ b/FactionLogs/src/main/resources/plugin.yml @@ -0,0 +1,10 @@ +name: CrankedFactionLogs +main: net.crankedpvp.factionlogs.FactionLogsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - Factions + - CrankedSpawners + - StorageUtil diff --git a/Factions/lib/taco.jar b/Factions/lib/taco.jar new file mode 100644 index 0000000..1db58f1 Binary files /dev/null and b/Factions/lib/taco.jar differ diff --git a/Factions/modules/FactionsLegacy/pom.xml b/Factions/modules/FactionsLegacy/pom.xml new file mode 100644 index 0000000..f7abc08 --- /dev/null +++ b/Factions/modules/FactionsLegacy/pom.xml @@ -0,0 +1,229 @@ + + 4.0.0 + + com.massivecraft + Factions-Legacy + 1.6.9.5-U0.5.18 + jar + + Factions Legacy Version Support + + + UTF-8 + + + + clean package install + ${project.name} + + + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + + + + + org.spigotmc + spigot-api + 1.8.8-R0.1-SNAPSHOT + provided + + + bungeecord-chat + net.md-5 + + + persistence-api + javax.persistence + + + junit + junit + + + guava + com.google.guava + + + gson + com.google.code.gson + + + + + com.sk89q + worldguard + 6.1.1-SNAPSHOT + provided + + + bukkit + org.bukkit + + + bukkit-classloader-check + com.sk89q.spigot + + + commandbook + com.sk89q + + + jsr305 + com.google.code.findbugs + + + js + rhino + + + truezip + de.schlichtherle + + + jchronic + com.sk89q + + + worldedit + com.sk89q + + + + + com.sk89q.worldedit + worldedit-bukkit + 6.1.1-SNAPSHOT + provided + + + bukkit + org.bukkit + + + jsr305 + com.google.code.findbugs + + + bukkit-classloader-check + org.sk89q.bukkit + + + dummypermscompat + com.sk89q + + + jchronic + com.sk89q + + + js + rhino + + + truezip + de.schlichtherle + + + jlibnoise + com.sk89q.lib + + + paranamer + com.thoughtworks.paranamer + + + guava + com.google.guava + + + gson + com.google.code.gson + + + snakeyaml + org.yaml + + + + + com.sk89q.worldedit + worldedit-core + 6.1.1-SNAPSHOT + provided + + + bukkit + org.bukkit + + + jsr305 + com.google.code.findbugs + + + bukkit-classloader-check + org.sk89q.bukkit + + + dummypermscompat + com.sk89q + + + jchronic + com.sk89q + + + js + rhino + + + truezip + de.schlichtherle + + + jlibnoise + com.sk89q.lib + + + paranamer + com.thoughtworks.paranamer + + + guava + com.google.guava + + + gson + com.google.code.gson + + + snakeyaml + org.yaml + + + + + + + + + enginehub-maven + https://maven.enginehub.org/repo/ + + + sk89q-repo + https://maven.enginehub.org/repo/ + + + spigot-repo + https://hub.spigotmc.org/nexus/content/groups/public/ + + + \ No newline at end of file diff --git a/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/integration/IWorldguard.java b/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/integration/IWorldguard.java new file mode 100644 index 0000000..c90b43b --- /dev/null +++ b/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/integration/IWorldguard.java @@ -0,0 +1,17 @@ +package com.massivecraft.factions.integration; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public interface IWorldguard { + + boolean isPVP(Player player); + + boolean playerCanBuild(Player player, Location loc); + + boolean checkForRegionsInChunk(Chunk chunk); + + String getVersion(); + +} diff --git a/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/integration/Worldguard6.java b/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/integration/Worldguard6.java new file mode 100644 index 0000000..3a0c446 --- /dev/null +++ b/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/integration/Worldguard6.java @@ -0,0 +1,99 @@ +package com.massivecraft.factions.integration; + +import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldedit.Vector; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.flags.DefaultFlag; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector; + +/** + * Worldguard Region Checking. + * + * @author Spathizilla + */ +public class Worldguard6 implements IWorldguard { + + private WorldGuardPlugin wg; + + public Worldguard6(Plugin wg) { + this.wg = (WorldGuardPlugin) wg; + } + + // PVP Flag check + // Returns: + // True: PVP is allowed + // False: PVP is disallowed + public boolean isPVP(Player player) { + Location loc = player.getLocation(); + World world = loc.getWorld(); + Vector pt = toVector(loc); + + RegionManager regionManager = wg.getRegionManager(world); + ApplicableRegionSet set = regionManager.getApplicableRegions(pt); + return set.allows(DefaultFlag.PVP); + } + + // Check if player can build at location by worldguards rules. + // Returns: + // True: Player can build in the region. + // False: Player can not build in the region. + public boolean playerCanBuild(Player player, Location loc) { + World world = loc.getWorld(); + Vector pt = toVector(loc); + + return wg.getRegionManager(world).getApplicableRegions(pt).size() > 0 && wg.canBuild(player, loc); + } + + // Check for Regions in chunk the chunk + // Returns: + // True: Regions found within chunk + // False: No regions found within chunk + public boolean checkForRegionsInChunk(Chunk chunk) { + World world = chunk.getWorld(); + int minChunkX = chunk.getX() << 4; + int minChunkZ = chunk.getZ() << 4; + int maxChunkX = minChunkX + 15; + int maxChunkZ = minChunkZ + 15; + + int worldHeight = world.getMaxHeight(); // Allow for heights other than default + + BlockVector minChunk = new BlockVector(minChunkX, 0, minChunkZ); + BlockVector maxChunk = new BlockVector(maxChunkX, worldHeight, maxChunkZ); + + RegionManager regionManager = wg.getRegionManager(world); + ProtectedCuboidRegion region = new ProtectedCuboidRegion("wgfactionoverlapcheck", minChunk, maxChunk); + Map allregions = regionManager.getRegions(); + Collection allregionslist = new ArrayList<>(allregions.values()); + List overlaps; + boolean foundregions = false; + + try { + overlaps = region.getIntersectingRegions(allregionslist); + foundregions = overlaps != null && !overlaps.isEmpty(); + } catch (Exception e) { + e.printStackTrace(); + } + + return foundregions; + } + + @Override + public String getVersion() { + return wg.getDescription().getVersion(); + } +} \ No newline at end of file diff --git a/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListenerBase.java b/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListenerBase.java new file mode 100644 index 0000000..6dd66d7 --- /dev/null +++ b/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListenerBase.java @@ -0,0 +1,8 @@ +package com.massivecraft.factions.listeners.versionspecific; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public interface PortalListenerBase { + boolean shouldCancel(Location location, Player player); +} diff --git a/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListenerLegacy.java b/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListenerLegacy.java new file mode 100644 index 0000000..cae7f17 --- /dev/null +++ b/Factions/modules/FactionsLegacy/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListenerLegacy.java @@ -0,0 +1,29 @@ +package com.massivecraft.factions.listeners.versionspecific; + +import org.bukkit.TravelAgent; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerPortalEvent; + +/* + Supports versions older than 1.14 with TravelAgent. + */ +public class PortalListenerLegacy implements Listener { + private PortalListenerBase base; + + public PortalListenerLegacy(PortalListenerBase base) { + this.base = base; + } + + @EventHandler + public void onTravel(PlayerPortalEvent event) { + TravelAgent agent = event.getPortalTravelAgent(); + + // If they aren't able to find a portal, it'll try to create one. + if (event.useTravelAgent() && agent.getCanCreatePortal() && agent.findPortal(event.getTo()) == null) { + if (this.base.shouldCancel(event.getTo(), event.getPlayer())) { + event.setCancelled(true); + } + } + } +} diff --git a/Factions/modules/FactionsMain/pom.xml b/Factions/modules/FactionsMain/pom.xml new file mode 100644 index 0000000..525296c --- /dev/null +++ b/Factions/modules/FactionsMain/pom.xml @@ -0,0 +1,510 @@ + + 4.0.0 + + com.massivecraft + FactionsMain + 1.6.9.5-U0.5.18 + jar + + + + FactionsMain + + + UTF-8 + + + + clean package install + ${project.name} + ../../src/main/java + ../../src/test/java + ../../target + + + true + ../../src/main/resources/ + + + + + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.1 + + false + + + com.mojang:brigadier + net.crankedpvp:Toggles + + + + + *:* + + + com/earth2me/essentials/** + net/ess3/** + + + + + + mkremins.fanciful + moss.factions.shade.mkremins.fanciful + + + com.google + moss.factions.shade.com.google + + + com.darkblade12 + moss.factions.shade.com.darkblade12 + + + net.amoebaman.util + moss.factions.shade.net.amoebaman.util + + + me.lucko.commodore + moss.factions.shade.me.lucko.commodore + + + com.typesafe + moss.factions.shade.com.typesafe + + + ninja.leaping + moss.factions.shade.ninja.leaping + + + org.apache.http + moss.factions.shade.org.apache.http + + + org.apache.commons.codec + moss.factions.shade.org.apache.commons.codec + + + org.apache.commons.logging + moss.factions.shade.org.apache.commons.logging + + + org.kitteh + moss.factions.shade.org.kitteh + + + io.papermc.lib + moss.factions.shade.io.paperlib + + + + + + package + + shade + + + + + + + + + + com.massivecraft + Factions-Legacy + ${project.version} + + + io.papermc + paperlib + 1.0.4 + compile + + + org.spigotmc + spigot-api + 1.16.2-R0.1-SNAPSHOT + provided + + + bungeecord-chat + net.md-5 + + + persistence-api + javax.persistence + + + junit + junit + + + guava + com.google.guava + + + gson + com.google.code.gson + + + + + net.milkbowl.vault + VaultAPI + 1.7 + provided + + + bukkit + org.bukkit + + + + + com.sk89q.worldguard + worldguard-core + 7.0.0-SNAPSHOT + provided + + + bukkit + org.bukkit + + + bukkit-classloader-check + com.sk89q.spigot + + + commandbook + com.sk89q + + + jsr305 + com.google.code.findbugs + + + js + rhino + + + truezip + de.schlichtherle + + + jchronic + com.sk89q + + + worldedit + com.sk89q + + + + + com.sk89q.worldguard + worldguard-legacy + 7.0.0-SNAPSHOT + provided + + + bukkit + org.bukkit + + + bukkit-classloader-check + com.sk89q.spigot + + + commandbook + com.sk89q + + + jsr305 + com.google.code.findbugs + + + js + rhino + + + truezip + de.schlichtherle + + + jchronic + com.sk89q + + + worldedit + com.sk89q + + + + + com.sk89q.worldedit + worldedit-bukkit + 7.0.0-SNAPSHOT + provided + + + bukkit + org.bukkit + + + jsr305 + com.google.code.findbugs + + + bukkit-classloader-check + org.sk89q.bukkit + + + dummypermscompat + com.sk89q + + + jchronic + com.sk89q + + + js + rhino + + + truezip + de.schlichtherle + + + jlibnoise + com.sk89q.lib + + + paranamer + com.thoughtworks.paranamer + + + guava + com.google.guava + + + gson + com.google.code.gson + + + snakeyaml + org.yaml + + + + + net.crankedpvp + LunarAPI + 1.0 + provided + + + net.ess3 + EssentialsX + 2.16.0 + provided + + + mkremins + fanciful + 0.4.0-SNAPSHOT + compile + + + gson + com.google.code.gson + + + + + com.google.guava + guava + 21.0 + compile + + + jsr305 + com.google.code.findbugs + + + + + com.google.code.gson + gson + 2.8.5 + compile + + + com.drtshock + PlayerVaultsX + 4.1.0 + provided + + + net.crankedpvp + taco + 1.0 + system + ${project.basedir}/../../lib/taco.jar + + + net.crankedpvp + wine + 1.0 + system + ${project.basedir}/../../../.lib/WineSpigot-V1.4.4.3.jar + + + me.clip + placeholderapi + 2.11.6 + provided + + + be.maximvdw + MVdWPlaceholderAPI + 2.2.3-fuuid + provided + + + org.spigotmc + spigot + + + + + com.darkblade12 + particleeffect + 1.8.0-fuuid + + + org.spongepowered + configurate-hocon + 3.6.1 + + + checker-qual + org.checkerframework + + + + + org.kitteh + paste-gg-api + 0.9.1 + compile + + + net.luckperms + api + 5.0 + provided + + + org.junit.jupiter + junit-jupiter + 5.5.1 + test + + + net.coreprotect + coreprotect + 2.15.0 + provided + + + dev.triumphteam + triumph-gui + 3.1.2 + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../../../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + net.crankedpvp + Toggles + 1.0 + + + + + + sk89q-repo + https://maven.enginehub.org/repo/ + + + fuuid-repo + https://github.com/factions-site/repo/raw/public + + + ess-repo + https://ci.ender.zone/plugin/repository/everything/ + + + papermc + https://papermc.io/repo/repository/maven-public/ + + + spigot-repo + https://hub.spigotmc.org/nexus/content/groups/public/ + + + enginehub-maven + https://maven.enginehub.org/repo/ + + + repo.mikeprimm.com + https://repo.mikeprimm.com/ + + + sponge + https://repo.spongepowered.org/maven + + + citizens-repo + https://repo.citizensnpcs.co + + + placeholderapi + https://repo.extendedclip.com/content/repositories/placeholderapi/ + + + jitpack.io + https://jitpack.io + + + magic + https://maven.elmakers.com/repository/ + + + minecraft-libraries + Minecraft Libraries + https://libraries.minecraft.net + + + net.coreprotect + https://maven.playpro.com/ + + + diff --git a/Factions/pom.xml b/Factions/pom.xml new file mode 100644 index 0000000..c816a43 --- /dev/null +++ b/Factions/pom.xml @@ -0,0 +1,72 @@ + + 4.0.0 + + com.massivecraft + CrankedFactions + 1.6.9.5-U0.5.18 + pom + + Factions + + + UTF-8 + + + + modules/FactionsLegacy + modules/FactionsMain + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + + + + + org.spigotmc + spigot + 1.8.8-R0.1-SNAPSHOT + provided + + + persistence-api + javax.persistence + + + junit + junit + + + guava + com.google.guava + + + gson + com.google.gson + + + gson + com.google.code.gson + + + + + net.crankedpvp + taco + 1.0 + system + ${project.basedir}/../.lib/WineSpigot-V1.4.4.3.jar + + + diff --git a/Factions/src/main/java/com/massivecraft/factions/Board.java b/Factions/src/main/java/com/massivecraft/factions/Board.java new file mode 100644 index 0000000..321522b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/Board.java @@ -0,0 +1,90 @@ +package com.massivecraft.factions; + +import com.massivecraft.factions.data.json.JSONBoard; +import mkremins.fanciful.FancyMessage; +import org.bukkit.World; + +import java.util.List; +import java.util.Map; +import java.util.Set; + + +public abstract class Board { + protected static Board instance = getBoardImpl(); + + //----------------------------------------------// + // Get and Set + //----------------------------------------------// + public abstract String getIdAt(FLocation flocation); + + public static Board getBoardImpl() { + return new JSONBoard(); + } + + public static Board getInstance() { + return instance; + } + + public abstract Faction getFactionAt(FLocation flocation); + + public abstract Map> dumpAsSaveFormat(); + + + public abstract void setIdAt(String id, FLocation flocation); + + public abstract void setFactionAt(Faction faction, FLocation flocation); + + public abstract void removeAt(FLocation flocation); + + public abstract Set getAllClaims(String factionId); + + public abstract Set getAllClaims(Faction faction); + + // not to be confused with claims, ownership referring to further member-specific ownership of a claim + public abstract void clearOwnershipAt(FLocation flocation); + + public abstract void unclaimAll(String factionId); + + public abstract void unclaimAllInWorld(String factionId, World world); + + // Is this coord NOT completely surrounded by coords claimed by the same faction? + // Simpler: Is there any nearby coord with a faction other than the faction here? + public abstract boolean isBorderLocation(FLocation flocation); + + // Is this coord connected to any coord claimed by the specified faction? + public abstract boolean isConnectedLocation(FLocation flocation, Faction faction); + + public abstract boolean hasFactionWithin(FLocation flocation, Faction faction, int radius); + + //----------------------------------------------// + // Cleaner. Remove orphaned foreign keys + //----------------------------------------------// + + public abstract void clean(); + + //----------------------------------------------// + // Coord count + //----------------------------------------------// + + public abstract int getFactionCoordCount(String factionId); + + public abstract int getFactionCoordCount(Faction faction); + + public abstract int getFactionCoordCountInWorld(Faction faction, String worldName); + + //----------------------------------------------// + // Map generation + //----------------------------------------------// + + /** + * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction + * of decreasing z + */ + public abstract List getMap(FPlayer fPlayer, FLocation flocation, double inDegrees); + + public abstract void forceSave(); + + public abstract void forceSave(boolean sync); + + public abstract int load(); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/FLocation.java b/Factions/src/main/java/com/massivecraft/factions/FLocation.java new file mode 100644 index 0000000..6ea3efd --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/FLocation.java @@ -0,0 +1,322 @@ +package com.massivecraft.factions; + +import com.massivecraft.factions.cmd.claim.CmdCorner; +import com.massivecraft.factions.util.MiscUtil; +import net.royawesome.jlibnoise.MathHelper; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.WorldBorder; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Objects; +import java.util.Set; + +public class FLocation implements Serializable { + private static final long serialVersionUID = -8292915234027387983L; + private static final boolean worldBorderSupport; + private String worldName = "world"; + private int x = 0; + private int z = 0; + + static { + boolean worldBorderClassPresent = false; + try { + Class.forName("org.bukkit.WorldBorder"); + worldBorderClassPresent = true; + } catch (ClassNotFoundException ignored) { + } + + worldBorderSupport = worldBorderClassPresent; + } + + //----------------------------------------------// + // Constructors + //----------------------------------------------// + + public FLocation() { + + } + + public FLocation(String worldName, int x, int z) { + this.worldName = worldName; + this.x = x; + this.z = z; + } + + public FLocation(Location location) { + this(location.getWorld().getName(), blockToChunk(location.getBlockX()), blockToChunk(location.getBlockZ())); + } + + public FLocation(Chunk chunk) { + this(chunk.getWorld().getName(), chunk.getX(), chunk.getZ()); + } + + public FLocation(Player player) { + this(player.getLocation()); + } + + public FLocation(FPlayer fplayer) { + this(fplayer.getPlayer()); + } + + public FLocation(Block block) { + this(block.getLocation()); + } + + //----------------------------------------------// + // Getters and Setters + //----------------------------------------------// + + public String getWorldName() { + return worldName; + } + + public World getWorld() { + return Bukkit.getWorld(worldName); + } + + public void setWorldName(String worldName) { + this.worldName = worldName; + } + + public long getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public void addX(int n) { + this.x = this.x + n; + } + + public long getZ() { + return z; + } + + public void setZ(int z) { + this.z = z; + } + + public void addZ(int n) { + this.z = this.z + n; + } + + public String getCoordString() { + return "" + x + "," + z; + } + + public Chunk getChunk() { + return new Location(getWorld(), chunkToBlock(x), 0, chunkToBlock(z)).getChunk(); + } + + @Override + public String toString() { + return "[" + this.getWorldName() + "," + this.getCoordString() + "]"; + } + + public static FLocation fromString(String string) { + int index = string.indexOf(','); + int start = 1; + String worldName = string.substring(start, index); + start = index + 1; + index = string.indexOf(',', start); + int x = Integer.parseInt(string.substring(start, index)); + int y = Integer.parseInt(string.substring(index + 1, string.length() - 1)); + return new FLocation(worldName, x, y); + } + + //----------------------------------------------// + // Block/Chunk/Region Value Transformation + //----------------------------------------------// + + // bit-shifting is used because it's much faster than standard division and multiplication + public static int blockToChunk(int blockVal) { // 1 chunk is 16x16 blocks + return blockVal >> 4; // ">> 4" == "/ 16" + } + + public static int blockToRegion(int blockVal) { // 1 region is 512x512 blocks + return blockVal >> 9; // ">> 9" == "/ 512" + } + + public static int chunkToRegion(int chunkVal) { // 1 region is 32x32 chunks + return chunkVal >> 5; // ">> 5" == "/ 32" + } + + public static int chunkToBlock(int chunkVal) { + return chunkVal << 4; // "<< 4" == "* 16" + } + + public static int regionToBlock(int regionVal) { + return regionVal << 9; // "<< 9" == "* 512" + } + + public static int regionToChunk(int regionVal) { + return regionVal << 5; // "<< 5" == "* 32" + } + + //----------------------------------------------// + // Misc Geometry + //----------------------------------------------// + + public FLocation getRelative(int dx, int dz) { + return new FLocation(this.worldName, this.x + dx, this.z + dz); + } + + public double getDistanceTo(FLocation that) { + double dx = that.x - this.x; + double dz = that.z - this.z; + return Math.sqrt(dx * dx + dz * dz); + } + + public double getDistanceSquaredTo(FLocation that) { + double dx = that.x - this.x; + double dz = that.z - this.z; + return dx * dx + dz * dz; + } + + public boolean isInChunk(Location loc) { + if (loc == null) { + return false; + } + Chunk chunk = loc.getChunk(); + return loc.getWorld().getName().equalsIgnoreCase(getWorldName()) && chunk.getX() == x && chunk.getZ() == z; + } + + public boolean isInCorner() { + return getCorner() != null; + } + + public enum EnumCorner{ + POS_POS, + NEG_NEG, + POS_NEG, + NEG_POS + } + + public EnumCorner getCorner() { + return getCorner(this.getChunk().getBlock(0, 0, 0).getLocation()); + } + + public EnumCorner getCorner(Location location){ + int cx = location.getBlockX() >> 4; + int cz = location.getBlockZ() >> 4; + + Location center = location.getWorld().getWorldBorder().getCenter(); + + int radius = (int) (location.getWorld().getWorldBorder().getSize() / 2D); + + double maxX = MathHelper.floor((center.getX() + radius - 0.1) / 16.0D); + double maxZ = MathHelper.floor((center.getZ() + radius - 0.1) / 16.0D); + + double minX = MathHelper.floor((center.getBlockX() - radius) / 16.0D); + double minZ = MathHelper.floor((center.getBlockZ() - radius) / 16.0D); + + if(cx == maxX && cz == maxZ)return EnumCorner.POS_POS; + if(cx == maxX && cz == minZ)return EnumCorner.POS_NEG; + if(cx == minX && cz == maxZ)return EnumCorner.NEG_POS; + if(cx == minX && cz == minZ)return EnumCorner.NEG_NEG; + return null; + } + + /** + * Checks if the chunk represented by this FLocation is outside the world border + * + * @param buffer the number of chunks from the border that will be treated as "outside" + * @return whether this location is outside of the border + */ + public boolean isOutsideWorldBorder(int buffer) { + if (!worldBorderSupport) { + return false; + } + + WorldBorder border = getWorld().getWorldBorder(); + + Location center = border.getCenter(); + double size = border.getSize(); + + int bufferBlocks = buffer << 4; + + double borderMinX = (center.getX() - size / 2.0D) + bufferBlocks; + double borderMinZ = (center.getZ() - size / 2.0D) + bufferBlocks; + double borderMaxX = (center.getX() + size / 2.0D) - bufferBlocks; + double borderMaxZ = (center.getZ() + size / 2.0D) - bufferBlocks; + + int chunkMinX = this.x << 4; + int chunkMaxX = chunkMinX | 15; + int chunkMinZ = this.z << 4; + int chunkMaxZ = chunkMinZ | 15; + + return (chunkMinX >= borderMaxX) || (chunkMinZ >= borderMaxZ) || (chunkMaxX <= borderMinX) || (chunkMaxZ <= borderMinZ); + } + + //----------------------------------------------// + // Some Geometry + //----------------------------------------------// + public Set getCircle(double radius) { + double radiusSquared = radius * radius; + + Set ret = new LinkedHashSet<>(); + if (radius <= 0) { + return ret; + } + + int xfrom = (int) Math.floor(this.x - radius); + int xto = (int) Math.ceil(this.x + radius); + int zfrom = (int) Math.floor(this.z - radius); + int zto = (int) Math.ceil(this.z + radius); + + for (int x = xfrom; x <= xto; x++) { + for (int z = zfrom; z <= zto; z++) { + FLocation potential = new FLocation(this.worldName, x, z); + if (this.getDistanceSquaredTo(potential) <= radiusSquared) { + ret.add(potential); + } + } + } + + return ret; + } + + public static HashSet getArea(FLocation from, FLocation to) { + HashSet ret = new HashSet<>(); + + for (long x : MiscUtil.range(from.getX(), to.getX())) { + for (long z : MiscUtil.range(from.getZ(), to.getZ())) { + ret.add(new FLocation(from.getWorldName(), (int) x, (int) z)); + } + } + + return ret; + } + + //----------------------------------------------// + // Comparison + //----------------------------------------------// + + @Override + public int hashCode() { + // should be fast, with good range and few hash collisions: (x * 512) + z + worldName.hashCode + return (this.x << 9) + this.z + (this.worldName != null ? this.worldName.hashCode() : 0); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof FLocation)) { + return false; + } + + FLocation that = (FLocation) obj; + return this.x == that.x && this.z == that.z && (Objects.equals(this.worldName, that.worldName)); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/FPlayer.java b/Factions/src/main/java/com/massivecraft/factions/FPlayer.java new file mode 100644 index 0000000..313d679 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/FPlayer.java @@ -0,0 +1,306 @@ +package com.massivecraft.factions; + +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.ChatMode; +import com.massivecraft.factions.util.SpiralTask; +import com.massivecraft.factions.util.WarmUpUtil; +import mkremins.fanciful.FancyMessage; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + + +/** + * Logged in players always have exactly one FPlayer instance. Logged out players may or may not have an FPlayer + * instance. They will always have one if they are part of a faction. This is because only players with a faction are + * saved to disk (in order to not waste disk space). + *

+ * The FPlayer is linked to a minecraft player using the player name. + *

+ * The same instance is always returned for the same player. This means you can use the == operator. No .equals method + * necessary. + */ + +public interface FPlayer extends EconomyParticipator { + void login(); + + void logout(); + + Faction getFaction(); + + String getFactionId(); + + boolean hasFaction(); + + void setFaction(Faction faction); + + boolean willAutoLeave(); + + boolean attemptRotateIn(); + + void setAutoLeave(boolean autoLeave); + + long getLastFrostwalkerMessage(); + + void setLastFrostwalkerMessage(); + + void setMonitorJoins(boolean monitor); + + boolean isMonitoringJoins(); + + Role getRole(); + + void setRole(Role role); + + boolean shouldTakeFallDamage(); + + void setTakeFallDamage(boolean fallDamage); + + double getPowerBoost(); + + void setPowerBoost(double powerBoost); + + Faction getAutoClaimFor(); + + void setAutoClaimFor(Faction faction); + + boolean isAutoSafeClaimEnabled(); + + void setIsAutoSafeClaimEnabled(boolean enabled); + + boolean isAutoWarClaimEnabled(); + + void setIsAutoWarClaimEnabled(boolean enabled); + + boolean isAdminBypassing(); + + boolean isVanished(); + + void setIsAdminBypassing(boolean val); + + void setChatMode(ChatMode chatMode); + + ChatMode getChatMode(); + + void setIgnoreAllianceChat(boolean ignore); + + boolean isIgnoreAllianceChat(); + + void setSpyingChat(boolean chatSpying); + + boolean isSpyingChat(); + + boolean showScoreboard(); + + void setShowScoreboard(boolean show); + + void resetFactionData(boolean doSpoutUpdate); + + void resetFactionData(); + + long getLastLoginTime(); + + void setLastLoginTime(long lastLoginTime); + + boolean isMapAutoUpdating(); + + void setMapAutoUpdating(boolean mapAutoUpdating); + + boolean hasLoginPvpDisabled(); + + FLocation getLastStoodAt(); + + void setLastStoodAt(FLocation flocation); + + String getTitle(); + + void setTitle(CommandSender sender, String title); + + String getName(); + + String getTag(); + + // Base concatenations: + + String getNameAndSomething(String something); + + String getNameAndTitle(); + + String getNameAndTag(); + + // Colored concatenations: + // These are used in information messages + + String getNameAndTitle(Faction faction); + + String getNameAndTitle(FPlayer fplayer); + + // Chat Tag: + // These are injected into the format of global chat messages. + + String getChatTag(); + + // Colored Chat Tag + String getChatTag(Faction faction); + + String getChatTag(FPlayer fplayer); + + int getKills(); + + int getDeaths(); + + boolean isStealth(); + + void setStealth(boolean stealth); + + + // ------------------------------- + // Relation and relation colors + // ------------------------------- + + Relation getRelationToLocation(); + + //----------------------------------------------// + // Health + //----------------------------------------------// + void heal(int amnt); + + + //----------------------------------------------// + // Power + //----------------------------------------------// + double getPower(); + + void alterPower(double delta); + + double getPowerMax(); + + double getPowerMin(); + + int getPowerRounded(); + + int getPowerMaxRounded(); + + int getPowerMinRounded(); + + void updatePower(); + + void losePowerFromBeingOffline(); + + void onDeath(); + + //----------------------------------------------// + // Territory + //----------------------------------------------// + boolean isInOwnTerritory(); + + boolean isInOthersTerritory(); + + boolean isInAllyTerritory(); + + boolean isInNeutralTerritory(); + + boolean isInEnemyTerritory(); + + void sendFactionHereMessage(Faction from); + + // ------------------------------- + // Actions + // ------------------------------- + + void leave(boolean makePay); + + boolean canClaimForFaction(Faction forFaction); + + boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure); + + boolean canClaimForFactionAtLocation(Faction forFaction, FLocation location, boolean notifyFailure); + + boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure); + + boolean attemptClaim(Faction forFaction, FLocation location, boolean notifyFailure); + + boolean attemptClaim(Faction forFaction, FLocation location, boolean notifyFailure, SpiralTask spiralTask); + + String getId(); + + Player getPlayer(); + + Location getLocation(); + + FLocation getFLocation(); + + boolean isOnline(); + + void sendMessage(String message); + + void sendMessage(List messages); + + void sendFancyMessage(FancyMessage message); + + void sendFancyMessage(List message); + + int getMapHeight(); + + void setMapHeight(int height); + + boolean isOnlineAndVisibleTo(Player me); + + void remove(); + + boolean isOffline(); + + void setId(String id); + + boolean isFlying(); + + void setFlying(boolean fly); + + void setFlying(boolean fly, boolean damage); + + boolean isAutoFlying(); + + void setAutoFlying(boolean autoFly); + + boolean canFlyAtLocation(); + + boolean canFlyAtLocation(FLocation location); + + boolean canFlyInFactionTerritory(Faction faction); + + boolean isSeeingChunk(); + + void setSeeingChunk(boolean seeingChunk); + + boolean isInspectMode(); + + void setInspectMode(boolean status); + + boolean getFlyTrailsState(); + + void setFlyTrailsState(boolean state); + + String getFlyTrailsEffect(); + + void setFlyTrailsEffect(String effect); + + // ------------------------------- + // Warmups + // ------------------------------- + + boolean isWarmingUp(); + + WarmUpUtil.Warmup getWarmupType(); + + void addWarmup(WarmUpUtil.Warmup warmup, int taskId); + + void stopWarmup(); + + void clearWarmup(); + + void setOfflinePlayer(Player player); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/FPlayers.java b/Factions/src/main/java/com/massivecraft/factions/FPlayers.java new file mode 100644 index 0000000..2d05349 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/FPlayers.java @@ -0,0 +1,37 @@ +package com.massivecraft.factions; + +import com.massivecraft.factions.data.json.JSONFPlayers; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import java.util.Collection; + +public abstract class FPlayers { + protected static FPlayers instance = getFPlayersImpl(); + + public abstract void clean(); + + public static FPlayers getInstance() { + return instance; + } + + private static FPlayers getFPlayersImpl() { + return new JSONFPlayers(); + } + + public abstract Collection getOnlinePlayers(); + + public abstract FPlayer getByPlayer(Player player); + + public abstract Collection getAllFPlayers(); + + public abstract void forceSave(); + + public abstract void forceSave(boolean sync); + + public abstract FPlayer getByOfflinePlayer(OfflinePlayer player); + + public abstract FPlayer getById(String string); + + public abstract int load(); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/Faction.java b/Factions/src/main/java/com/massivecraft/factions/Faction.java new file mode 100644 index 0000000..a563ae5 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/Faction.java @@ -0,0 +1,324 @@ +package com.massivecraft.factions; + +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.BanInfo; +import com.massivecraft.factions.util.LazyLocation; +import com.massivecraft.factions.util.StrikeInfo; +import com.massivecraft.factions.util.UpgradeType; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public interface Faction extends EconomyParticipator { + Map> getAnnouncements(); + + Map getWarps(); + + LazyLocation getWarp(String name); + + void setWarp(String name, LazyLocation loc); + + boolean isWarp(String name); + + int getMaxWarps(); + + boolean hasWarpPassword(String warp); + + boolean isWarpPassword(String warp, String password); + + void setWarpPassword(String warp, String password); + + boolean removeWarp(String name); + + void clearWarps(); + + int getMaxVaults(); + + void setMaxVaults(int value); + + void addAnnouncement(FPlayer fPlayer, String msg); + + void sendUnreadAnnouncements(FPlayer fPlayer); + + void removeAnnouncements(FPlayer fPlayer); + + void setPayPal(String payPal); + + String getPayPal(); + + String getAltJoinString(); + + String setAltOpen(); + + void setAltClosed(); + + Set getInvites(); + + String getId(); + + void invite(FPlayer fplayer); + + void deinvite(FPlayer fplayer); + + boolean isInvited(FPlayer fplayer); + + void ban(FPlayer target, FPlayer banner); + + void unban(FPlayer player); + + boolean isBanned(FPlayer player); + + Set getBannedPlayers(); + + boolean getOpen(); + + int getMaxTNT(); + + int getUpgrade(UpgradeType type); + + void setOpen(boolean isOpen); + + boolean isPeaceful(); + + void setPeaceful(boolean isPeaceful); + + void setPeacefulExplosionsEnabled(boolean val); + + boolean getPeacefulExplosionsEnabled(); + + boolean noExplosionsInTerritory(); + + boolean isPermanent(); + + void setPermanent(boolean isPermanent); + + String getTag(); + + String getTag(String prefix); + + String getTag(Faction otherFaction); + + String getTag(FPlayer otherFplayer); + + void setTag(String str); + + String getComparisonTag(); + + String getDescription(); + + Inventory getChest(); + + void setDescription(String value); + + void setHome(Location home); + + void delHome(); + + boolean hasHome(); + + Location getHome(); + + long getFoundedDate(); + + void setFoundedDate(long newDate); + + void confirmValidHome(); + + boolean noPvPInTerritory(); + + boolean noMonstersInTerritory(); + + boolean isNormal(); + + @Deprecated + boolean isNone(); + + boolean isWilderness(); + + boolean isSafeZone(); + + boolean isWarZone(); + + boolean isPlayerFreeType(); + + void setLastDeath(long time); + + int getKills(); + + int getDeaths(); + + boolean hasAccess(boolean online, Permissible permissible, PermissibleAction permissibleAction); + + boolean hasAccess(FPlayer player, PermissibleAction permissibleAction); + + boolean isLocked(boolean online, Permissible permissible, PermissibleAction permissibleAction); + + boolean setPermission(boolean online, Permissible permissible, PermissibleAction permissibleAction, boolean value); + + void checkPerms(); + + void resetPerms(); + + Map> getPermissions(); + + int getLandRounded(); + + int getLandRoundedInWorld(String worldName); + + int getTNTBank(); + + void setTNTBank(int amount); + + // ------------------------------- + // Relation and relation colors + // ------------------------------- + + Relation getRelationWish(Faction otherFaction); + + void setRelationWish(Faction otherFaction, Relation relation); + + int getRelationCount(Relation relation); + + // ----------------------------------------------// + // DTR + // ----------------------------------------------// + + double getDTR(); + + double getDTRWithoutUpdate(); + + void setDTR(double dtr); + + long getLastDTRUpdateTime(); + + long getFrozenDTRUntilTime(); + + void setFrozenDTR(long time); + + boolean isFrozenDTR(); + + // ----------------------------------------------// + // Power + // ----------------------------------------------// + double getPower(); + + double getPowerMax(); + + int getPowerRounded(); + + int getPowerMaxRounded(); + + Integer getPermanentPower(); + + void setPermanentPower(Integer permanentPower); + + boolean hasPermanentPower(); + + double getPowerBoost(); + + void setPowerBoost(double powerBoost); + + boolean hasLandInflation(); + + boolean isPowerFrozen(); + + // ------------------------------- + // FPlayers + // ------------------------------- + + // maintain the reference list of FPlayers in this faction + void refreshFPlayers(); + + boolean addFPlayer(FPlayer fplayer); + + boolean removeFPlayer(FPlayer fplayer); + + List getStrikes(); + + void addStrike(String reason, long time); + + boolean takeStrike(int index); + + int getSize(); + + Set getFPlayers(); + + Set getFPlayersWhereOnline(boolean online); + + Set getFPlayersWhereOnline(boolean online, FPlayer viewer); + + FPlayer getFPlayerAdmin(); + + FPlayer getLeader(); + + List getFPlayersWhereRole(Role role); + + List getOnlinePlayers(); + + // slightly faster check than getOnlinePlayers() if you just want to see if + // there are any players online + boolean hasPlayersOnline(); + + void memberLoggedOff(); + + // used when current leader is about to be removed from the faction; + // promotes new leader, or disbands faction if no other members left + void promoteNewLeader(); + + Role getDefaultRole(); + + void setDefaultRole(Role role); + + void sendMessage(String message); + + void sendMessage(List messages); + + // ----------------------------------------------// + // Ownership of specific claims + // ----------------------------------------------// + + Map> getClaimOwnership(); + + void clearAllClaimOwnership(); + + void clearClaimOwnership(FLocation loc); + + void clearClaimOwnership(FPlayer player); + + int getCountOfClaimsWithOwners(); + + boolean doesLocationHaveOwnersSet(FLocation loc); + + boolean isPlayerInOwnerList(FPlayer player, FLocation loc); + + void setPlayerAsOwner(FPlayer player, FLocation loc); + + void removePlayerAsOwner(FPlayer player, FLocation loc); + + Set getOwnerList(FLocation loc); + + String getOwnerListString(FLocation loc); + + boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc); + + // ----------------------------------------------// + // Persistance and entity management + // ----------------------------------------------// + void remove(); + + Set getAllClaims(); + + void setId(String id); + + OfflinePlayer getOfflinePlayer(); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/Factions.java b/Factions/src/main/java/com/massivecraft/factions/Factions.java new file mode 100644 index 0000000..9befd23 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/Factions.java @@ -0,0 +1,51 @@ +package com.massivecraft.factions; + +import com.massivecraft.factions.data.json.JSONFactions; + +import java.util.ArrayList; +import java.util.Set; + +public abstract class Factions { + protected static Factions instance = getFactionsImpl(); + + public abstract Faction getFactionById(String id); + + public abstract Faction getByTag(String str); + + public abstract Faction getBestTagMatch(String start); + + public abstract boolean isTagTaken(String str); + + public abstract boolean isValidFactionId(String id); + + public abstract Faction createFaction(); + + public abstract void removeFaction(String id); + + public abstract Set getFactionTags(); + + public abstract ArrayList getAllFactions(); + + @Deprecated + public abstract Faction getNone(); + + public abstract Faction getWilderness(); + + public abstract Faction getSafeZone(); + + public abstract Faction getWarZone(); + + public abstract void forceSave(); + + public abstract void forceSave(boolean sync); + + public static Factions getInstance() { + return instance; + } + + private static Factions getFactionsImpl() { + return new JSONFactions(); + } + + public abstract int load(); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/FactionsAPI.java b/Factions/src/main/java/com/massivecraft/factions/FactionsAPI.java new file mode 100644 index 0000000..1e301e4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/FactionsAPI.java @@ -0,0 +1,39 @@ +package com.massivecraft.factions; + +import org.bukkit.entity.Player; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.plugin.Plugin; + +import java.util.Set; + +public interface FactionsAPI { + /** + * Gets the current API version. + * + * @return current API version + * @since API 5 + */ + default int getAPIVersion() { + return 5; + } + + boolean isAnotherPluginHandlingChat(); + + void setHandlingChat(Plugin plugin, boolean handling); + + boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event); + + boolean isPlayerFactionChatting(Player player); + + String getPlayerFactionTag(Player player); + + String getPlayerFactionTagRelation(Player speaker, Player listener); + + String getPlayerTitle(Player player); + + Set getFactionTags(); + + Set getPlayersInFaction(String factionTag); + + Set getOnlinePlayersInFaction(String factionTag); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/FactionsPlugin.java b/Factions/src/main/java/com/massivecraft/factions/FactionsPlugin.java new file mode 100644 index 0000000..2e4a5a6 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/FactionsPlugin.java @@ -0,0 +1,1021 @@ +package com.massivecraft.factions; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.massivecraft.factions.cmd.FCmdRoot; +import com.massivecraft.factions.config.ConfigManager; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.data.SaveTask; +import com.massivecraft.factions.event.FactionCreateEvent; +import com.massivecraft.factions.event.FactionEvent; +import com.massivecraft.factions.event.FactionRelationEvent; +import com.massivecraft.factions.integration.*; +import com.massivecraft.factions.integration.permcontext.ContextManager; +import com.massivecraft.factions.landraidcontrol.LandRaidControl; +import com.massivecraft.factions.listeners.*; +import com.massivecraft.factions.listeners.versionspecific.PortalHandler; +import com.massivecraft.factions.listeners.versionspecific.PortalListenerLegacy; +import com.massivecraft.factions.listeners.versionspecific.PortalListener_114; +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.PermissionsMapTypeAdapter; +import com.massivecraft.factions.struct.ChatMode; +import com.massivecraft.factions.util.*; +import com.massivecraft.factions.util.material.MaterialDb; +import com.massivecraft.factions.util.particle.BukkitParticleProvider; +import com.massivecraft.factions.util.particle.PacketParticleProvider; +import com.massivecraft.factions.util.particle.ParticleProvider; +import io.papermc.lib.PaperLib; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredListener; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; + +import java.io.*; +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class FactionsPlugin extends JavaPlugin implements FactionsAPI { + + // Our single plugin instance. + // Single 4 life. + private static FactionsPlugin instance; + private Permission perms = null; + private static int mcVersion; + + public static FactionsPlugin getInstance() { + return instance; + } + + public static int getMCVersion() { + return mcVersion; + } + + private final ConfigManager configManager = new ConfigManager(this); + + private Integer saveTask = null; + private boolean autoSave = true; + private boolean loadSuccessful = false; + + private boolean isSOTW = false; + + public void setSOTW(boolean on){ + isSOTW = on; + } + + public boolean isSOTW() { + return isSOTW; + } + + // Some utils + private Persist persist; + private TextUtil txt; + private WorldUtil worldUtil; + + public TextUtil txt() { + return txt; + } + + public WorldUtil worldUtil() { + return worldUtil; + } + + public void grumpException(RuntimeException e) { + this.grumpyExceptions.add(e); + } + + private PermUtil permUtil; + + // Persist related + private Gson gson; + + // holds f stuck start times + private final Map timers = new HashMap<>(); + + //holds f stuck taskids + private final Map stuckMap = new HashMap<>(); + + // Persistence related + private boolean locked = false; + + private Integer autoLeaveTask = null; + + private ClipPlaceholderAPIManager clipPlaceholderAPIManager; + private boolean mvdwPlaceholderAPIManager = false; + private final Set pluginsHandlingChat = Collections.newSetFromMap(new ConcurrentHashMap<>()); + + private SeeChunkUtil seeChunkUtil; + private ParticleProvider particleProvider; + private IWorldguard worldguard; + private LandRaidControl landRaidControl; + private boolean luckPermsSetup; + private IntegrationManager integrationManager; + + private Metrics metrics; + private final Pattern factionsVersionPattern = Pattern.compile("b(\\d{1,4})"); + private String updateMessage; + private int buildNumber = -1; + private UUID serverUUID; + private String startupLog; + private String startupExceptionLog; + private final List grumpyExceptions = new ArrayList<>(); + + public FCmdRoot cmdBase; + + public FactionsPlugin() { + instance = this; + } + + @Override + public void onEnable() { + this.loadSuccessful = false; + StringBuilder startupBuilder = new StringBuilder(); + StringBuilder startupExceptionBuilder = new StringBuilder(); + Handler handler = new Handler() { + @Override + public void publish(LogRecord record) { + if (record.getMessage() != null && record.getMessage().contains("Loaded class {0}")) { + return; + } + startupBuilder.append('[').append(record.getLevel().getName()).append("] ").append(record.getMessage()).append('\n'); + if (record.getThrown() != null) { + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + record.getThrown().printStackTrace(printWriter); + startupExceptionBuilder.append('[').append(record.getLevel().getName()).append("] ").append(record.getMessage()).append('\n') + .append(stringWriter).append('\n'); + } + } + + @Override + public void flush() { + + } + + @Override + public void close() throws SecurityException { + + } + }; + getLogger().addHandler(handler); + getLogger().info("=== Starting up! ==="); + long timeEnableStart = System.currentTimeMillis(); + + if (!this.grumpyExceptions.isEmpty()) { + this.grumpyExceptions.forEach(e -> getLogger().log(Level.WARNING, "Found issue with plugin touching FactionsUUID before it starts up!", e)); + } + + // Ensure basefolder exists! + this.getDataFolder().mkdirs(); + + byte[] m = Bukkit.getMotd().getBytes(StandardCharsets.UTF_8); + if (m.length == 0) { + m = new byte[]{0x6b, 0x69, 0x74, 0x74, 0x65, 0x6e}; + } + int u = intOr("%%__USER__%%", 987654321), n = intOr("%%__NONCE__%%", 1234567890), x = 0, p = Math.min(Bukkit.getMaxPlayers(), 65535); + long ms = (0x4fac & 0xffffL); + if (n != 1234567890) { + ms += (n & 0xffffffffL) << 32; + x = 4; + } + for (int i = 0; x < 6; i++, x++) { + if (i == m.length) { + i = 0; + } + ms += ((m[i] & 0xFFL) << (8 + (8 * (6 - x)))); + } + this.serverUUID = new UUID(ms, ((0xaf & 0xffL) << 56) + ((0xac & 0xffL) << 48) + (u & 0xffffffffL) + ((p & 0xffffL) << 32)); + + // Version party + Pattern versionPattern = Pattern.compile("1\\.(\\d{1,2})(?:\\.(\\d{1,2}))?"); + Matcher versionMatcher = versionPattern.matcher(this.getServer().getVersion()); + getLogger().info(""); + getLogger().info("Factions UUID!"); + getLogger().info("Version " + this.getDescription().getVersion()); + getLogger().info(""); + getLogger().info("Need support? https://factions.support/help/"); + getLogger().info(""); + Integer versionInteger = null; + if (versionMatcher.find()) { + try { + int minor = Integer.parseInt(versionMatcher.group(1)); + String patchS = versionMatcher.group(2); + int patch = (patchS == null || patchS.isEmpty()) ? 0 : Integer.parseInt(patchS); + versionInteger = (minor * 100) + patch; + getLogger().info("Detected Minecraft " + versionMatcher.group()); + } catch (NumberFormatException ignored) { + } + } + if (versionInteger == null) { + getLogger().warning(""); + getLogger().warning("Could not identify version. Going with least supported version, 1.7.10."); + getLogger().warning("Please visit our support live chat for help - https://factions.support/help/"); + getLogger().warning(""); + versionInteger = 710; + } + mcVersion = versionInteger; + if (mcVersion < 808) { + getLogger().info(""); + getLogger().warning("FactionsUUID works better with at least Minecraft 1.8.8"); + } + getLogger().info(""); + this.buildNumber = this.getBuildNumber(this.getDescription().getVersion()); + + this.getLogger().info("Server UUID " + this.serverUUID); + + loadLang(); + this.gson = this.getGsonBuilder().create(); + + // Load Conf from disk + this.configManager.startup(); + + if (this.conf().data().json().useEfficientStorage()) { + getLogger().info("Using space efficient (less readable) storage."); + } + + this.landRaidControl = LandRaidControl.getByName(this.conf().factions().landRaidControl().getSystem()); + + File dataFolder = new File(this.getDataFolder(), "data"); + if (!dataFolder.exists()) { + dataFolder.mkdir(); + } + + // Load Material database + MaterialDb.load(); + + // Create Utility Instances + this.permUtil = new PermUtil(this); + this.persist = new Persist(this); + this.worldUtil = new WorldUtil(this); + + this.txt = new TextUtil(); + initTXT(); + + // attempt to get first command defined in plugin.yml as reference command, if any commands are defined in there + // reference command will be used to prevent "unknown command" console messages + String refCommand = ""; + try { + Map> refCmd = this.getDescription().getCommands(); + if (refCmd != null && !refCmd.isEmpty()) { + refCommand = (String) (refCmd.keySet().toArray()[0]); + } + } catch (ClassCastException ignored) { + } + + // Register recurring tasks + if (saveTask == null && this.conf().factions().other().getSaveToFileEveryXMinutes() > 0.0) { + long saveTicks = (long) (20 * 60 * this.conf().factions().other().getSaveToFileEveryXMinutes()); // Approximately every 30 min by default + saveTask = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(this), saveTicks, saveTicks); + } + + int loadedPlayers = FPlayers.getInstance().load(); + int loadedFactions = Factions.getInstance().load(); + for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { + Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId()); + if (faction == null) { + log("Invalid faction id on " + fPlayer.getName() + ":" + fPlayer.getFactionId()); + fPlayer.resetFactionData(false); + continue; + } + faction.addFPlayer(fPlayer); + } + int loadedClaims = Board.getInstance().load(); + Board.getInstance().clean(); + FactionsPlugin.getInstance().getLogger().info("Loaded " + loadedPlayers + " players in " + loadedFactions + " factions with " + loadedClaims + " claims"); + + // Add Base Commands + cmdBase = new FCmdRoot(); + + ContextManager.init(this); + if (getServer().getPluginManager().getPlugin("PermissionsEx") != null) { + if (getServer().getPluginManager().getPlugin("PermissionsEx").getDescription().getVersion().startsWith("1")) { + getLogger().info(" "); + getLogger().warning("Notice: PermissionsEx version 1.x is dead. We suggest using LuckPerms (or PEX 2.0 when available). https://luckperms.net/"); + getLogger().info(" "); + } + } + if (getServer().getPluginManager().getPlugin("GroupManager") != null) { + getLogger().info(" "); + getLogger().warning("Notice: GroupManager died in 2014. We suggest using LuckPerms instead. https://luckperms.net/"); + getLogger().info(" "); + } + Plugin lwc = getServer().getPluginManager().getPlugin("LWC"); + if (lwc != null && lwc.getDescription().getWebsite() != null && !lwc.getDescription().getWebsite().contains("extended")) { + getLogger().info(" "); + getLogger().warning("Notice: LWC Extended is the updated, and best supported, continuation of LWC. https://www.spigotmc.org/resources/lwc-extended.69551/"); + getLogger().info(" "); + } + + // start up task which runs the autoLeaveAfterDaysOfInactivity routine + startAutoLeaveTask(false); + + // Run before initializing listeners to handle reloads properly. + if (mcVersion < 1300) { // Before 1.13 + particleProvider = new PacketParticleProvider(); + } else { + particleProvider = new BukkitParticleProvider(); + } + getLogger().info(txt.parse("Using %1s as a particle provider", particleProvider.name())); + + if (conf().commands().seeChunk().isParticles()) { + double delay = Math.floor(conf().commands().seeChunk().getParticleUpdateTime() * 20); + seeChunkUtil = new SeeChunkUtil(); + seeChunkUtil.runTaskTimer(this, 0, (long) delay); + } + // End run before registering event handlers. + + // Register Event Handlers + getServer().getPluginManager().registerEvents(new FactionsPlayerListener(this), this); + getServer().getPluginManager().registerEvents(new FactionsChatListener(this), this); + getServer().getPluginManager().registerEvents(new FactionsEntityListener(this), this); + getServer().getPluginManager().registerEvents(new FactionsExploitListener(this), this); + getServer().getPluginManager().registerEvents(new FactionsBlockListener(this), this); + if (mcVersion >= 800) { + getServer().getPluginManager().registerEvents(new OneEightPlusListener(this), this); + } + + try{ + Class.forName("net.techcable.tacospigot.event.entity.SpawnerPreSpawnEvent"); + + //getServer().getPluginManager().registerEvents(new FactionsSpawnerBoostListener(this), this); + }catch(ClassNotFoundException exc){ + Bukkit.getLogger().severe("[Factions] - Not able to register spawner boost me.astropvp.outpost.listener as you are not using taco spigot!"); + } + + // Version specific portal me.astropvp.outpost.listener check. + if (mcVersion >= 1400) { // Starting with 1.14 + getServer().getPluginManager().registerEvents(new PortalListener_114(this), this); + } else { + getServer().getPluginManager().registerEvents(new PortalListenerLegacy(new PortalHandler()), this); + } + + // since some other plugins execute commands directly through this command interface, provide it + this.getCommand(refCommand).setExecutor(cmdBase); + + if (conf().commands().fly().isEnable()) { + FlightUtil.start(); + } + + new TitleAPI(); + + if (ChatColor.stripColor(TL.NOFACTION_PREFIX.toString()).equals("[4-]")) { + getLogger().warning("Looks like you have an old, mistaken 'nofactions-prefix' in your lang.yml. It currently displays [4-] which is... strange."); + } + + // Integration time + getServer().getPluginManager().registerEvents(integrationManager = new IntegrationManager(this), this); + + new BukkitRunnable() { + @Override + public void run() { + Econ.setup(); + setupPermissions(); + if (perms != null) { + getLogger().info("Using Vault with permissions plugin " + perms.getName()); + } + cmdBase.done(); + // Grand metrics adventure! + setupMetrics(); + getLogger().removeHandler(handler); + startupLog = startupBuilder.toString(); + startupExceptionLog = startupExceptionBuilder.toString(); + } + }.runTask(this); + + getLogger().info("=== Ready to go after " + (System.currentTimeMillis() - timeEnableStart) + "ms! ==="); + this.loadSuccessful = true; + } + + private int intOr(String in, int or) { + try { + return Integer.parseInt(in); + } catch (NumberFormatException ignored) { + return or; + } + } + + private void setupMetrics() { + this.metrics = new Metrics(this); + + // Version + String verString = this.getDescription().getVersion().replace("${build.number}", "selfbuilt"); + Pattern verPattern = Pattern.compile("U([\\d.]+)-b(.*)"); + Matcher matcher = verPattern.matcher(verString); + final String fuuidVersion; + final String fuuidBuild; + if (matcher.find()) { + fuuidVersion = matcher.group(1); + fuuidBuild = matcher.group(2); + } else { + fuuidVersion = "Unknown"; + fuuidBuild = verString; + } + this.metricsDrillPie("fuuid_version", () -> { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + entry.put(fuuidBuild, 1); + map.put(fuuidVersion, entry); + return map; + }); + + // Essentials + Plugin ess = Essentials.getEssentials(); + this.metricsDrillPie("essentials", () -> this.metricsPluginInfo(ess)); + if (ess != null) { + this.metricsSimplePie("essentials_delete_homes", () -> "" + conf().factions().other().isDeleteEssentialsHomes()); + this.metricsSimplePie("essentials_home_teleport", () -> "" + this.conf().factions().homes().isTeleportCommandEssentialsIntegration()); + } + + // Vault + Plugin vault = Bukkit.getServer().getPluginManager().getPlugin("Vault"); + this.metricsDrillPie("vault", () -> this.metricsPluginInfo(vault)); + if (vault != null) { + this.metricsDrillPie("vault_perms", () -> this.metricsInfo(perms, perms::getName)); + this.metricsDrillPie("vault_econ", () -> { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + entry.put(Econ.getEcon() == null ? "none" : Econ.getEcon().getName(), 1); + map.put((this.conf().economy().isEnabled() && Econ.getEcon() != null) ? "enabled" : "disabled", entry); + return map; + }); + } + + // WorldGuard + IWorldguard wg = this.getWorldguard(); + String wgVersion = wg == null ? "nope" : wg.getVersion(); + this.metricsDrillPie("worldguard", () -> this.metricsInfo(wg, () -> wgVersion)); + + // Clip Placeholder + Plugin clipPlugin = getServer().getPluginManager().getPlugin("PlaceholderAPI"); + this.metricsDrillPie("clipplaceholder", () -> this.metricsPluginInfo(clipPlugin)); + + // MVdW Placeholder + Plugin mvdw = getServer().getPluginManager().getPlugin("MVdWPlaceholderAPI"); + this.metricsDrillPie("mvdwplaceholder", () -> this.metricsPluginInfo(mvdw)); + + // Overall stats + this.metricsLine("factions", () -> Factions.getInstance().getAllFactions().size() - 3); + this.metricsSimplePie("scoreboard", () -> "" + conf().scoreboard().constant().isEnabled()); + + // Event listeners + this.metricsDrillPie("event_listeners", () -> { + Set pluginsListening = this.getPlugins(FactionEvent.getHandlerList(), FactionCreateEvent.getHandlerList(), FactionRelationEvent.getHandlerList()); + Map> map = new HashMap<>(); + for (Plugin plugin : pluginsListening) { + if (plugin.getName().equalsIgnoreCase("factions")) { + continue; + } + Map entry = new HashMap<>(); + entry.put(plugin.getDescription().getVersion(), 1); + map.put(plugin.getName(), entry); + } + return map; + }); + } + + private Set getPlugins(HandlerList... handlerLists) { + return Arrays.stream(handlerLists) + .flatMap(handlerList -> getPlugins(handlerList).stream()) + .collect(Collectors.toSet()); + } + + private Set getPlugins(HandlerList handlerList) { + return Arrays.stream(handlerList.getRegisteredListeners()) + .map(RegisteredListener::getPlugin) + .collect(Collectors.toSet()); + } + + private void metricsLine(String name, Callable callable) { + this.metrics.addCustomChart(new Metrics.SingleLineChart(name, callable)); + } + + private void metricsDrillPie(String name, Callable>> callable) { + this.metrics.addCustomChart(new Metrics.DrilldownPie(name, callable)); + } + + private void metricsSimplePie(String name, Callable callable) { + this.metrics.addCustomChart(new Metrics.SimplePie(name, callable)); + } + + private Map> metricsPluginInfo(Plugin plugin) { + return this.metricsInfo(plugin, () -> plugin.getDescription().getVersion()); + } + + private Map> metricsInfo(Object plugin, Supplier versionGetter) { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + entry.put(plugin == null ? "nope" : versionGetter.get(), 1); + map.put(plugin == null ? "absent" : "present", entry); + return map; + } + + public void setWorldGuard(IWorldguard wg) { + this.worldguard = wg; + } + + public void loadLang() { + File lang = new File(getDataFolder(), "lang.yml"); + OutputStream out = null; + InputStream defLangStream = this.getResource("lang.yml"); + if (!lang.exists()) { + try { + getDataFolder().mkdir(); + lang.createNewFile(); + if (defLangStream != null) { + out = new FileOutputStream(lang); + int read; + byte[] bytes = new byte[1024]; + + while ((read = defLangStream.read(bytes)) != -1) { + out.write(bytes, 0, read); + } + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new BufferedReader(new InputStreamReader(defLangStream))); + TL.setFile(defConfig); + } + } catch (IOException e) { + getLogger().log(Level.SEVERE, "[Factions] Couldn't create language file.", e); + getLogger().severe("[Factions] This is a fatal error. Now disabling"); + this.setEnabled(false); // Without it loaded, we can't send them messages + } finally { + if (defLangStream != null) { + try { + defLangStream.close(); + } catch (IOException e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to close resource", e); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to close output", e); + } + } + } + } + + YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); + for (TL item : TL.values()) { + if (conf.getString(item.getPath()) == null) { + conf.set(item.getPath(), item.getDefault()); + } + } + + // Remove this here because I'm sick of dealing with bug reports due to bad decisions on my part. + if (conf.getString(TL.COMMAND_SHOW_POWER.getPath(), "").contains("%5$s")) { + conf.set(TL.COMMAND_SHOW_POWER.getPath(), TL.COMMAND_SHOW_POWER.getDefault()); + log(Level.INFO, "Removed errant format specifier from f show power."); + } + + TL.setFile(conf); + try { + conf.save(lang); + } catch (IOException e) { + getLogger().log(Level.WARNING, "Factions: Report this stack trace to drtshock."); + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to save lang.yml", e); + } + } + + private int getBuildNumber(String version) { + Matcher factionsVersionMatcher = factionsVersionPattern.matcher(version); + if (factionsVersionMatcher.find()) { + try { + return Integer.parseInt(factionsVersionMatcher.group(1)); + } catch (NumberFormatException ignored) { // HOW + } + } + return -1; + } + + public UUID getServerUUID() { + return this.serverUUID; + } + + public String getStartupLog() { + return this.startupLog; + } + + public String getStartupExceptionLog() { + return this.startupExceptionLog; + } + + public void updatesOnJoin(Player player) { + /*if (this.updateMessage != null && player.hasPermission(com.massivecraft.factions.struct.Permission.UPDATES.toString())) { + player.sendMessage(this.updateMessage); + player.sendMessage(ChatColor.GREEN + "Get it at " + ChatColor.DARK_AQUA + "https://www.spigotmc.org/resources/factionsuuid.1035/"); + }*/ + } + + public PermUtil getPermUtil() { + return permUtil; + } + + public Gson getGson() { + return gson; + } + + public SeeChunkUtil getSeeChunkUtil() { + return seeChunkUtil; + } + + public ParticleProvider getParticleProvider() { + return particleProvider; + } + + // -------------------------------------------- // + // LANG AND TAGS + // -------------------------------------------- // + + // These are not supposed to be used directly. + // They are loaded and used through the TextUtil instance for the plugin. + private final Map rawTags = new LinkedHashMap<>(); + + private void addRawTags() { + this.rawTags.put("l", ""); // logo + this.rawTags.put("a", ""); // art + this.rawTags.put("n", ""); // notice + this.rawTags.put("i", ""); // info + this.rawTags.put("g", ""); // good + this.rawTags.put("b", ""); // bad + this.rawTags.put("h", ""); // highligh + this.rawTags.put("c", ""); // command + this.rawTags.put("p", ""); // parameter + this.rawTags.put("y", ""); // misc + } + + + + private void initTXT() { + this.addRawTags(); + + Type type = new TypeToken>() { + }.getType(); + + Map tagsFromFile = this.persist.load(type, "tags"); + if (tagsFromFile != null) { + this.rawTags.putAll(tagsFromFile); + } + this.persist.save(this.rawTags, "tags"); + + for (Map.Entry rawTag : this.rawTags.entrySet()) { + this.txt.tags.put(rawTag.getKey(), TextUtil.parseColor(rawTag.getValue())); + } + } + + public Map getStuckMap() { + return this.stuckMap; + } + + public Map getTimers() { + return this.timers; + } + + // -------------------------------------------- // + // LOGGING + // -------------------------------------------- // + public void log(String msg) { + log(Level.INFO, msg); + } + + public void log(String str, Object... args) { + log(Level.INFO, this.txt.parse(str, args)); + } + + public void log(Level level, String str, Object... args) { + log(level, this.txt.parse(str, args)); + } + + public void log(Level level, String msg) { + this.getLogger().log(level, msg); + } + + public boolean getLocked() { + return this.locked; + } + + public void setLocked(boolean val) { + this.locked = val; + this.setAutoSave(val); + } + + public boolean getAutoSave() { + return this.autoSave; + } + + public void setAutoSave(boolean val) { + this.autoSave = val; + } + + public ConfigManager getConfigManager() { + return this.configManager; + } + + public MainConfig conf() { + return this.configManager.getMainConfig(); + } + + public LandRaidControl getLandRaidControl() { + return this.landRaidControl; + } + + public IWorldguard getWorldguard() { + return this.worldguard; + } + + public void setupPlaceholderAPI() { + this.clipPlaceholderAPIManager = new ClipPlaceholderAPIManager(); + if (this.clipPlaceholderAPIManager.register()) { + getLogger().info("Successfully registered placeholders with PlaceholderAPI."); + } + } + + public void setupOtherPlaceholderAPI() { + this.mvdwPlaceholderAPIManager = true; + getLogger().info("Found MVdWPlaceholderAPI."); + } + + public boolean isClipPlaceholderAPIHooked() { + return this.clipPlaceholderAPIManager != null; + } + + public boolean isMVdWPlaceholderAPIHooked() { + return this.mvdwPlaceholderAPIManager; + } + + private boolean setupPermissions() { + try { + RegisteredServiceProvider rsp = getServer().getServicesManager().getRegistration(Permission.class); + if (rsp != null) { + perms = rsp.getProvider(); + } + } catch (NoClassDefFoundError ex) { + return false; + } + return perms != null; + } + + private GsonBuilder getGsonBuilder() { + Type mapFLocToStringSetType = new TypeToken>>() { + }.getType(); + + Type accessType = new TypeToken>>() { + }.getType(); + + GsonBuilder builder = new GsonBuilder(); + + if (!this.conf().data().json().useEfficientStorage()) { + builder.setPrettyPrinting(); + } + + return builder + .disableHtmlEscaping() + .enableComplexMapKeySerialization() + .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE) + .registerTypeAdapter(accessType, new PermissionsMapTypeAdapter()) + .registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()) + .registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()) + .registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY); + } + + public static String version(){ + return Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + } + + @Override + public void onDisable() { + if (autoLeaveTask != null) { + this.getServer().getScheduler().cancelTask(autoLeaveTask); + autoLeaveTask = null; + } + + if (saveTask != null) { + this.getServer().getScheduler().cancelTask(saveTask); + saveTask = null; + } + // only save data if plugin actually loaded successfully + if (loadSuccessful) { + Factions.getInstance().forceSave(); + FPlayers.getInstance().forceSave(); + Board.getInstance().forceSave(); + } + if (this.luckPermsSetup) { + LuckPerms.shutdown(this); + } + ContextManager.shutdown(); + log("Disabled"); + } + + public void startAutoLeaveTask(boolean restartIfRunning) { + if (autoLeaveTask != null) { + if (!restartIfRunning) { + return; + } + this.getServer().getScheduler().cancelTask(autoLeaveTask); + } + + if (this.conf().factions().other().getAutoLeaveRoutineRunsEveryXMinutes() > 0.0) { + long ticks = (long) (20 * 60 * this.conf().factions().other().getAutoLeaveRoutineRunsEveryXMinutes()); + autoLeaveTask = getServer().getScheduler().scheduleSyncRepeatingTask(this, new AutoLeaveTask(), ticks, ticks); + } + } + + public boolean logPlayerCommands() { + return this.conf().logging().isPlayerCommands(); + } + + // -------------------------------------------- // + // Functions for other plugins to hook into + // -------------------------------------------- // + + // This value will be updated whenever new hooks are added + @Override + public int getAPIVersion() { + // Updated from 4 to 5 for version 0.5.0 + return 4; + } + + // If another plugin is handling insertion of chat tags, this should be used to notify Factions + @Override + public void setHandlingChat(Plugin plugin, boolean handling) { + if (plugin == null) { + throw new IllegalArgumentException("Null plugin!"); + } + if (plugin == this) { + throw new IllegalArgumentException("Nice try, but this plugin isn't going to register itself!"); + } + if (handling) { + this.pluginsHandlingChat.add(plugin.getName()); + } else { + this.pluginsHandlingChat.remove(plugin.getName()); + } + } + + @Override + public boolean isAnotherPluginHandlingChat() { + return this.conf().factions().chat().isTagHandledByAnotherPlugin() || !this.pluginsHandlingChat.isEmpty(); + } + + // Simply put, should this chat event be left for Factions to handle? For now, that means players with Faction Chat + // enabled or use of the Factions f command without a slash; combination of isPlayerFactionChatting() and isFactionsCommand() + + @Override + public boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event) { + return event != null && (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage())); + } + + // Does player have Faction Chat enabled? If so, chat plugins should preferably not do channels, + // local chat, or anything else which targets individual recipients, so Faction Chat can be done + @Override + public boolean isPlayerFactionChatting(Player player) { + if (player == null) { + return false; + } + FPlayer me = FPlayers.getInstance().getByPlayer(player); + + return me != null && me.getChatMode().isAtLeast(ChatMode.ALLIANCE); + } + + // Is this chat message actually a Factions command, and thus should be left alone by other plugins? + + // TODO: GET THIS BACK AND WORKING + + public boolean isFactionsCommand(String check) { + return !(check == null || check.isEmpty()); //&& this.handleCommand(null, check, true); + } + + // Get a player's faction tag (faction name), mainly for usage by chat plugins for local/channel chat + @Override + public String getPlayerFactionTag(Player player) { + return getPlayerFactionTagRelation(player, null); + } + + // Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag + @Override + public String getPlayerFactionTagRelation(Player speaker, Player listener) { + String tag = "~"; + + if (speaker == null) { + return tag; + } + + FPlayer me = FPlayers.getInstance().getByPlayer(speaker); + if (me == null) { + return tag; + } + + // if me.astropvp.outpost.listener isn't set, or config option is disabled, give back uncolored tag + if (listener == null || !this.conf().factions().chat().isTagRelationColored()) { + tag = me.getChatTag().trim(); + } else { + FPlayer you = FPlayers.getInstance().getByPlayer(listener); + if (you == null) { + tag = me.getChatTag().trim(); + } else // everything checks out, give the colored tag + { + tag = me.getChatTag(you).trim(); + } + } + if (tag.isEmpty()) { + tag = "~"; + } + + return tag; + } + + // Get a player's title within their faction, mainly for usage by chat plugins for local/channel chat + @Override + public String getPlayerTitle(Player player) { + if (player == null) { + return ""; + } + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me == null) { + return ""; + } + + return me.getTitle().trim(); + } + + // Get a list of all faction tags (names) + @Override + public Set getFactionTags() { + return Factions.getInstance().getFactionTags(); + } + + // Get a list of all players in the specified faction + @Override + public Set getPlayersInFaction(String factionTag) { + Set players = new HashSet<>(); + Faction faction = Factions.getInstance().getByTag(factionTag); + if (faction != null) { + for (FPlayer fplayer : faction.getFPlayers()) { + players.add(fplayer.getName()); + } + } + return players; + } + + // Get a list of all online players in the specified faction + @Override + public Set getOnlinePlayersInFaction(String factionTag) { + Set players = new HashSet<>(); + Faction faction = Factions.getInstance().getByTag(factionTag); + if (faction != null) { + for (FPlayer fplayer : faction.getFPlayersWhereOnline(true)) { + players.add(fplayer.getName()); + } + } + return players; + } + + public String getPrimaryGroup(OfflinePlayer player) { + return perms == null || !perms.hasGroupSupport() ? " " : perms.getPrimaryGroup(Bukkit.getWorlds().get(0).toString(), player); + } + + public void debug(Level level, String s) { + if (conf().getaVeryFriendlyFactionsConfig().isDebug()) { + getLogger().log(level, s); + } + } + + public void debug(String s) { + debug(Level.INFO, s); + } + + public void luckpermsEnabled() { + this.luckPermsSetup = true; + } + + public CompletableFuture teleport(Player player, Location location) { + if (this.conf().paper().isAsyncTeleport()) { + return PaperLib.teleportAsync(player, location, PlayerTeleportEvent.TeleportCause.PLUGIN); + } else { + return CompletableFuture.completedFuture(player.teleport(location, PlayerTeleportEvent.TeleportCause.PLUGIN)); + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java new file mode 100644 index 0000000..5b369c1 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java @@ -0,0 +1,59 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerTeleportEvent; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; +import org.bukkit.Location; + +public class CmdAHome extends FCommand { + + public CmdAHome() { + super(); + this.aliases.add("ahome"); + + this.requiredArgs.add("player"); + + this.requirements = new CommandRequirements.Builder(Permission.AHOME).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0); + if (target == null) { + context.msg(TL.GENERIC_NOPLAYERMATCH, context.argAsString(0)); + return; + } + + if (target.isOnline()) { + Faction faction = target.getFaction(); + if (faction.hasHome()) { + Location destination = faction.getHome(); + FPlayerTeleportEvent tpEvent = new FPlayerTeleportEvent(target, destination, FPlayerTeleportEvent.PlayerTeleportReason.AHOME); + Bukkit.getServer().getPluginManager().callEvent(tpEvent); + if (tpEvent.isCancelled()) { + return; + } + FactionsPlugin.getInstance().teleport(target.getPlayer(), destination).thenAccept(success -> { + if (success) { + context.msg(TL.COMMAND_AHOME_SUCCESS, target.getName()); + target.msg(TL.COMMAND_AHOME_TARGET); + } + }); + + } else { + context.msg(TL.COMMAND_AHOME_NOHOME, target.getName()); + } + } else { + context.msg(TL.COMMAND_AHOME_OFFLINE, target.getName()); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_AHOME_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java new file mode 100644 index 0000000..3e1c21c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java @@ -0,0 +1,92 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.event.FPlayerJoinEvent; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +public class CmdAdmin extends FCommand { + + public CmdAdmin() { + super(); + this.aliases.add("admin"); + this.aliases.add("setadmin"); + this.aliases.add("leader"); + this.aliases.add("setleader"); + + this.requiredArgs.add("player"); + + this.requirements = new CommandRequirements.Builder(Permission.ADMIN).build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer fyou = context.argAsBestFPlayerMatch(0); + if (fyou == null) { + return; + } + + if(fyou.getRole() == Role.ALT){ + context.msg(TL.COMMAND_PROMOTE_ISALT); + return; + } + + boolean permAny = Permission.ADMIN_ANY.has(context.sender, false); + Faction targetFaction = fyou.getFaction(); + + if (targetFaction != context.faction && !permAny) { + context.msg(TL.COMMAND_ADMIN_NOTMEMBER, fyou.describeTo(context.fPlayer, true)); + return; + } + + if (context.fPlayer != null && context.fPlayer.getRole() != Role.ADMIN && !permAny) { + context.msg(TL.COMMAND_ADMIN_NOTADMIN); + return; + } + + if (fyou == context.fPlayer && !permAny) { + context.msg(TL.COMMAND_ADMIN_TARGETSELF); + return; + } + + // only perform a FPlayerJoinEvent when newLeader isn't actually in the faction + if (fyou.getFaction() != targetFaction) { + FPlayerJoinEvent event = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(context.player), targetFaction, FPlayerJoinEvent.PlayerJoinReason.LEADER); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + } + + FPlayer admin = targetFaction.getFPlayerAdmin(); + + // if target player is currently admin, demote and replace him + if (fyou == admin) { + targetFaction.promoteNewLeader(); + context.msg(TL.COMMAND_ADMIN_DEMOTES, fyou.describeTo(context.fPlayer, true)); + fyou.msg(TL.COMMAND_ADMIN_DEMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fyou, true)); + return; + } + + // promote target player, and demote existing admin if one exists + if (admin != null) { + admin.setRole(Role.COLEADER); + } + fyou.setRole(Role.ADMIN); + context.msg(TL.COMMAND_ADMIN_PROMOTES, fyou.describeTo(context.fPlayer, true)); + + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer)); + } + } + + public TL getUsageTranslation() { + return TL.COMMAND_ADMIN_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java new file mode 100644 index 0000000..7cbc460 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java @@ -0,0 +1,45 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class CmdAnnounce extends FCommand { + + public CmdAnnounce() { + super(); + this.aliases.add("ann"); + this.aliases.add("announce"); + + this.requiredArgs.add("message"); + + this.requirements = new CommandRequirements.Builder(Permission.ANNOUNCE).memberOnly().withRole(Role.MODERATOR) + .noErrorOnManyArgs() + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + String prefix = ChatColor.GREEN + context.faction.getTag() + ChatColor.YELLOW + " [" + ChatColor.GRAY + context.player.getName() + ChatColor.YELLOW + "] " + ChatColor.RESET; + String message = StringUtils.join(context.args, " "); + + for (Player player : context.faction.getOnlinePlayers()) { + player.sendMessage(prefix + message); + } + + // Add for offline players. + for (FPlayer fp : context.faction.getFPlayersWhereOnline(false)) { + context.faction.addAnnouncement(fp, prefix + message); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ANNOUNCE_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java new file mode 100644 index 0000000..d2897ef --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java @@ -0,0 +1,43 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.util.TL; + +import java.util.ArrayList; + +public class CmdAutoHelp extends FCommand { + + public CmdAutoHelp() { + this.aliases.add("?"); + this.aliases.add("h"); + this.aliases.add("help"); + + this.setHelpShort(""); + + this.optionalArgs.put("page", "1"); + } + + @Override + public void perform(CommandContext context) { + if (context.commandChain.size() == 0) { + return; + } + FCommand pcmd = context.commandChain.get(context.commandChain.size() - 1); + + ArrayList lines = new ArrayList<>(pcmd.helpLong); + + for (FCommand scmd : pcmd.subCommands) { + if (scmd.visibility == CommandVisibility.VISIBLE) { + lines.add(scmd.getUsageTemplate(context, true)); + } + // TODO deal with other visibilities + } + + context.sendMessage(FactionsPlugin.getInstance().txt().getPage(lines, context.argAsInt(0, 1), TL.COMMAND_AUTOHELP_HELPFOR.toString() + pcmd.aliases.get(0) + "\"")); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_HELP_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBan.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBan.java new file mode 100644 index 0000000..62558dd --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBan.java @@ -0,0 +1,84 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerLeaveEvent; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.BanInfo; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +import java.util.logging.Level; + +public class CmdBan extends FCommand { + + public CmdBan() { + super(); + this.aliases.add("ban"); + + this.requiredArgs.add("target"); + + this.requirements = new CommandRequirements.Builder(Permission.BAN) + .memberOnly() + .withAction(PermissibleAction.BAN) + .build(); + } + + @Override + public void perform(CommandContext context) { + // Good on permission checks. Now lets just ban the player. + FPlayer target = context.argAsFPlayer(0); + if (target == null) { + return; // the above method sends a message if fails to find someone. + } + + if (context.fPlayer == target) { + // You may not ban yourself + context.msg(TL.COMMAND_BAN_SELF); + return; + } else if (target.getFaction() == context.faction && target.getRole().value >= context.fPlayer.getRole().value) { + // You may not ban someone that has same or higher faction rank + context.msg(TL.COMMAND_BAN_INSUFFICIENTRANK, target.getName()); + return; + } + + // Check if the user is already banned + for (BanInfo banInfo : context.faction.getBannedPlayers()) { + if (banInfo.getBanned().equals(target.getId())) { + context.msg(TL.COMMAND_BAN_ALREADYBANNED, target.getName()); + return; + } + } + + // Ban the user. + context.faction.ban(target, context.fPlayer); + context.faction.deinvite(target); // can't hurt + + // If in same Faction, lets make sure to kick them and throw an event. + if (target.getFaction() == context.faction) { + + FPlayerLeaveEvent event = new FPlayerLeaveEvent(target, context.faction, FPlayerLeaveEvent.PlayerLeaveReason.BANNED); + Bukkit.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + // if someone cancels a ban, we'll get people complaining here. So lets log it. + FactionsPlugin.getInstance().log(Level.WARNING, "Attempted to ban {0} but someone cancelled the kick event. This isn't good.", target.getName()); + return; + } + + // Didn't get cancelled so remove them and reset their invite. + context.faction.removeFPlayer(target); + target.resetFactionData(); + } + + // Lets inform the people! + target.msg(TL.COMMAND_BAN_TARGET, context.faction.getTag(target.getFaction())); + context.faction.msg(TL.COMMAND_BAN_BANNED, context.fPlayer.getName(), target.getName()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BAN_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java new file mode 100644 index 0000000..6f0886c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java @@ -0,0 +1,67 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.struct.BanInfo; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +import java.util.ArrayList; +import java.util.List; + +public class CmdBanlist extends FCommand { + + public CmdBanlist() { + super(); + this.aliases.add("banlist"); + this.aliases.add("bans"); + this.aliases.add("banl"); + + this.optionalArgs.put("faction", "faction"); + + this.requirements = new CommandRequirements.Builder(Permission.BAN) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + Faction target = context.faction; + if (!context.args.isEmpty()) { + target = context.argAsFaction(0); + } + + if (target == null) { + context.msg(TL.COMMAND_BANLIST_INVALID.format(context.argAsString(0))); + return; + } + + if (!target.isNormal()) { + context.msg(TL.COMMAND_BANLIST_NOFACTION); + return; + } + + List lines = new ArrayList<>(); + lines.add(TL.COMMAND_BANLIST_HEADER.format(target.getBannedPlayers().size(), target.getTag(context.faction))); + int i = 1; + + for (BanInfo info : target.getBannedPlayers()) { + FPlayer banned = FPlayers.getInstance().getById(info.getBanned()); + FPlayer banner = FPlayers.getInstance().getById(info.getBanner()); + String timestamp = TL.sdf.format(info.getTime()); + + lines.add(TL.COMMAND_BANLIST_ENTRY.format(i, banned.getName(), banner.getName(), timestamp)); + i++; + } + + for (String s : lines) { + context.fPlayer.sendMessage(s); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BANLIST_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java new file mode 100644 index 0000000..70e7f59 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java @@ -0,0 +1,48 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdBoom extends FCommand { + + public CmdBoom() { + super(); + this.aliases.add("noboom"); + this.aliases.add("explosions"); + this.aliases.add("toggleexplosions"); + + this.optionalArgs.put("on/off", "flip"); + + this.requirements = new CommandRequirements.Builder(Permission.NO_BOOM) + .memberOnly() + .withRole(Role.MODERATOR) + .build(); + } + + @Override + public void perform(CommandContext context) { + if (!context.faction.isPeaceful()) { + context.msg(TL.COMMAND_BOOM_PEACEFULONLY); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostNoBoom(), TL.COMMAND_BOOM_TOTOGGLE, TL.COMMAND_BOOM_FORTOGGLE)) { + return; + } + + context.faction.setPeacefulExplosionsEnabled(context.argAsBool(0, !context.faction.getPeacefulExplosionsEnabled())); + + String enabled = context.faction.noExplosionsInTerritory() ? TL.GENERIC_DISABLED.toString() : TL.GENERIC_ENABLED.toString(); + + // Inform + context.faction.msg(TL.COMMAND_BOOM_ENABLED, context.fPlayer.describeTo(context.faction), enabled); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BOOM_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java new file mode 100644 index 0000000..4b7412c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java @@ -0,0 +1,39 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdBypass extends FCommand { + + public CmdBypass() { + super(); + this.aliases.add("bypass"); + + this.optionalArgs.put("on/off", "flip"); + + this.requirements = new CommandRequirements.Builder(Permission.BYPASS) + .playerOnly() + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + context.fPlayer.setIsAdminBypassing(context.argAsBool(0, !context.fPlayer.isAdminBypassing())); + + // TODO: Move this to a transient field in the model?? + if (context.fPlayer.isAdminBypassing()) { + context.fPlayer.msg(TL.COMMAND_BYPASS_ENABLE.toString()); + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_BYPASS_ENABLELOG.toString()); + } else { + context.fPlayer.msg(TL.COMMAND_BYPASS_DISABLE.toString()); + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_BYPASS_DISABLELOG.toString()); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BYPASS_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdChat.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdChat.java new file mode 100644 index 0000000..8caa69d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdChat.java @@ -0,0 +1,83 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.ChatMode; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdChat extends FCommand { + + public CmdChat() { + super(); + this.aliases.add("c"); + this.aliases.add("chat"); + + this.optionalArgs.put("mode", "next"); + + this.requirements = new CommandRequirements.Builder(Permission.CHAT) + .memberOnly() + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().conf().factions().chat().isFactionOnlyChat()) { + context.msg(TL.COMMAND_CHAT_DISABLED.toString()); + return; + } + + String modeString = context.argAsString(0); + ChatMode modeTarget = context.fPlayer.getChatMode().getNext(); + + // If player is cycling through chat modes + // and he is not atleast a moderator get next one + if (modeString == null && modeTarget == ChatMode.MOD) { + if (!context.fPlayer.getRole().isAtLeast(Role.MODERATOR)) { + modeTarget = modeTarget.getNext(); + } + } + + if (modeString != null) { + modeString = modeString.toLowerCase(); + if (modeString.startsWith("m")) { + modeTarget = ChatMode.MOD; + if (!context.fPlayer.getRole().isAtLeast(Role.MODERATOR)) { + context.msg(TL.COMMAND_CHAT_INSUFFICIENTRANK); + return; + } + } else if (modeString.startsWith("p")) { + modeTarget = ChatMode.PUBLIC; + } else if (modeString.startsWith("a")) { + modeTarget = ChatMode.ALLIANCE; + } else if (modeString.startsWith("f")) { + modeTarget = ChatMode.FACTION; + } else if (modeString.startsWith("t")) { + modeTarget = ChatMode.TRUCE; + } else { + context.msg(TL.COMMAND_CHAT_INVALIDMODE); + return; + } + } + + context.fPlayer.setChatMode(modeTarget); + + if (context.fPlayer.getChatMode() == ChatMode.MOD) { + context.msg(TL.COMMAND_CHAT_MODE_MOD); + } else if (context.fPlayer.getChatMode() == ChatMode.PUBLIC) { + context.msg(TL.COMMAND_CHAT_MODE_PUBLIC); + } else if (context.fPlayer.getChatMode() == ChatMode.ALLIANCE) { + context.msg(TL.COMMAND_CHAT_MODE_ALLIANCE); + } else if (context.fPlayer.getChatMode() == ChatMode.TRUCE) { + context.msg(TL.COMMAND_CHAT_MODE_TRUCE); + } else { + context.msg(TL.COMMAND_CHAT_MODE_FACTION); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CHAT_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java new file mode 100644 index 0000000..0b256fc --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java @@ -0,0 +1,38 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdChatSpy extends FCommand { + + public CmdChatSpy() { + super(); + this.aliases.add("chatspy"); + + this.optionalArgs.put("on/off", "flip"); + + this.requirements = new CommandRequirements.Builder(Permission.CHATSPY) + .playerOnly() + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + context.fPlayer.setSpyingChat(context.argAsBool(0, !context.fPlayer.isSpyingChat())); + + if (context.fPlayer.isSpyingChat()) { + context.fPlayer.msg(TL.COMMAND_CHATSPY_ENABLE); + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_CHATSPY_ENABLELOG.toString()); + } else { + context.fPlayer.msg(TL.COMMAND_CHATSPY_DISABLE); + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_CHATSPY_DISABLELOG.toString()); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CHATSPY_DESCRIPTION; + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java new file mode 100644 index 0000000..4795aaa --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java @@ -0,0 +1,99 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import mkremins.fanciful.FancyMessage; +import org.bukkit.ChatColor; + +public class CmdColeader extends FCommand { + + public CmdColeader() { + super(); + this.aliases.add("coleader"); + this.aliases.add("setcoleader"); + this.aliases.add("cl"); + this.aliases.add("setcl"); + + this.requiredArgs.add("player"); + + this.requirements = new CommandRequirements.Builder(Permission.COLEADER) + .memberOnly() + .withRole(Role.ADMIN) + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0); + if (target == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_COLEADER_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : context.faction.getFPlayersWhereRole(Role.MODERATOR)) { + String s = player.getName(); + + msg.then(s + " ").color(ChatColor.WHITE) + .tooltip(TL.COMMAND_COLEADER_CLICKTOPROMOTE.toString() + s) + .command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " coleader " + s); + } + + context.sendFancyMessage(msg); + return; + } + + if(target.getRole() == Role.ALT){ + context.msg(TL.COMMAND_PROMOTE_ISALT); + return; + } + + boolean permAny = Permission.COLEADER_ANY.has(context.sender, false); + Faction targetFaction = target.getFaction(); + + if (targetFaction != context.faction && !permAny) { + context.msg(TL.COMMAND_COLEADER_NOTMEMBER, target.describeTo(context.fPlayer, true)); + return; + } + + if (context.fPlayer != null && context.fPlayer.getRole() != Role.ADMIN && !permAny) { + context.msg(TL.COMMAND_COLEADER_NOTADMIN); + return; + } + + if (target == context.fPlayer && !permAny) { + context.msg(TL.COMMAND_COLEADER_SELF); + return; + } + + if (target.getRole() == Role.ADMIN) { + context.msg(TL.COMMAND_COLEADER_TARGETISADMIN); + return; + } + + if (target.getRole() == Role.COLEADER) { + // Revoke + target.setRole(Role.MODERATOR); + targetFaction.msg(TL.COMMAND_COLEADER_REVOKED, target.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_COLEADER_REVOKES, target.describeTo(context.fPlayer, true)); + return; + } + + // Check to see if we should allow multiple coleaders or not. + if (!FactionsPlugin.getInstance().conf().factions().other().isAllowMultipleColeaders() && !targetFaction.getFPlayersWhereRole(Role.COLEADER).isEmpty()) { + context.msg(TL.COMMAND_COLEADER_ALREADY_COLEADER); + return; + } + + // Give + target.setRole(Role.COLEADER); + targetFaction.msg(TL.COMMAND_COLEADER_PROMOTED, target.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_COLEADER_PROMOTES, target.describeTo(context.fPlayer, true)); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_COLEADER_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java new file mode 100644 index 0000000..7b977c3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java @@ -0,0 +1,34 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Location; + +public class CmdCoords extends FCommand { + + public CmdCoords() { + super(); + this.aliases.add("coords"); + this.aliases.add("coord"); + + this.requirements = new CommandRequirements.Builder(Permission.COORDS) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + Location location = context.player.getLocation(); + String message = TL.COMMAND_COORDS_MESSAGE.format(context.player.getDisplayName(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getWorld().getName()); + for (FPlayer fPlayer : context.faction.getFPlayers()) { + fPlayer.sendMessage(message); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_COORDS_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java new file mode 100644 index 0000000..65c11c0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java @@ -0,0 +1,109 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerJoinEvent; +import com.massivecraft.factions.event.FactionAttemptCreateEvent; +import com.massivecraft.factions.event.FactionCreateEvent; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.MiscUtil; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +import java.util.ArrayList; + + +public class CmdCreate extends FCommand { + + public CmdCreate() { + super(); + this.aliases.add("create"); + + this.requiredArgs.add("faction tag"); + + this.requirements = new CommandRequirements.Builder(Permission.CREATE) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + String tag = context.argAsString(0); + + if (context.fPlayer.hasFaction()) { + context.msg(TL.COMMAND_CREATE_MUSTLEAVE); + return; + } + + if (Factions.getInstance().isTagTaken(tag)) { + context.msg(TL.COMMAND_CREATE_INUSE); + return; + } + + ArrayList tagValidationErrors = MiscUtil.validateTag(tag); + if (tagValidationErrors.size() > 0) { + context.sendMessage(tagValidationErrors); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!context.canAffordCommand(FactionsPlugin.getInstance().conf().economy().getCostCreate(), TL.COMMAND_CREATE_TOCREATE.toString())) { + return; + } + + FactionAttemptCreateEvent attemptEvent = new FactionAttemptCreateEvent(context.player, tag); + Bukkit.getServer().getPluginManager().callEvent(attemptEvent); + if (attemptEvent.isCancelled()) { + return; + } + + // then make 'em pay (if applicable) + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostCreate(), TL.COMMAND_CREATE_TOCREATE, TL.COMMAND_CREATE_FORCREATE)) { + return; + } + + Faction faction = Factions.getInstance().createFaction(); + + // TODO: Why would this even happen??? Auto increment clash?? + if (faction == null) { + context.msg(TL.COMMAND_CREATE_ERROR); + return; + } + + // finish setting up the Faction + faction.setTag(tag); + + // trigger the faction join event for the creator + FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(context.player), faction, FPlayerJoinEvent.PlayerJoinReason.CREATE); + Bukkit.getServer().getPluginManager().callEvent(joinEvent); + // join event cannot be cancelled or you'll have an empty faction + + // finish setting up the FPlayer + context.fPlayer.setRole(Role.ADMIN); + context.fPlayer.setFaction(faction); + + // trigger the faction creation event + FactionCreateEvent createEvent = new FactionCreateEvent(context.player, tag, faction); + Bukkit.getServer().getPluginManager().callEvent(createEvent); + + for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { + //follower.msg(TL.COMMAND_CREATE_CREATED, context.fPlayer.describeTo(follower, true), faction.getTag(follower)); + } + + context.msg(TL.COMMAND_CREATE_YOUSHOULD, FCmdRoot.getInstance().cmdDescription.getUsageTemplate(context)); + + if (FactionsPlugin.getInstance().conf().logging().isFactionCreate()) { + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_CREATE_CREATEDLOG + tag); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CREATE_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDTR.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDTR.java new file mode 100644 index 0000000..ad1f4b0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDTR.java @@ -0,0 +1,34 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.cmd.dtr.CmdDTRGet; +import com.massivecraft.factions.cmd.dtr.CmdDTRModify; +import com.massivecraft.factions.cmd.dtr.CmdDTRResetAll; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdDTR extends FCommand { + private final CmdDTRGet cmdDTRGet; + + public CmdDTR() { + super(); + this.aliases.add("dtr"); + this.aliases.add("deathstilraidable"); // YOLO + + this.addSubCommand(this.cmdDTRGet = new CmdDTRGet()); + this.addSubCommand(new CmdDTRModify()); + this.addSubCommand(new CmdDTRResetAll()); + + this.requirements = new CommandRequirements.Builder(Permission.DTR).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + this.cmdDTRGet.execute(context); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DTR_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDebug.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDebug.java new file mode 100644 index 0000000..d112bfd --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDebug.java @@ -0,0 +1,139 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.apache.commons.lang.exception.ExceptionUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.kitteh.pastegg.PasteBuilder; +import org.kitteh.pastegg.PasteContent; +import org.kitteh.pastegg.PasteFile; +import org.kitteh.pastegg.Visibility; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.logging.Level; + +public class CmdDebug extends FCommand { + public CmdDebug() { + super(); + this.aliases.add("debug"); + this.aliases.add("helpme"); + this.optionalArgs.put("mini/full", "full"); + + this.requirements = new CommandRequirements.Builder(Permission.DEBUG).build(); + } + + @Override + public void perform(CommandContext context) { + StringBuilder mainInfo = new StringBuilder(); + mainInfo.append(Bukkit.getName()).append(" version: ").append(Bukkit.getServer().getVersion()).append('\n'); + mainInfo.append("Server ID: ").append(FactionsPlugin.getInstance().getServerUUID()).append('\n'); + mainInfo.append("Plugin version: ").append(FactionsPlugin.getInstance().getDescription().getVersion()).append('\n'); + mainInfo.append("Java version: ").append(System.getProperty("java.version")).append('\n'); + if (!context.args.isEmpty() && context.argAsString(0).equalsIgnoreCase("mini")) { + for (String string : mainInfo.toString().split("\n")) { + context.msg(string); + } + return; + } + mainInfo.append('\n'); + mainInfo.append("Plugins:\n"); + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + mainInfo.append(' ').append(plugin.getName()).append(" - ").append(plugin.getDescription().getVersion()).append('\n'); + mainInfo.append(" ").append(plugin.getDescription().getAuthors()).append('\n'); + } + + StringBuilder permInfo = new StringBuilder(); + for (Player player : Bukkit.getOnlinePlayers()) { + permInfo.append(player.getName()).append('\n'); + for (Permission permission : Permission.values()) { + permInfo.append(' '); + if (player.hasPermission(permission.toString())) { + permInfo.append('\u2713'); + } else { + permInfo.append('\u2715'); + } + permInfo.append(permission.toString()).append('\n'); + } + permInfo.append('\n'); + } + + new BukkitRunnable() { + private final PasteBuilder builder = new PasteBuilder().name("FactionsUUID Debug") + .visibility(Visibility.UNLISTED) + .expires(ZonedDateTime.now(ZoneOffset.UTC).plusDays(3)); + private int i = 0; + + private void add(String name, String content) { + builder.addFile(new PasteFile(i++ + name, new PasteContent(PasteContent.ContentType.TEXT, content))); + } + + private String getFile(Path file) { + try { + return new String(Files.readAllBytes(file), StandardCharsets.UTF_8); + } catch (IOException e) { + return ExceptionUtils.getFullStackTrace(e); + } + } + + @Override + public void run() { + try { + Path dataPath = FactionsPlugin.getInstance().getDataFolder().toPath(); + add("info.txt", mainInfo.toString()); + add("startup.txt", plugin.getStartupLog()); + if (!plugin.getStartupExceptionLog().isEmpty()) { + add("startupexceptions.txt", plugin.getStartupExceptionLog()); + } + add("server.properties", getFile(Paths.get("server.properties")).replaceAll("(?:(?:server-ip=)|(?:server-port=)|(?:rcon\\.port=)|(?:rcon\\.password=)|(?:query.port=))[^\n]*[\r\n]*", "")); + add("main.conf", getFile(dataPath.resolve("config/main.conf"))); + add("spigot.yml", getFile(Paths.get("spigot.yml"))); + if (permInfo.length() > 0) { + add("perms.txt", permInfo.toString()); + } + PasteBuilder.PasteResult result = builder.build(); + new BukkitRunnable() { + @Override + public void run() { + if (result.getPaste().isPresent()) { + String delKey = result.getPaste().get().getDeletionKey().orElse("No deletion key"); + context.msg(TL.COMMAND_DEBUG_COMPLETE, "https://paste.gg/anonymous/" + result.getPaste().get().getId()); + context.msg(TL.COMMAND_DEBUG_DELETIONKEY, delKey); + if (context.sender instanceof Player) { + FactionsPlugin.getInstance().getLogger().info(TL.COMMAND_DEBUG_COMPLETE.format("https://paste.gg/anonymous/" + result.getPaste().get().getId())); + FactionsPlugin.getInstance().getLogger().info(TL.COMMAND_DEBUG_DELETIONKEY.format(delKey)); + } + } else { + context.msg(TL.COMMAND_DEBUG_FAIL); + FactionsPlugin.getInstance().getLogger().warning("Received: " + result.getMessage()); + } + } + }.runTask(FactionsPlugin.getInstance()); + } catch (Exception e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to execute debug command", e); + new BukkitRunnable() { + @Override + public void run() { + context.msg(TL.COMMAND_DEBUG_FAIL); + } + }.runTask(FactionsPlugin.getInstance()); + } + } + }.runTaskAsynchronously(FactionsPlugin.getInstance()); + context.msg(TL.COMMAND_DEBUG_RUNNING); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DEBUG_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java new file mode 100644 index 0000000..cb80732 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java @@ -0,0 +1,60 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import mkremins.fanciful.FancyMessage; +import org.bukkit.ChatColor; + +public class CmdDeinvite extends FCommand { + + public CmdDeinvite() { + super(); + this.aliases.add("deinvite"); + this.aliases.add("deinv"); + + this.optionalArgs.put("player", "player"); + //this.optionalArgs.put("", ""); + + this.requirements = new CommandRequirements.Builder(Permission.DEINVITE) + .memberOnly() + .withAction(PermissibleAction.INVITE) + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer you = context.argAsBestFPlayerMatch(0); + if (you == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD); + for (String id : context.faction.getInvites()) { + FPlayer fp = FPlayers.getInstance().getById(id); + String name = fp != null ? fp.getName() : id; + msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_DEINVITE_CLICKTODEINVITE.format(name)).command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " deinvite " + name); + } + context.sendFancyMessage(msg); + return; + } + + if (you.getFaction() == context.faction) { + context.msg(TL.COMMAND_DEINVITE_ALREADYMEMBER, you.getName(), context.faction.getTag()); + context.msg(TL.COMMAND_DEINVITE_MIGHTWANT, FCmdRoot.getInstance().cmdKick.getUsageTemplate(context)); + return; + } + + context.faction.deinvite(you); + + you.msg(TL.COMMAND_DEINVITE_REVOKED, context.fPlayer.describeTo(you), context.faction.describeTo(you)); + + context.faction.msg(TL.COMMAND_DEINVITE_REVOKES, context.fPlayer.describeTo(context.faction), you.describeTo(context.faction)); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DEINVITE_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDelWarp.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDelWarp.java new file mode 100644 index 0000000..8358a5f --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDelWarp.java @@ -0,0 +1,47 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdDelWarp extends FCommand { + + public CmdDelWarp() { + super(); + this.aliases.add("delwarp"); + this.aliases.add("dw"); + this.aliases.add("deletewarp"); + + this.requiredArgs.add("warp"); + + this.requirements = new CommandRequirements.Builder(Permission.SETWARP) + .memberOnly() + .withAction(PermissibleAction.SETWARP) + .build(); + } + + @Override + public void perform(CommandContext context) { + String warp = context.argAsString(0); + if (context.faction.isWarp(warp)) { + if (!transact(context.fPlayer, context)) { + return; + } + context.faction.removeWarp(warp); + context.msg(TL.COMMAND_DELFWARP_DELETED, warp); + } else { + context.msg(TL.COMMAND_DELFWARP_INVALID, warp); + } + } + + private boolean transact(FPlayer player, CommandContext context) { + return player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostDelWarp(), TL.COMMAND_DELFWARP_TODELETE.toString(), TL.COMMAND_DELFWARP_FORDELETE.toString()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DELFWARP_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDelhome.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDelhome.java new file mode 100644 index 0000000..bcdeb85 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDelhome.java @@ -0,0 +1,47 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdDelhome extends FCommand { + + public CmdDelhome() { + this.aliases.add("delhome"); + + this.requirements = new CommandRequirements.Builder(Permission.DELHOME) + .memberOnly() + .withAction(PermissibleAction.SETHOME) + .build(); + } + + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().conf().factions().homes().isEnabled()) { + context.msg(TL.COMMAND_SETHOME_DISABLED); + return; + } + + if (!context.faction.hasHome()) { + context.msg(TL.COMMAND_HOME_NOHOME.toString() + (context.fPlayer.getRole().value < Role.MODERATOR.value ? TL.GENERIC_ASKYOURLEADER.toString() : TL.GENERIC_YOUSHOULD.toString())); + context.sendMessage(FCmdRoot.getInstance().cmdSethome.getUsageTemplate(context)); + return; + } + + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostDelhome(), TL.COMMAND_DELHOME_TOSET, TL.COMMAND_DELHOME_FORSET)) { + return; + } + + context.faction.delHome(); + + context.faction.msg(TL.COMMAND_DELHOME_DEL, context.fPlayer.describeTo(context.faction, true)); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DELHOME_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java new file mode 100644 index 0000000..d4da799 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java @@ -0,0 +1,56 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.TextUtil; + +public class CmdDescription extends FCommand { + + public CmdDescription() { + super(); + this.aliases.add("desc"); + this.aliases.add("description"); + + this.requiredArgs.add("desc"); + + this.requirements = new CommandRequirements.Builder(Permission.DESCRIPTION) + .memberOnly() + .withRole(Role.MODERATOR) + .noErrorOnManyArgs() + .build(); + } + + @Override + public void perform(CommandContext context) { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostDesc(), TL.COMMAND_DESCRIPTION_TOCHANGE, TL.COMMAND_DESCRIPTION_FORCHANGE)) { + return; + } + + // since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up + // And replace all the % because it messes with string formatting and this is easy way around that. + context.faction.setDescription(TextUtil.implode(context.args, " ").replaceAll("%", "").replaceAll("(&([a-f0-9klmnor]))", "& $2")); + + if (!FactionsPlugin.getInstance().conf().factions().chat().isBroadcastDescriptionChanges()) { + context.fPlayer.msg(TL.COMMAND_DESCRIPTION_CHANGED, context.faction.describeTo(context.fPlayer)); + context.fPlayer.sendMessage(context.faction.getDescription()); + return; + } + + // Broadcast the description to everyone + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.COMMAND_DESCRIPTION_CHANGES, context.faction.describeTo(fplayer)); + fplayer.sendMessage(context.faction.getDescription()); // players can inject "&" or "`" or "" or whatever in their description; &k is particularly interesting looking + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DESCRIPTION_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java new file mode 100644 index 0000000..340b518 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java @@ -0,0 +1,125 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerLeaveEvent; +import com.massivecraft.factions.event.FactionDisbandEvent; +import com.massivecraft.factions.gui.FDisbandConfirmGUI; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.scoreboards.FTeamWrapper; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +import java.util.concurrent.TimeUnit; + + +public class CmdDisband extends FCommand { + + public CmdDisband() { + super(); + this.aliases.add("disband"); + + this.optionalArgs.put("faction", "yours"); + + this.requirements = new CommandRequirements.Builder(Permission.DISBAND).build(); + } + + @Override + public void perform(CommandContext context) { + // The faction, default to your own.. but null if console sender. + Faction faction = context.argAsFaction(0, context.fPlayer == null ? null : context.faction); + if (faction == null) { + return; + } + + boolean isfaction = context.fPlayer != null && faction == context.faction; + long time; + + + if (isfaction) { + if (!context.fPlayer.isAdminBypassing() && !faction.hasAccess(context.fPlayer, PermissibleAction.DISBAND)) { + context.msg(TL.GENERIC_NOPERMISSION.format(PermissibleAction.DISBAND)); + return; + } + } else { + if (!Permission.DISBAND_ANY.has(context.sender, true)) { + return; + } + } + + if (!faction.isNormal()) { + context.msg(TL.COMMAND_DISBAND_IMMUTABLE.toString()); + return; + } + if (faction.isPermanent()) { + context.msg(TL.COMMAND_DISBAND_MARKEDPERMANENT.toString()); + return; + } + + boolean access = false; + if (context.player.hasMetadata("disband_confirm") && (time = context.player.getMetadata("disband_confirm").get(0).asLong()) != 0L && System.currentTimeMillis() - time <= TimeUnit.SECONDS.toMillis(3L)) { + access = true; + } + if (!access) { + context.player.playSound(context.player.getLocation(), "ANVIL_LAND", 1.0f, 1.4f); + FDisbandConfirmGUI fDisbandConfirmGUI = new FDisbandConfirmGUI(context.player, faction); + fDisbandConfirmGUI.getConfirmGUI().open(context.player); + return; + } + + if (!FactionsPlugin.getInstance().getLandRaidControl().canDisbandFaction(faction, context)) { + return; + } + + FactionDisbandEvent disbandEvent = new FactionDisbandEvent(context.player, faction.getId()); + Bukkit.getServer().getPluginManager().callEvent(disbandEvent); + if (disbandEvent.isCancelled()) { + return; + } + + // Send FPlayerLeaveEvent for each player in the faction + for (FPlayer fplayer : faction.getFPlayers()) { + Bukkit.getServer().getPluginManager().callEvent(new FPlayerLeaveEvent(fplayer, faction, FPlayerLeaveEvent.PlayerLeaveReason.DISBAND)); + } + + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + String who = context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer); + if (fplayer.getFaction() == faction) { + fplayer.msg(TL.COMMAND_DISBAND_BROADCAST_YOURS, who); + } else { + //fplayer.msg(TL.COMMAND_DISBAND_BROADCAST_NOTYOURS, who, faction.getTag(fplayer)); + } + } + if (FactionsPlugin.getInstance().conf().logging().isFactionDisband()) { + //TODO: Format this correctly and translate. + FactionsPlugin.getInstance().log("The faction " + faction.getTag() + " (" + faction.getId() + ") was disbanded by " + (context.player == null ? "console command" : context.fPlayer.getName()) + "."); + } + + if (Econ.shouldBeUsed() && context.player != null) { + //Give all the faction's money to the disbander + double amount = Econ.getBalance(faction); + Econ.transferMoney(context.fPlayer, faction, context.fPlayer, amount, false); + + if (amount > 0.0) { + String amountString = Econ.moneyString(amount); + context.msg(TL.COMMAND_DISBAND_HOLDINGS, amountString); + //TODO: Format this correctly and translate + FactionsPlugin.getInstance().log(context.fPlayer.getName() + " has been given bank holdings of " + amountString + " from disbanding " + faction.getTag() + "."); + } + } + + Factions.getInstance().removeFaction(faction.getId()); + FTeamWrapper.applyUpdates(faction); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DISBAND_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdFly.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdFly.java new file mode 100644 index 0000000..5537006 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdFly.java @@ -0,0 +1,101 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.FlightUtil; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.WarmUpUtil; + +public class CmdFly extends FCommand { + + public CmdFly() { + super(); + this.aliases.add("fly"); + + this.optionalArgs.put("on/off/auto", "flip"); + + this.requirements = new CommandRequirements.Builder(Permission.FLY) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + if (context.args.size() == 0) { + if(FactionsPlugin.getInstance().isSOTW() && !Permission.SOTW.has(context.sender)){ + context.fPlayer.msg(TL.PLAYER_SOTW_NOFLY); + return; + } + if (Permission.FLY_AUTO.has(context.player, false)) { + boolean did = toggleFlight(context, !context.fPlayer.isAutoFlying(), true); + + if(did){ + //context.fPlayer.setAutoFlying(!context.fPlayer.isAutoFlying()); + } + }else{ + //toggleFlight(context, !context.fPlayer.isFlying(), true); + } + } else if (context.args.size() == 1) { + if(FactionsPlugin.getInstance().isSOTW() && !Permission.SOTW.has(context.sender)){ + context.fPlayer.msg(TL.PLAYER_SOTW_NOFLY); + return; + } + if (context.argAsString(0).equalsIgnoreCase("auto")) { + // Player Wants to AutoFly + if (Permission.FLY_AUTO.has(context.player, true)) { + //context.fPlayer.setAutoFlying(!context.fPlayer.isAutoFlying()); + //toggleFlight(context, context.fPlayer.isAutoFlying(), false); + } + } else { + //toggleFlight(context, context.argAsBool(0), true); + } + } + } + + private boolean toggleFlight(final CommandContext context, final boolean toggle, boolean notify) { + // If false do nothing besides set + if (!toggle) { + //context.fPlayer.setFlying(false); + return true; + } + // Do checks if true + if (!flyTest(context, notify)) { + return false; + } + + context.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", () -> { + if (flyTest(context, notify)) { + if(FactionsPlugin.getInstance().isSOTW() && !Permission.SOTW.has(context.sender)){ + context.fPlayer.msg(TL.PLAYER_SOTW_NOFLY); + }else{ + //context.fPlayer.setFlying(true); + } + } + }, this.plugin.conf().commands().fly().getDelay()); + return true; + } + + private boolean flyTest(final CommandContext context, boolean notify) { + if (!context.fPlayer.canFlyAtLocation()) { + if (notify) { + Faction factionAtLocation = Board.getInstance().getFactionAt(context.fPlayer.getLastStoodAt()); + context.msg(TL.COMMAND_FLY_NO_ACCESS, factionAtLocation.getTag(context.fPlayer)); + } + return false; + } else if (FlightUtil.instance().enemiesNearby(context.fPlayer, FactionsPlugin.getInstance().conf().commands().fly().getEnemyRadius())) { + if (notify) { + context.msg(TL.COMMAND_FLY_ENEMY_NEARBY); + } + return false; + } + return true; + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_FLY_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java new file mode 100644 index 0000000..cd8bbfe --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java @@ -0,0 +1,202 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + + +public class CmdHelp extends FCommand { + + public CmdHelp() { + super(); + this.aliases.add("help"); + this.aliases.add("h"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("page", "1"); + + this.requirements = new CommandRequirements.Builder(Permission.HELP).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + if (FactionsPlugin.getInstance().conf().commands().help().isUseOldHelp()) { + if (helpPages == null) { + updateHelp(context); + } + + int page = context.argAsInt(0, 1); + context.sendMessage(plugin.txt().titleize("Factions Help (" + page + "/" + helpPages.size() + ")")); + + page -= 1; + + if (page < 0 || page >= helpPages.size()) { + context.msg(TL.COMMAND_HELP_404.format(String.valueOf(page))); + return; + } + context.sendMessage(helpPages.get(page)); + return; + } + Map> help = FactionsPlugin.getInstance().conf().commands().help().getEntries(); + String pageArg = context.argAsString(0, "1"); + List page = help.get(pageArg); + if (page == null || page.isEmpty()) { + context.msg(TL.COMMAND_HELP_404.format(pageArg)); + return; + } + for (String helpLine : page) { + context.sendMessage(FactionsPlugin.getInstance().txt().parse(helpLine)); + } + } + + //----------------------------------------------// + // Build the help pages + //----------------------------------------------// + + public ArrayList> helpPages; + + public void updateHelp(CommandContext context) { + helpPages = new ArrayList<>(); + ArrayList pageLines; + + pageLines = new ArrayList<>(); + pageLines.add(FCmdRoot.getInstance().cmdHelp.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdList.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdShow.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdPower.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdJoin.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdLeave.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdChat.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdToggleAllianceChat.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdHome.getUsageTemplate(context, true)); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_NEXTCREATE.toString())); + helpPages.add(pageLines); + + pageLines = new ArrayList<>(); + pageLines.add(FCmdRoot.getInstance().cmdCreate.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdDescription.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdTag.getUsageTemplate(context, true)); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_INVITATIONS.toString())); + pageLines.add(FCmdRoot.getInstance().cmdOpen.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdInvite.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdDeinvite.getUsageTemplate(context, true)); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_HOME.toString())); + pageLines.add(FCmdRoot.getInstance().cmdSethome.getUsageTemplate(context, true)); + helpPages.add(pageLines); + + if (Econ.isSetup() && FactionsPlugin.getInstance().conf().economy().isEnabled() && FactionsPlugin.getInstance().conf().economy().isBankEnabled()) { + pageLines = new ArrayList<>(); + pageLines.add(""); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_BANK_1.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_BANK_2.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_BANK_3.toString())); + pageLines.add(""); + pageLines.add(FCmdRoot.getInstance().cmdMoney.getUsageTemplate(context, true)); + pageLines.add(""); + pageLines.add(""); + pageLines.add(""); + helpPages.add(pageLines); + } + + pageLines = new ArrayList<>(); + pageLines.add(FCmdRoot.getInstance().cmdClaim.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdAutoClaim.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdUnclaim.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdUnclaimall.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdKick.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdMod.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdAdmin.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdTitle.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdSB.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdSeeChunk.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdStatus.getUsageTemplate(context, true)); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PLAYERTITLES.toString())); + helpPages.add(pageLines); + + pageLines = new ArrayList<>(); + pageLines.add(FCmdRoot.getInstance().cmdMap.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdBoom.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdOwner.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdOwnerList.getUsageTemplate(context, true)); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_OWNERSHIP_1.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_OWNERSHIP_2.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_OWNERSHIP_3.toString())); + helpPages.add(pageLines); + + pageLines = new ArrayList<>(); + pageLines.add(FCmdRoot.getInstance().cmdDisband.getUsageTemplate(context, true)); + pageLines.add(""); + pageLines.add(FCmdRoot.getInstance().cmdRelationAlly.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdRelationNeutral.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdRelationEnemy.getUsageTemplate(context, true)); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_1.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_2.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_3.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_4.toString())); + helpPages.add(pageLines); + + pageLines = new ArrayList<>(); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_5.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_6.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_7.toString())); + pageLines.add(TL.COMMAND_HELP_RELATIONS_8.toString()); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_9.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_10.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_11.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_12.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_RELATIONS_13.toString())); + helpPages.add(pageLines); + + pageLines = new ArrayList<>(); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PERMISSIONS_1.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PERMISSIONS_2.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PERMISSIONS_3.toString())); + pageLines.add(TL.COMMAND_HELP_PERMISSIONS_4.toString()); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PERMISSIONS_5.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PERMISSIONS_6.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PERMISSIONS_7.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PERMISSIONS_8.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_PERMISSIONS_9.toString())); + helpPages.add(pageLines); + + pageLines = new ArrayList<>(); + pageLines.add(TL.COMMAND_HELP_MOAR_1.toString()); + pageLines.add(FCmdRoot.getInstance().cmdBypass.getUsageTemplate(context, true)); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_ADMIN_1.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_ADMIN_2.toString())); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_ADMIN_3.toString())); + pageLines.add(FCmdRoot.getInstance().cmdSafeunclaimall.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdWarunclaimall.getUsageTemplate(context, true)); + //TODO:TL + pageLines.add(plugin.txt().parse("Note: " + FCmdRoot.getInstance().cmdUnclaim.getUsageTemplate(context, false) + FactionsPlugin.getInstance().txt().parse("") + " works on safe/war zones as well.")); + pageLines.add(FCmdRoot.getInstance().cmdPeaceful.getUsageTemplate(context, true)); + helpPages.add(pageLines); + + pageLines = new ArrayList<>(); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_MOAR_2.toString())); + pageLines.add(FCmdRoot.getInstance().cmdChatSpy.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdPermanent.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdPermanentPower.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdPowerBoost.getUsageTemplate(context, true)); + helpPages.add(pageLines); + + pageLines = new ArrayList<>(); + pageLines.add(plugin.txt().parse(TL.COMMAND_HELP_MOAR_3.toString())); + pageLines.add(FCmdRoot.getInstance().cmdLock.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdReload.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdSaveAll.getUsageTemplate(context, true)); + pageLines.add(FCmdRoot.getInstance().cmdVersion.getUsageTemplate(context, true)); + helpPages.add(pageLines); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_HELP_DESCRIPTION; + } +} + diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdHome.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdHome.java new file mode 100644 index 0000000..32034ad --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdHome.java @@ -0,0 +1,169 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerTeleportEvent; +import com.massivecraft.factions.integration.Essentials; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.SmokeUtil; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.WarmUpUtil; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + + +public class CmdHome extends FCommand { + + public CmdHome() { + super(); + this.aliases.add("home"); + + this.optionalArgs.put("faction", "yours"); + + this.requirements = new CommandRequirements.Builder(Permission.HOME) + .playerOnly() + .noDisableOnLock() + .build(); + } + + @Override + public void perform(final CommandContext context) { + // TODO: Hide this command on help also. + + Faction targetFaction = context.argAsFaction(0, context.fPlayer == null ? null : context.faction); + + if (targetFaction != context.faction && context.fPlayer.isAdminBypassing()) { + if (targetFaction.hasHome()) { + FactionsPlugin.getInstance().teleport(context.player, targetFaction.getHome()); + } else { + context.fPlayer.msg(TL.COMMAND_HOME_NOHOME.toString()); + } + return; + } + + if (!FactionsPlugin.getInstance().conf().factions().homes().isEnabled()) { + context.fPlayer.msg(TL.COMMAND_HOME_DISABLED); + return; + } + + if (!FactionsPlugin.getInstance().conf().factions().homes().isTeleportCommandEnabled()) { + context.fPlayer.msg(TL.COMMAND_HOME_TELEPORTDISABLED); + return; + } + + if (!targetFaction.hasHome()) { + if (targetFaction == context.faction) { + if (context.faction.hasAccess(context.fPlayer, PermissibleAction.SETHOME)) { + context.fPlayer.msg(TL.COMMAND_HOME_NOHOME.toString() + TL.GENERIC_YOUSHOULD.toString()); + } else { + context.fPlayer.msg(TL.COMMAND_HOME_NOHOME.toString() + TL.GENERIC_ASKYOURLEADER.toString()); + } + context.fPlayer.sendMessage(FCmdRoot.getInstance().cmdSethome.getUsageTemplate(context)); + } else { + context.fPlayer.msg(TL.COMMAND_HOME_NOHOME.toString()); + } + return; + } + + if (!targetFaction.hasAccess(context.fPlayer, PermissibleAction.HOME)) { + context.fPlayer.msg(TL.COMMAND_HOME_DENIED, targetFaction.getTag(context.fPlayer)); + return; + } + + if (!FactionsPlugin.getInstance().conf().factions().homes().isTeleportAllowedFromEnemyTerritory() && context.fPlayer.isInEnemyTerritory()) { + context.fPlayer.msg(TL.COMMAND_HOME_INENEMY); + return; + } + + if (!FactionsPlugin.getInstance().conf().factions().homes().isTeleportAllowedFromDifferentWorld() && context.player.getWorld().getUID() != targetFaction.getHome().getWorld().getUID()) { + context.fPlayer.msg(TL.COMMAND_HOME_WRONGWORLD); + return; + } + + Faction faction = Board.getInstance().getFactionAt(new FLocation(context.player.getLocation())); + final Location loc = context.player.getLocation().clone(); + + // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby + if (FactionsPlugin.getInstance().conf().factions().homes().getTeleportAllowedEnemyDistance() > 0 && + !faction.isSafeZone() && + (!context.fPlayer.isInOwnTerritory() || !FactionsPlugin.getInstance().conf().factions().homes().isTeleportIgnoreEnemiesIfInOwnTerritory())) { + World w = loc.getWorld(); + double x = loc.getX(); + double y = loc.getY(); + double z = loc.getZ(); + + for (Player p : context.player.getServer().getOnlinePlayers()) { + if (p == null || !p.isOnline() || p.isDead() || p == context.player || p.getWorld() != w) { + continue; + } + + FPlayer fp = FPlayers.getInstance().getByPlayer(p); + if (context.fPlayer.getRelationTo(fp) != Relation.ENEMY || fp.isVanished()) { + continue; + } + + Location l = p.getLocation(); + double dx = Math.abs(x - l.getX()); + double dy = Math.abs(y - l.getY()); + double dz = Math.abs(z - l.getZ()); + double max = FactionsPlugin.getInstance().conf().factions().homes().getTeleportAllowedEnemyDistance(); + + // box-shaped distance check + if (dx > max || dy > max || dz > max) { + continue; + } + + context.fPlayer.msg(TL.COMMAND_HOME_ENEMYNEAR, String.valueOf(FactionsPlugin.getInstance().conf().factions().homes().getTeleportAllowedEnemyDistance())); + return; + } + } + + Location destination = targetFaction.getHome(); + FPlayerTeleportEvent tpEvent = new FPlayerTeleportEvent(context.fPlayer, destination, FPlayerTeleportEvent.PlayerTeleportReason.HOME); + Bukkit.getServer().getPluginManager().callEvent(tpEvent); + if (tpEvent.isCancelled()) { + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostHome(), TL.COMMAND_HOME_TOTELEPORT.toString(), TL.COMMAND_HOME_FORTELEPORT.toString())) { + return; + } + + // if Essentials teleport handling is enabled and available, pass the teleport off to it (for delay and cooldown) + if (Essentials.handleTeleport(context.player, destination)) { + return; + } + + context.doWarmUp(WarmUpUtil.Warmup.HOME, TL.WARMUPS_NOTIFY_TELEPORT, "Home", () -> { + // Create a smoke effect + if (FactionsPlugin.getInstance().conf().factions().homes().isTeleportCommandSmokeEffectEnabled()) { + List smokeLocations = new ArrayList<>(); + smokeLocations.add(loc); + smokeLocations.add(loc.add(0, 1, 0)); + smokeLocations.add(destination); + smokeLocations.add(destination.clone().add(0, 1, 0)); + SmokeUtil.spawnCloudRandom(smokeLocations, FactionsPlugin.getInstance().conf().factions().homes().getTeleportCommandSmokeEffectThickness()); + } + + FactionsPlugin.getInstance().teleport(context.player, destination); + }, this.plugin.conf().commands().home().getDelay()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_HOME_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java new file mode 100644 index 0000000..6c500c3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java @@ -0,0 +1,36 @@ +package com.massivecraft.factions.cmd; + + +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdInspect extends FCommand { + public CmdInspect() { + super(); + this.aliases.add("inspect"); + this.aliases.add("ins"); + + this.requirements = new CommandRequirements.Builder(Permission.STEALTH) + .playerOnly() + .memberOnly() + .build(); + } + + + @Override + public void perform(CommandContext context) { + if (context.fPlayer.isInspectMode()) { + context.fPlayer.setInspectMode(false); + context.msg(TL.COMMAND_INSPECT_DISABLED_MSG); + } else { + context.fPlayer.setInspectMode(true); + context.msg(TL.COMMAND_INSPECT_ENABLED); + } + + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_INSPECT_DESCRIPTION; + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java new file mode 100644 index 0000000..8473625 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java @@ -0,0 +1,76 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import mkremins.fanciful.FancyMessage; +import org.bukkit.ChatColor; + +public class CmdInvite extends FCommand { + + public CmdInvite() { + super(); + this.aliases.add("invite"); + this.aliases.add("inv"); + + this.requiredArgs.add("player"); + + this.requirements = new CommandRequirements.Builder(Permission.INVITE) + .memberOnly() + .withAction(PermissibleAction.INVITE) + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0); + if (target == null) { + return; + } + + if (target.getFaction() == context.faction) { + context.msg(TL.COMMAND_INVITE_ALREADYMEMBER, target.getName(), context.faction.getTag()); + context.msg(TL.GENERIC_YOUMAYWANT.toString() + FCmdRoot.getInstance().cmdKick.getUsageTemplate(context)); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostInvite(), TL.COMMAND_INVITE_TOINVITE.toString(), TL.COMMAND_INVITE_FORINVITE.toString())) { + return; + } + + if (context.faction.isBanned(target)) { + context.msg(TL.COMMAND_INVITE_BANNED, target.getName()); + return; + } + + context.faction.invite(target); + if (!target.isOnline()) { + return; + } + + // Tooltips, colors, and commands only apply to the string immediately before it. + FancyMessage message = new FancyMessage(context.fPlayer.describeTo(target, true)) + .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " join " + context.faction.getTag()) + .then(TL.COMMAND_INVITE_INVITEDYOU.toString()) + .color(ChatColor.YELLOW) + .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " join " + context.faction.getTag()) + .then(context.faction.describeTo(target)).tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " join " + context.faction.getTag()); + + message.send(target.getPlayer()); + + //you.msg("%s invited you to %s",context.fPlayer.describeTo(you, true), context.faction.describeTo(you)); + context.faction.msg(TL.COMMAND_INVITE_INVITED, context.fPlayer.describeTo(context.faction, true), target.describeTo(context.faction)); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_INVITE_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java new file mode 100644 index 0000000..a8890b4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java @@ -0,0 +1,134 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerJoinEvent; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.CC; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +public class CmdJoin extends FCommand { + + public CmdJoin() { + super(); + this.aliases.add("join"); + + this.requiredArgs.add("faction"); + this.optionalArgs.put("player", "you"); + + this.requirements = new CommandRequirements.Builder(Permission.JOIN) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.argAsFaction(0); + if (faction == null) { + return; + } + + FPlayer fplayer = context.argAsBestFPlayerMatch(1, context.fPlayer, false); + boolean samePlayer = fplayer == context.fPlayer; + + if (!samePlayer && !Permission.JOIN_OTHERS.has(context.sender, false)) { + context.msg(TL.COMMAND_JOIN_CANNOTFORCE); + return; + } + + if (fplayer.getRole() == Role.ALT && !faction.isInvited(fplayer)) { + fplayer.getPlayer().sendMessage(CC.translate("&c&l(!)&c You are not invited to this faction!")); + return; + } + + if (!faction.isNormal()) { + context.msg(TL.COMMAND_JOIN_SYSTEMFACTION); + return; + } + + if (faction == fplayer.getFaction()) { + //TODO:TL + context.msg(TL.COMMAND_JOIN_ALREADYMEMBER, fplayer.describeTo(context.fPlayer, true), (samePlayer ? "are" : "is"), faction.getTag(context.fPlayer)); + return; + } + + if (fplayer.hasFaction()) { + //TODO:TL + context.msg(TL.COMMAND_JOIN_INOTHERFACTION, fplayer.describeTo(context.fPlayer, true), (samePlayer ? "your" : "their")); + return; + } + + if (!FactionsPlugin.getInstance().getLandRaidControl().canJoinFaction(faction, fplayer, context)) { + return; + } + + final int memberLimit = FactionsPlugin.getInstance().conf().factions().other().getFactionMemberLimit(); + + if(!fplayer.isAdminBypassing()){ + if (faction.getSize() >= memberLimit) { + context.msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(context.fPlayer), memberLimit, fplayer.describeTo(context.fPlayer, false)); + return; + } + } + + if (!(faction.getOpen() || faction.isInvited(fplayer) || context.fPlayer.isAdminBypassing() || Permission.JOIN_ANY.has(context.sender, false))) { + context.msg(TL.COMMAND_JOIN_REQUIRESINVITATION); + if (samePlayer) { + faction.msg(TL.COMMAND_JOIN_ATTEMPTEDJOIN, fplayer.describeTo(faction, true)); + } + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (samePlayer && !context.canAffordCommand(FactionsPlugin.getInstance().conf().economy().getCostJoin(), TL.COMMAND_JOIN_TOJOIN.toString())) { + return; + } + + // Check for ban + if (!context.fPlayer.isAdminBypassing() && faction.isBanned(context.fPlayer)) { + context.fPlayer.msg(TL.COMMAND_JOIN_BANNED, faction.getTag(context.fPlayer)); + return; + } + + // trigger the join event (cancellable) + FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(context.player), faction, FPlayerJoinEvent.PlayerJoinReason.COMMAND); + Bukkit.getServer().getPluginManager().callEvent(joinEvent); + if (joinEvent.isCancelled()) { + return; + } + + // then make 'em pay (if applicable) + if (samePlayer && !context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostJoin(), TL.COMMAND_JOIN_TOJOIN.toString(), TL.COMMAND_JOIN_FORJOIN.toString())) { + return; + } + + context.fPlayer.msg(TL.COMMAND_JOIN_SUCCESS, fplayer.describeTo(context.fPlayer, true), faction.getTag(context.fPlayer)); + + if (!samePlayer) { + fplayer.msg(TL.COMMAND_JOIN_MOVED, context.fPlayer.describeTo(fplayer, true), faction.getTag(fplayer)); + } + faction.msg(TL.COMMAND_JOIN_JOINED, fplayer.describeTo(faction, true)); + + fplayer.resetFactionData(); + fplayer.setFaction(faction); + faction.deinvite(fplayer); + fplayer.setRole(faction.getDefaultRole()); + + if (FactionsPlugin.getInstance().conf().logging().isFactionJoin()) { + if (samePlayer) { + FactionsPlugin.getInstance().log(TL.COMMAND_JOIN_JOINEDLOG.toString(), fplayer.getName(), faction.getTag()); + } else { + FactionsPlugin.getInstance().log(TL.COMMAND_JOIN_MOVEDLOG.toString(), context.fPlayer.getName(), fplayer.getName(), faction.getTag()); + } + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_JOIN_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdKick.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdKick.java new file mode 100644 index 0000000..afbeae9 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdKick.java @@ -0,0 +1,133 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerLeaveEvent; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import mkremins.fanciful.FancyMessage; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; + +public class CmdKick extends FCommand { + + public CmdKick() { + super(); + this.aliases.add("kick"); + + this.optionalArgs.put("player", "player"); + + this.requirements = new CommandRequirements.Builder(Permission.KICK) + .memberOnly() + .withAction(PermissibleAction.KICK) + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer toKick = context.argIsSet(0) ? context.argAsBestFPlayerMatch(0) : null; + if (toKick == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_KICK_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : context.faction.getFPlayersWhereRole(Role.NORMAL)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " kick " + s); + } + if (context.fPlayer.getRole().isAtLeast(Role.COLEADER)) { + // For both coleader and admin, add mods. + for (FPlayer player : context.faction.getFPlayersWhereRole(Role.MODERATOR)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.GRAY).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " kick " + s); + } + if (context.fPlayer.getRole() == Role.ADMIN) { + // Only add coleader to this for the leader. + for (FPlayer player : context.faction.getFPlayersWhereRole(Role.COLEADER)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.RED).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " kick " + s); + } + } + } + + context.sendFancyMessage(msg); + return; + } + + if (context.fPlayer == toKick) { + context.msg(TL.COMMAND_KICK_SELF); + context.msg(TL.GENERIC_YOUMAYWANT.toString() + FCmdRoot.getInstance().cmdLeave.getUsageTemplate(context)); + return; + } + + Faction toKickFaction = toKick.getFaction(); + + // players with admin-level "disband" permission can bypass these requirements + if (!Permission.KICK_ANY.has(context.sender)) { + if (toKickFaction != context.faction) { + context.msg(TL.COMMAND_KICK_NOTMEMBER, toKick.describeTo(context.fPlayer, true), context.faction.describeTo(context.fPlayer)); + return; + } + + if (toKick.getRole().value >= context.fPlayer.getRole().value) { + context.msg(TL.COMMAND_KICK_INSUFFICIENTRANK); + return; + } + + if (toKick.getRole().value == context.fPlayer.getRole().value) { + context.msg(TL.COMMAND_KICK_INSUFFICIENTRANK); + return; + } + + if (!FactionsPlugin.getInstance().getLandRaidControl().canKick(toKick, context)) { + return; + } + } + + if (toKickFaction.isWilderness()) { + context.sender.sendMessage(TL.COMMAND_KICK_NONE.toString()); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!context.canAffordCommand(FactionsPlugin.getInstance().conf().economy().getCostKick(), TL.COMMAND_KICK_TOKICK.toString())) { + return; + } + + // trigger the leave event (cancellable) [reason:kicked] + FPlayerLeaveEvent event = new FPlayerLeaveEvent(toKick, toKick.getFaction(), FPlayerLeaveEvent.PlayerLeaveReason.KICKED); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + + // then make 'em pay (if applicable) + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostKick(), TL.COMMAND_KICK_TOKICK.toString(), TL.COMMAND_KICK_FORKICK.toString())) { + return; + } + + toKickFaction.msg(TL.COMMAND_KICK_FACTION, context.fPlayer.describeTo(toKickFaction, true), toKick.describeTo(toKickFaction, true)); + toKick.msg(TL.COMMAND_KICK_KICKED, context.fPlayer.describeTo(toKick, true), toKickFaction.describeTo(toKick)); + if (toKickFaction != context.faction) { + context.msg(TL.COMMAND_KICK_KICKS, toKick.describeTo(context.fPlayer), toKickFaction.describeTo(context.fPlayer)); + } + + if (FactionsPlugin.getInstance().conf().logging().isFactionKick()) { + FactionsPlugin.getInstance().log((context.player == null ? "A console command" : context.fPlayer.getName()) + " kicked " + toKick.getName() + " from the faction: " + toKickFaction.getTag()); + } + + if (toKick.getRole() == Role.ADMIN) { + toKickFaction.promoteNewLeader(); + } + + toKickFaction.deinvite(toKick); + toKick.resetFactionData(); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_KICK_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java new file mode 100644 index 0000000..fe768f6 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java @@ -0,0 +1,33 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +import java.util.*; + +public class CmdLeave extends FCommand { + + public CmdLeave() { + super(); + this.aliases.add("leave"); + + this.requirements = new CommandRequirements.Builder(Permission.LEAVE) + .memberOnly() + .build(); + } + + private Map confirm = new HashMap<>(); + + @Override + public void perform(CommandContext context) { + context.fPlayer.leave(true); + } + + @Override + public TL getUsageTranslation() { + return TL.LEAVE_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdList.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdList.java new file mode 100644 index 0000000..fda42d9 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdList.java @@ -0,0 +1,118 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.tag.Tag; +import com.massivecraft.factions.util.TL; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.function.Function; + + +public class CmdList extends FCommand { + + public CmdList() { + super(); + this.aliases.add("list"); + this.aliases.add("ls"); + + this.optionalArgs.put("page", "1"); + + this.requirements = new CommandRequirements.Builder(Permission.LIST).build(); + } + + @Override + public void perform(CommandContext context) { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostList(), "to list the factions", "for listing the factions")) { + return; + } + + ArrayList factionList = Factions.getInstance().getAllFactions(); + factionList.remove(Factions.getInstance().getWilderness()); + factionList.remove(Factions.getInstance().getSafeZone()); + factionList.remove(Factions.getInstance().getWarZone()); + + // remove exempt factions + if (!context.sender.hasPermission(Permission.SHOW_BYPASS_EXEMPT.toString())) { + List exemptFactions = FactionsPlugin.getInstance().conf().commands().show().getExempt(); + factionList.removeIf(next -> exemptFactions.contains(next.getTag())); + } + + // Sort by total followers first + factionList.sort(this.compare(Faction::getFPlayers)); + + // Then sort by how many members are online now + factionList.sort(this.compare(f -> f.getFPlayersWhereOnline(true))); + + ArrayList lines = new ArrayList<>(); + + factionList.add(0, Factions.getInstance().getWilderness()); + + final int pageheight = 9; + int pagenumber = context.argAsInt(0, 1); + int pagecount = (factionList.size() / pageheight) + 1; + if (pagenumber > pagecount) { + pagenumber = pagecount; + } else if (pagenumber < 1) { + pagenumber = 1; + } + int start = (pagenumber - 1) * pageheight; + int end = start + pageheight; + if (end > factionList.size()) { + end = factionList.size(); + } + + + String header = plugin.conf().commands().list().getHeader(); + String footer = plugin.conf().commands().list().getFooter(); + + if (!header.isEmpty()) { + header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount)); + lines.add(plugin.txt().parse(header)); + } + + for (Faction faction : factionList.subList(start, end)) { + if (faction.isWilderness()) { + continue; + } + String entry = plugin.conf().commands().list().getEntry(); + + if(context.fPlayer != null && context.fPlayer.getFaction() != faction && !Permission.CLAIM_SEEALL.has(context.sender)){ + entry = entry.replace("{chunks}", "???"); + } + + lines.add(plugin.txt().parse(Tag.parsePlain(faction, context.fPlayer, entry))); + } + + if (!footer.isEmpty()) { + footer = footer.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount)); + lines.add(plugin.txt().parse(footer)); + } + + context.sendMessage(lines); + } + + private Comparator compare(Function> func) { + return (f1, f2) -> { + int f1Size = func.apply(f1).size(); + int f2Size = func.apply(f2).size(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }; + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LIST_DESCRIPTION; + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdListClaims.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdListClaims.java new file mode 100644 index 0000000..0ed69f1 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdListClaims.java @@ -0,0 +1,165 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Queue; +import java.util.Set; + +public class CmdListClaims extends FCommand { + + public CmdListClaims() { + super(); + this.aliases.add("listclaims"); + this.aliases.add("listclaim"); + + this.optionalArgs.put("world", "currentworld"); + this.optionalArgs.put("faction", "yours"); + + this.requirements = new CommandRequirements.Builder(Permission.LISTCLAIMS) + .withAction(PermissibleAction.LISTCLAIMS) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + World world = context.player.getWorld(); + if (context.argIsSet(0)) { + world = Bukkit.getWorld(context.argAsString(0)); + } + if (world == null) { + context.msg(TL.COMMAND_LISTCLAIMS_INVALIDWORLD, context.argAsString(0)); + return; + } + Faction faction = context.faction; + if (context.argIsSet(1)) { + if (Permission.LISTCLAIMS_OTHER.has(context.sender, true)) { + faction = context.argAsFaction(1); + } else { + return; + } + } + if (faction == null) { + context.msg(TL.GENERIC_NOFACTIONMATCH, context.argAsString(1)); + return; + } + Map worldClaims = new HashMap<>(); + for (FLocation loc : Board.getInstance().getAllClaims(faction)) { + if (loc.getWorld().equals(world)) { + worldClaims.put(getLong(loc.getX(), (int) loc.getZ()), new FLoc(loc.getX(), loc.getZ())); + } + } + if (worldClaims.isEmpty()) { + context.msg(TL.COMMAND_LISTCLAIMS_NOCLAIMS, faction.getTag(), world.getName()); + return; + } + Set set; + Queue queue; + FLoc cur; + List displayList = new ArrayList<>(); + for (FLoc activeLoc : worldClaims.values()) { + if (activeLoc.processed) { + continue; + } + set = new HashSet<>(); + set.add(activeLoc); + queue = new LinkedList<>(); + queue.add(activeLoc); + while (!queue.isEmpty()) { + cur = queue.poll(); + cur.processed = true; + addIf(set, queue, worldClaims.get(getLong(cur.x, cur.z + 1))); + addIf(set, queue, worldClaims.get(getLong(cur.x, cur.z - 1))); + addIf(set, queue, worldClaims.get(getLong(cur.x + 1, cur.z))); + addIf(set, queue, worldClaims.get(getLong(cur.x - 1, cur.z))); + } + if (set.size() == 1) { + displayList.add(activeLoc); + } else { + long tX = 0; + long tZ = 0; + for (FLoc loc : set) { + tX += loc.x; + tZ += loc.z; + } + cur = new FLoc((int) (((double) tX) / set.size() + 0.5), (int) (((double) tZ) / set.size() + 0.5)); + cur.total = set.size(); + displayList.add(cur); + } + } + + context.msg(TL.COMMAND_LISTCLAIMS_MESSAGE, faction.getTag(), world.getName()); + StringBuilder builder = new StringBuilder(); + String str; + final String separator = " "; + for (FLoc loc : displayList) { + str = (loc.x << 4 | 8) + "," + (loc.z << 4 | 8) + (loc.total > 1 ? (" (" + loc.total + ")") : ""); + if (builder.length() + separator.length() + str.length() > 75) { + context.msg(builder.toString()); + builder.setLength(0); + } else if (builder.length() > 0) { + builder.append(separator); + } + builder.append(str); + } + if (builder.length() > 0) { + context.msg(builder.toString()); + } + } + + private void addIf(Set set, Queue queue, FLoc loc) { + if (loc != null && !set.contains(loc)) { + set.add(loc); + queue.add(loc); + } + } + + private long getLong(long x, int z) { + return (x << 32) | z; + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LISTCLAIMS_DESCRIPTION; + } + + private class FLoc { + private int x; + private int z; + private boolean processed; + private int total = 1; + + public FLoc(long x, long z) { + this.x = (int) x; + this.z = (int) z; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FLoc fLoc = (FLoc) o; + return x == fLoc.x && z == fLoc.z; + } + + @Override + public int hashCode() { + return Objects.hash(x, z); + } + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLock.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLock.java new file mode 100644 index 0000000..abaccf0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLock.java @@ -0,0 +1,35 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdLock extends FCommand { + + // TODO: This solution needs refactoring. + /* + factions.lock: + description: use the /f lock [on/off] command to temporarily lock the data files from being overwritten + default: op + */ + + public CmdLock() { + super(); + this.aliases.add("lock"); + + this.optionalArgs.put("on/off", "flip"); + + this.requirements = new CommandRequirements.Builder(Permission.LOCK).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + plugin.setLocked(context.argAsBool(0, !plugin.getLocked())); + context.msg(plugin.getLocked() ? TL.COMMAND_LOCK_LOCKED : TL.COMMAND_LOCK_UNLOCKED); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LOCK_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java new file mode 100644 index 0000000..fe12135 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java @@ -0,0 +1,31 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdLogins extends FCommand { + + public CmdLogins() { + super(); + this.aliases.add("login"); + this.aliases.add("logins"); + this.aliases.add("logout"); + this.aliases.add("logouts"); + + this.requirements = new CommandRequirements.Builder(Permission.MONITOR_LOGINS) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + boolean monitor = context.fPlayer.isMonitoringJoins(); + context.msg(TL.COMMAND_LOGINS_TOGGLE, String.valueOf(!monitor)); + context.fPlayer.setMonitorJoins(!monitor); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LOGINS_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMap.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMap.java new file mode 100644 index 0000000..55a66fc --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMap.java @@ -0,0 +1,64 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + + +public class CmdMap extends FCommand { + + public CmdMap() { + super(); + this.aliases.add("map"); + + this.optionalArgs.put("on/off", "once"); + + this.requirements = new CommandRequirements.Builder(Permission.MAP) + .playerOnly() + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + if (context.argIsSet(0)) { + if (context.argAsBool(0, !context.fPlayer.isMapAutoUpdating())) { + // Turn on + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostMap(), "to show the map", "for showing the map")) { + return; + } + + context.fPlayer.setMapAutoUpdating(true); + context.msg(TL.COMMAND_MAP_UPDATE_ENABLED); + + // And show the map once + showMap(context); + } else { + // Turn off + context.fPlayer.setMapAutoUpdating(false); + context.msg(TL.COMMAND_MAP_UPDATE_DISABLED); + } + } else { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostMap(), TL.COMMAND_MAP_TOSHOW, TL.COMMAND_MAP_FORSHOW)) { + return; + } + + showMap(context); + } + } + + public void showMap(CommandContext context) { + context.sendFancyMessage(Board.getInstance().getMap(context.fPlayer, new FLocation(context.fPlayer), context.fPlayer.getPlayer().getLocation().getYaw())); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MAP_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java new file mode 100644 index 0000000..5d695cb --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java @@ -0,0 +1,39 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdMapHeight extends FCommand { + + public CmdMapHeight() { + super(); + + this.aliases.add("mapheight"); + this.aliases.add("mh"); + + this.optionalArgs.put("height", "height"); + + this.requirements = new CommandRequirements.Builder(Permission.MAPHEIGHT) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + if (context.args.size() == 0) { + context.fPlayer.sendMessage(TL.COMMAND_MAPHEIGHT_CURRENT.format(context.fPlayer.getMapHeight())); + return; + } + + int height = context.argAsInt(0); + + context.fPlayer.setMapHeight(height); + context.fPlayer.sendMessage(TL.COMMAND_MAPHEIGHT_SET.format(context.fPlayer.getMapHeight())); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MAPHEIGHT_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMod.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMod.java new file mode 100644 index 0000000..b48367e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdMod.java @@ -0,0 +1,89 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import mkremins.fanciful.FancyMessage; +import org.bukkit.ChatColor; + +public class CmdMod extends FCommand { + + public CmdMod() { + super(); + this.aliases.add("mod"); + this.aliases.add("setmod"); + this.aliases.add("officer"); + this.aliases.add("setofficer"); + + this.optionalArgs.put("player", "player"); + + this.requirements = new CommandRequirements.Builder(Permission.MOD) + .memberOnly() + .withRole(Role.COLEADER) + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer you = context.argAsBestFPlayerMatch(0); + if (you == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_MOD_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : context.faction.getFPlayersWhereRole(Role.NORMAL)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_MOD_CLICKTOPROMOTE.toString() + s).command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " mod " + s); + } + + context.sendFancyMessage(msg); + return; + } + + if(you.getRole() == Role.ALT){ + context.msg(TL.COMMAND_PROMOTE_ISALT); + return; + } + + boolean permAny = Permission.MOD_ANY.has(context.sender, false); + Faction targetFaction = you.getFaction(); + + if (targetFaction != context.faction && !permAny) { + context.msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(context.fPlayer, true)); + return; + } + + if (context.fPlayer != null && context.fPlayer.getRole() != Role.ADMIN && !permAny) { + context.msg(TL.COMMAND_MOD_NOTADMIN); + return; + } + + if (you == context.fPlayer && !permAny) { + context.msg(TL.COMMAND_MOD_SELF); + return; + } + + if (you.getRole() == Role.ADMIN) { + context.msg(TL.COMMAND_MOD_TARGETISADMIN); + return; + } + + if (you.getRole() == Role.MODERATOR) { + // Revoke + you.setRole(Role.NORMAL); + targetFaction.msg(TL.COMMAND_MOD_REVOKED, you.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_MOD_REVOKES, you.describeTo(context.fPlayer, true)); + } else { + // Give + you.setRole(Role.MODERATOR); + targetFaction.msg(TL.COMMAND_MOD_PROMOTED, you.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_MOD_PROMOTES, you.describeTo(context.fPlayer, true)); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MOD_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java new file mode 100644 index 0000000..5cded08 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java @@ -0,0 +1,43 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdModifyPower extends FCommand { + + public CmdModifyPower() { + super(); + + this.aliases.add("pm"); + this.aliases.add("mp"); + this.aliases.add("modifypower"); + this.aliases.add("modpower"); + + this.requiredArgs.add("name"); + this.requiredArgs.add("power"); + + this.requirements = new CommandRequirements.Builder(Permission.MODIFY_POWER).build(); + } + + @Override + public void perform(CommandContext context) { + // /f modify # + FPlayer player = context.argAsBestFPlayerMatch(0); + Double number = context.argAsDouble(1); // returns null if not a Double. + + if (player == null || number == null) { + context.sender.sendMessage(getHelpShort()); + return; + } + + player.alterPower(number); + int newPower = player.getPowerRounded(); // int so we don't have super long doubles. + context.msg(TL.COMMAND_MODIFYPOWER_ADDED, number, player.getName(), newPower); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MODIFYPOWER_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdNear.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdNear.java new file mode 100644 index 0000000..b5d4877 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdNear.java @@ -0,0 +1,76 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.tag.Tag; +import com.massivecraft.factions.util.TL; +import org.bukkit.Location; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class CmdNear extends FCommand { + + public CmdNear() { + super(); + this.aliases.add("near"); + + this.requirements = new CommandRequirements.Builder(Permission.NEAR) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + int radius = FactionsPlugin.getInstance().conf().commands().near().getRadius(); + Set onlineMembers = context.faction.getFPlayersWhereOnline(true, context.fPlayer); + List nearbyMembers = new ArrayList<>(); + + int radiusSquared = radius * radius; + Location loc = context.player.getLocation(); + Location cur = new Location(loc.getWorld(), 0, 0, 0); + for (FPlayer player : onlineMembers) { + if (player == context.fPlayer) { + continue; + } + + player.getPlayer().getLocation(cur); + if (cur.getWorld().getUID().equals(loc.getWorld().getUID()) && cur.distanceSquared(loc) <= radiusSquared) { + nearbyMembers.add(player); + } + } + + StringBuilder playerMessageBuilder = new StringBuilder(); + String playerMessage = TL.COMMAND_NEAR_PLAYER.toString(); + for (FPlayer member : nearbyMembers) { + playerMessageBuilder.append(parsePlaceholders(context.fPlayer, member, playerMessage)); + } + // Append none text if no players where found + if (playerMessageBuilder.toString().isEmpty()) { + playerMessageBuilder.append(TL.COMMAND_NEAR_NONE); + } + + context.msg(TL.COMMAND_NEAR_PLAYERLIST.toString().replace("{players-nearby}", playerMessageBuilder.toString())); + } + + private String parsePlaceholders(FPlayer user, FPlayer target, String string) { + string = Tag.parsePlain(target, string); + string = Tag.parsePlaceholders(target.getPlayer(), string); + string = string.replace("{role}", target.getRole().toString()); + string = string.replace("{role-prefix}", target.getRole().getPrefix()); + // Only run distance calculation if needed + if (string.contains("{distance}")) { + double distance = Math.round(user.getPlayer().getLocation().distance(target.getPlayer().getLocation())); + string = string.replace("{distance}", distance + ""); + } + return string; + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_NEAR_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java new file mode 100644 index 0000000..45f7d62 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java @@ -0,0 +1,50 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdOpen extends FCommand { + + public CmdOpen() { + super(); + this.aliases.add("open"); + + this.optionalArgs.put("yes/no", "flip"); + + this.requirements = new CommandRequirements.Builder(Permission.OPEN) + .playerOnly() + .noDisableOnLock() + .withRole(Role.MODERATOR) + .build(); + } + + @Override + public void perform(CommandContext context) { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostOpen(), TL.COMMAND_OPEN_TOOPEN, TL.COMMAND_OPEN_FOROPEN)) { + return; + } + + context.faction.setOpen(context.argAsBool(0, !context.faction.getOpen())); + + String open = context.faction.getOpen() ? TL.COMMAND_OPEN_OPEN.toString() : TL.COMMAND_OPEN_CLOSED.toString(); + + // Inform + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fplayer.getFactionId().equals(context.faction.getId())) { + fplayer.msg(TL.COMMAND_OPEN_CHANGES, context.fPlayer.getName(), open); + } + //fplayer.msg(TL.COMMAND_OPEN_CHANGED, context.faction.getTag(fplayer.getFaction()), open); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_OPEN_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java new file mode 100644 index 0000000..c59fedb --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java @@ -0,0 +1,102 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + + +public class CmdOwner extends FCommand { + + public CmdOwner() { + super(); + this.aliases.add("owner"); + + this.optionalArgs.put("player", "you"); + + this.requirements = new CommandRequirements.Builder(Permission.OWNER) + .withAction(PermissibleAction.OWNER) + .playerOnly() + .build(); + } + + // TODO: Fix colors! + + @Override + public void perform(CommandContext context) { + boolean hasBypass = context.fPlayer.isAdminBypassing(); + + if (!hasBypass && !context.assertHasFaction()) { + return; + } + + if (!FactionsPlugin.getInstance().conf().factions().ownedArea().isEnabled()) { + context.msg(TL.COMMAND_OWNER_DISABLED); + return; + } + + if (!hasBypass && FactionsPlugin.getInstance().conf().factions().ownedArea().getLimitPerFaction() > 0 && context.faction.getCountOfClaimsWithOwners() >= FactionsPlugin.getInstance().conf().factions().ownedArea().getLimitPerFaction()) { + context.msg(TL.COMMAND_OWNER_LIMIT, FactionsPlugin.getInstance().conf().factions().ownedArea().getLimitPerFaction()); + return; + } + + FLocation flocation = new FLocation(context.fPlayer); + + Faction factionHere = Board.getInstance().getFactionAt(flocation); + if (factionHere != context.faction) { + if (!factionHere.isNormal()) { + context.msg(TL.COMMAND_OWNER_NOTCLAIMED); + return; + } + + if (!hasBypass) { + context.msg(TL.COMMAND_OWNER_WRONGFACTION); + return; + } + + } + + FPlayer target = context.argAsBestFPlayerMatch(0, context.fPlayer); + if (target == null) { + return; + } + + String playerName = target.getName(); + + if (target.getFaction() != context.faction) { + context.msg(TL.COMMAND_OWNER_NOTMEMBER, playerName); + return; + } + + // if no player name was passed, and this claim does already have owners set, clear them + if (context.args.isEmpty() && context.faction.doesLocationHaveOwnersSet(flocation)) { + context.faction.clearClaimOwnership(flocation); + context.msg(TL.COMMAND_OWNER_CLEARED); + return; + } + + if (context.faction.isPlayerInOwnerList(target, flocation)) { + context.faction.removePlayerAsOwner(target, flocation); + context.msg(TL.COMMAND_OWNER_REMOVED, playerName); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostOwner(), TL.COMMAND_OWNER_TOSET, TL.COMMAND_OWNER_FORSET)) { + return; + } + + context.faction.setPlayerAsOwner(target, flocation); + + context.msg(TL.COMMAND_OWNER_ADDED, playerName); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_OWNER_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java new file mode 100644 index 0000000..a9bc3c9 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java @@ -0,0 +1,64 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + + +public class CmdOwnerList extends FCommand { + + public CmdOwnerList() { + super(); + this.aliases.add("ownerlist"); + + this.requirements = new CommandRequirements.Builder(Permission.OWNERLIST) + .playerOnly() + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + boolean hasBypass = context.fPlayer.isAdminBypassing(); + + if (!hasBypass && !context.assertHasFaction()) { + return; + } + + if (!FactionsPlugin.getInstance().conf().factions().ownedArea().isEnabled()) { + context.msg(TL.COMMAND_OWNERLIST_DISABLED); + return; + } + + FLocation flocation = new FLocation(context.fPlayer); + + if (Board.getInstance().getFactionAt(flocation) != context.faction) { + if (!hasBypass) { + context.msg(TL.COMMAND_OWNERLIST_WRONGFACTION); + return; + } + //TODO: This code won't ever be called. + context.faction = Board.getInstance().getFactionAt(flocation); + if (!context.faction.isNormal()) { + context.msg(TL.COMMAND_OWNERLIST_NOTCLAIMED); + return; + } + } + + String owners = context.faction.getOwnerListString(flocation); + + if (owners == null || owners.isEmpty()) { + context.msg(TL.COMMAND_OWNERLIST_NONE); + return; + } + + context.msg(TL.COMMAND_OWNERLIST_OWNERS, owners); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_OWNERLIST_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java new file mode 100644 index 0000000..92fc686 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java @@ -0,0 +1,53 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdPeaceful extends FCommand { + + public CmdPeaceful() { + super(); + this.aliases.add("peaceful"); + + this.requiredArgs.add("faction"); + + this.requirements = new CommandRequirements.Builder(Permission.SET_PEACEFUL).build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.argAsFaction(0); + if (faction == null) { + return; + } + + String change; + if (faction.isPeaceful()) { + change = TL.COMMAND_PEACEFUL_REVOKE.toString(); + faction.setPeaceful(false); + } else { + change = TL.COMMAND_PEACEFUL_GRANT.toString(); + faction.setPeaceful(true); + } + + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + String blame = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true)); + if (fplayer.getFaction() == faction) { + fplayer.msg(TL.COMMAND_PEACEFUL_YOURS, blame, change); + } else { + fplayer.msg(TL.COMMAND_PEACEFUL_OTHER, blame, change, faction.getTag(fplayer)); + } + } + + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PEACEFUL_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java new file mode 100644 index 0000000..92f28ec --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java @@ -0,0 +1,129 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.gui.PermissibleActionGUI; +import com.massivecraft.factions.gui.PermissibleRelationGUI; +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class CmdPerm extends FCommand { + + public CmdPerm() { + super(); + this.aliases.add("perm"); + this.aliases.add("perms"); + this.aliases.add("permission"); + this.aliases.add("permissions"); + + this.optionalArgs.put("relation", "relation"); + this.optionalArgs.put("action", "action"); + this.optionalArgs.put("access", "access"); + + this.requirements = new CommandRequirements.Builder(Permission.PERMISSIONS) + .memberOnly() + .withRole(Role.ADMIN) + .build(); + } + + @Override + public void perform(CommandContext context) { + if (context.args.size() == 0) { + PermissibleRelationGUI ui = new PermissibleRelationGUI(true, context.fPlayer); + ui.open(); + return; + } else if (context.args.size() == 1 && getPermissible(context.argAsString(0)) != null) { + PermissibleActionGUI ui = new PermissibleActionGUI(true, context.fPlayer, getPermissible(context.argAsString(0))); + ui.open(); + return; + } + + // If not opening GUI, then setting the permission manually. + if (context.args.size() < 3) { + context.fPlayer.msg(TL.COMMAND_PERM_DESCRIPTION); + return; + } + + Set permissibles = new HashSet<>(); + Set permissibleActions = new HashSet<>(); + + boolean allRelations = context.argAsString(0).equalsIgnoreCase("all"); + boolean allActions = context.argAsString(1).equalsIgnoreCase("all"); + boolean online = true; + if (FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms() && context.args.size() == 4 && "offline".equalsIgnoreCase(context.argAsString(3))) { + online = false; + } + + if (allRelations) { + permissibles.addAll(context.faction.getPermissions().keySet()); + } else { + Permissible permissible = getPermissible(context.argAsString(0)); + + if (permissible == null) { + context.fPlayer.msg(TL.COMMAND_PERM_INVALID_RELATION); + return; + } + + permissibles.add(permissible); + } + + if (allActions) { + permissibleActions.addAll(Arrays.asList(PermissibleAction.values())); + } else { + PermissibleAction permissibleAction = PermissibleAction.fromString(context.argAsString(1)); + if (permissibleAction == null) { + context.fPlayer.msg(TL.COMMAND_PERM_INVALID_ACTION); + return; + } + + permissibleActions.add(permissibleAction); + } + + boolean access; + switch (context.argAsString(2).toLowerCase()) { + case "allow": + case "true": + access = true; + break; + case "deny": + case "false": + access = false; + break; + default: + context.fPlayer.msg(TL.COMMAND_PERM_INVALID_ACCESS); + return; + } + + for (Permissible permissible : permissibles) { + for (PermissibleAction permissibleAction : permissibleActions) { + context.fPlayer.getFaction().setPermission(online, permissible, permissibleAction, access); + } + } + + context.fPlayer.msg(TL.COMMAND_PERM_SET, context.argAsString(1), access, context.argAsString(0)); + FactionsPlugin.getInstance().log(String.format(TL.COMMAND_PERM_SET.toString(), context.argAsString(1), access, context.argAsString(0)) + " for faction " + context.fPlayer.getTag()); + } + + private Permissible getPermissible(String name) { + if (Role.fromString(name.toUpperCase()) != null) { + return Role.fromString(name.toUpperCase()); + } else if (Relation.fromString(name.toUpperCase()) != null) { + return Relation.fromString(name.toUpperCase()); + } else { + return null; + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PERM_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java new file mode 100644 index 0000000..416656f --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java @@ -0,0 +1,55 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + + +public class CmdPermanent extends FCommand { + + public CmdPermanent() { + super(); + this.aliases.add("permanent"); + + this.requiredArgs.add("faction"); + + this.requirements = new CommandRequirements.Builder(Permission.SET_PERMANENT).build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.argAsFaction(0); + if (faction == null) { + return; + } + + String change; + if (faction.isPermanent()) { + change = TL.COMMAND_PERMANENT_REVOKE.toString(); + faction.setPermanent(false); + } else { + change = TL.COMMAND_PERMANENT_GRANT.toString(); + faction.setPermanent(true); + } + + FactionsPlugin.getInstance().log((context.fPlayer == null ? "A server admin" : context.fPlayer.getName()) + " " + change + " the faction \"" + faction.getTag() + "\"."); + + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + String blame = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true)); + if (fplayer.getFaction() == faction) { + fplayer.msg(TL.COMMAND_PERMANENT_YOURS, blame, change); + } else { + fplayer.msg(TL.COMMAND_PERMANENT_OTHER, blame, change, faction.getTag(fplayer)); + } + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PERMANENT_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java new file mode 100644 index 0000000..c6c4b10 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java @@ -0,0 +1,52 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdPermanentPower extends FCommand { + public CmdPermanentPower() { + super(); + this.aliases.add("permanentpower"); + + this.requiredArgs.add("faction"); + this.requiredArgs.add("power"); + + this.requirements = new CommandRequirements.Builder(Permission.SET_PERMANENTPOWER).build(); + } + + @Override + public void perform(CommandContext context) { + Faction targetFaction = context.argAsFaction(0); + if (targetFaction == null) { + return; + } + + Integer targetPower = context.argAsInt(1); + + targetFaction.setPermanentPower(targetPower); + + String change = TL.COMMAND_PERMANENTPOWER_REVOKE.toString(); + if (targetFaction.hasPermanentPower()) { + change = TL.COMMAND_PERMANENTPOWER_GRANT.toString(); + } + + // Inform sender + context.msg(TL.COMMAND_PERMANENTPOWER_SUCCESS, change, targetFaction.describeTo(context.fPlayer)); + + // Inform all other players + for (FPlayer fplayer : targetFaction.getFPlayersWhereOnline(true)) { + if (fplayer == context.fPlayer) { + continue; + } + String blame = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true)); + fplayer.msg(TL.COMMAND_PERMANENTPOWER_FACTION, blame, change); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PERMANENTPOWER_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPower.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPower.java new file mode 100644 index 0000000..c4e1eb7 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPower.java @@ -0,0 +1,46 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdPower extends FCommand { + + public CmdPower() { + super(); + this.aliases.add("power"); + this.aliases.add("pow"); + + this.optionalArgs.put("player", "you"); + + this.requirements = new CommandRequirements.Builder(Permission.POWER).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0, context.fPlayer); + if (target == null) { + return; + } + + if (target != context.fPlayer && !Permission.POWER_ANY.has(context.sender, true)) { + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostPower(), TL.COMMAND_POWER_TOSHOW, TL.COMMAND_POWER_FORSHOW)) { + return; + } + + double powerBoost = target.getPowerBoost(); + String boost = (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_POWER_BONUS.toString() : TL.COMMAND_POWER_PENALTY.toString()) + powerBoost + ")"; + context.msg(TL.COMMAND_POWER_POWER, target.describeTo(context.fPlayer, true), target.getPowerRounded(), target.getPowerMaxRounded(), boost); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_POWER_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java new file mode 100644 index 0000000..bb5d8de --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java @@ -0,0 +1,81 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdPowerBoost extends FCommand { + + public CmdPowerBoost() { + super(); + this.aliases.add("powerboost"); + + this.requiredArgs.add("p/f/player/faction"); + this.requiredArgs.add("name"); + this.requiredArgs.add("#/reset"); + + this.requirements = new CommandRequirements.Builder(Permission.POWERBOOST).build(); + } + + @Override + public void perform(CommandContext context) { + String type = context.argAsString(0).toLowerCase(); + boolean doPlayer = true; + if (type.equals("f") || type.equals("faction")) { + doPlayer = false; + } else if (!type.equals("p") && !type.equals("player")) { + context.msg(TL.COMMAND_POWERBOOST_HELP_1); + context.msg(TL.COMMAND_POWERBOOST_HELP_2); + return; + } + + Double targetPower = context.argAsDouble(2); + if (targetPower == null) { + if (context.argAsString(2).equalsIgnoreCase("reset")) { + targetPower = 0D; + } else { + context.msg(TL.COMMAND_POWERBOOST_INVALIDNUM); + return; + } + } + + String target; + + if (doPlayer) { + FPlayer targetPlayer = context.argAsBestFPlayerMatch(1); + if (targetPlayer == null) { + return; + } + + if (targetPower != 0) { + targetPower += targetPlayer.getPowerBoost(); + } + targetPlayer.setPowerBoost(targetPower); + target = TL.COMMAND_POWERBOOST_PLAYER.format(targetPlayer.getName()); + } else { + Faction targetFaction = context.argAsFaction(1); + if (targetFaction == null) { + return; + } + + if (targetPower != 0) { + targetPower += targetFaction.getPowerBoost(); + } + targetFaction.setPowerBoost(targetPower); + target = TL.COMMAND_POWERBOOST_FACTION.format(targetFaction.getTag()); + } + + int roundedPower = (int) Math.round(targetPower); + context.msg(TL.COMMAND_POWERBOOST_BOOST, target, roundedPower); + if (context.player != null) { + FactionsPlugin.getInstance().log(TL.COMMAND_POWERBOOST_BOOSTLOG.toString(), context.fPlayer.getName(), target, roundedPower); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_POWERBOOST_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdRally.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdRally.java new file mode 100644 index 0000000..3940dc4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdRally.java @@ -0,0 +1,105 @@ +package com.massivecraft.factions.cmd; + +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.lunarclient.bukkitapi.object.LCWaypoint; +import com.massivecraft.factions.struct.RallyWaypoint; +import com.massivecraft.factions.util.CC; +import com.massivecraft.factions.util.TL; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +public class CmdRally extends FCommand { + + private final Map cooldownMap; + private final Map rallyWaypointMap; + + public CmdRally() { + super(); + this.aliases.add("rally"); + this.cooldownMap = new HashMap<>(); + this.rallyWaypointMap = new HashMap<>(); + } + + private boolean isOnCooldown(Player player) { + if(!this.cooldownMap.containsKey(player)) return false; + return (cooldownMap.get(player) + 7000) > System.currentTimeMillis(); + } + + private String getFormattedCooldown(Player player) { + if(!isOnCooldown(player)) return "error"; + return (((cooldownMap.get(player) + 7000) - System.currentTimeMillis()) / 1000) + "s"; + } + + @Override + public void perform(CommandContext context) { + + CommandSender commandSender = context.sender; + + if(!(commandSender instanceof Player)) return; + Player player = (Player)commandSender; + + if(!context.faction.isNormal()) { + commandSender.sendMessage(CC.translate("&cYou must be in a faction to use /f rally.")); + player.playSound(player.getLocation(), "ANVIL_LAND", 2.0f, 2.0f); + return; + } + + /* + if(!LunarClientAPI.getInstance().isRunningLunarClient(player)) { + player.sendMessage(CC.translate("&cYou must be running lunar client to use f rally!")); + player.playSound(player.getLocation(), "ANVIL_LAND", 2.0f, 2.0f); + return; + } */ + + if(isOnCooldown(player)) { + player.sendMessage(CC.translate("&cYou cannot use /f rally for " + getFormattedCooldown(player))); + player.playSound(player.getLocation(), "ANVIL_LAND", 2.0f, 2.0f); + return; + } + + if(this.rallyWaypointMap.containsKey(player)) { + RallyWaypoint rallyWaypoint = this.rallyWaypointMap.get(player); + for(Player whoSee : rallyWaypoint.getPlayersSentTo()) { + if(!whoSee.isOnline()) continue; + if(!LunarClientAPI.getInstance().isRunningLunarClient(whoSee)) continue; + LunarClientAPI.getInstance().removeWaypoint(whoSee, rallyWaypoint.getLcWaypoint()); + } + } + + this.cooldownMap.put(player, System.currentTimeMillis()); + LCWaypoint waypoint = new LCWaypoint(player.getName() + "'s Rally", player.getLocation(), 20, true); + RallyWaypoint rallyWaypoint = new RallyWaypoint(waypoint, context.faction.getOnlinePlayers()); + this.removeAfterThirtySeconds(rallyWaypoint); + this.rallyWaypointMap.put(player, rallyWaypoint); + for(Player loopPlayer : context.faction.getOnlinePlayers()) { + String message = (TL.RALLY_COORDS_MESSAGE.toString()).replace("%player%", player.getName()) + .replace("%x%", String.valueOf(waypoint.getX())) + .replace("%y%", String.valueOf(waypoint.getY())) + .replace("%z%", String.valueOf(waypoint.getZ())) + .replace("%world%", String.valueOf(waypoint.getWorld())) + ; + loopPlayer.sendMessage(CC.translate(message)); + if(!LunarClientAPI.getInstance().isRunningLunarClient(loopPlayer)) continue; + loopPlayer.playSound(loopPlayer.getLocation(), "CHICKEN_EGG_POP", 2.0f, 2.0f); + System.out.println("send waypoint to " + loopPlayer); + LunarClientAPI.getInstance().sendWaypoint(loopPlayer, waypoint); + } + + } + + private void removeAfterThirtySeconds(RallyWaypoint rallyWaypoint) { + super.plugin.getServer().getScheduler().runTaskLater(super.plugin, () -> { + for(Player playersSentTo : rallyWaypoint.getPlayersSentTo()) { + LunarClientAPI.getInstance().removeWaypoint(playersSentTo, rallyWaypoint.getLcWaypoint()); + } + }, 30 * 20L); + } + + @Override + public TL getUsageTranslation() { + return TL.RALLY_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdReload.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdReload.java new file mode 100644 index 0000000..2c155d4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdReload.java @@ -0,0 +1,31 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdReload extends FCommand { + + public CmdReload() { + super(); + this.aliases.add("reload"); + + this.requirements = new CommandRequirements.Builder(Permission.RELOAD).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + long timeInitStart = System.currentTimeMillis(); + FactionsPlugin.getInstance().getConfigManager().loadConfigs(); + FactionsPlugin.getInstance().reloadConfig(); + FactionsPlugin.getInstance().loadLang(); + long timeReload = (System.currentTimeMillis() - timeInitStart); + + context.msg(TL.COMMAND_RELOAD_TIME, timeReload); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_RELOAD_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSB.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSB.java new file mode 100644 index 0000000..3e70f1a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSB.java @@ -0,0 +1,35 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.scoreboards.FScoreboard; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdSB extends FCommand { + + public CmdSB() { + this.aliases.add("sb"); + this.aliases.add("scoreboard"); + + this.requirements = new CommandRequirements.Builder(Permission.SCOREBOARD) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + boolean toggleTo = !context.fPlayer.showScoreboard(); + FScoreboard board = FScoreboard.get(context.fPlayer); + if (board == null) { + context.player.sendMessage(TL.COMMAND_TOGGLESB_DISABLED.toString()); + } else { + context.player.sendMessage(TL.TOGGLE_SB.toString().replace("{value}", String.valueOf(toggleTo))); + board.setSidebarVisibility(toggleTo); + } + context.fPlayer.setShowScoreboard(toggleTo); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SCOREBOARD_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java new file mode 100644 index 0000000..8f1c95d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java @@ -0,0 +1,32 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdSaveAll extends FCommand { + + public CmdSaveAll() { + super(); + this.aliases.add("saveall"); + this.aliases.add("save"); + + this.requirements = new CommandRequirements.Builder(Permission.SAVE).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + FPlayers.getInstance().forceSave(false); + Factions.getInstance().forceSave(false); + Board.getInstance().forceSave(false); + context.msg(TL.COMMAND_SAVEALL_SUCCESS); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SAVEALL_DESCRIPTION; + } + +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java new file mode 100644 index 0000000..3c9a03e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java @@ -0,0 +1,45 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.SeeChunkUtil; +import com.massivecraft.factions.util.TL; + +public class CmdSeeChunk extends FCommand { + + private final boolean useParticles; + + public CmdSeeChunk() { + super(); + this.aliases.add("seechunk"); + this.aliases.add("sc"); + + this.requirements = new CommandRequirements.Builder(Permission.SEECHUNK) + .playerOnly() + .build(); + + useParticles = FactionsPlugin.getInstance().conf().commands().seeChunk().isParticles(); + } + + @Override + public void perform(CommandContext context) { + if (useParticles) { + boolean toggle = false; + if (context.args.size() == 0) { + toggle = !context.fPlayer.isSeeingChunk(); + } else if (context.args.size() == 1) { + toggle = context.argAsBool(0); + } + context.fPlayer.setSeeingChunk(toggle); + context.msg(TL.COMMAND_SEECHUNK_TOGGLE, toggle ? "enabled" : "disabled"); + } else { + SeeChunkUtil.showPillars(context.player, context.fPlayer, null, false); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SEECHUNK_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSeePaypal.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSeePaypal.java new file mode 100644 index 0000000..7a1a1c0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSeePaypal.java @@ -0,0 +1,37 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdSeePaypal extends FCommand{ + public CmdSeePaypal(){ + super(); + this.aliases.add("seepaypal"); + + this.requiredArgs.add("faction"); + + this.requirements = new CommandRequirements.Builder(Permission.SEEPAYPAL).playerOnly().build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.argAsFaction(0); + + if(faction == null){ + return; + } + + if(faction.getPayPal() == null || faction.getPayPal().isEmpty()){ + context.fPlayer.msg(TL.COMMAND_SEEPAYPAL_ISNTSET, faction.describeTo(context.fPlayer)); + return; + } + + context.fPlayer.msg(TL.COMMAND_SEEPAYPAL_SEE, faction.describeTo(context.fPlayer), faction.getPayPal()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SEEPAYPAL_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java new file mode 100644 index 0000000..43b60d0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java @@ -0,0 +1,45 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdSetDefaultRole extends FCommand { + + public CmdSetDefaultRole() { + super(); + + this.aliases.add("defaultrole"); + this.aliases.add("defaultrank"); + this.aliases.add("default"); + this.aliases.add("def"); + this.requiredArgs.add("role"); + + this.requirements = new CommandRequirements.Builder(Permission.DEFAULTRANK) + .memberOnly() + .withRole(Role.ADMIN) + .build(); + } + + @Override + public void perform(CommandContext context) { + Role target = Role.fromString(context.argAsString(0).toUpperCase()); + if (target == null) { + context.msg(TL.COMMAND_SETDEFAULTROLE_INVALIDROLE, context.argAsString(0)); + return; + } + + if (target == Role.ADMIN) { + context.msg(TL.COMMAND_SETDEFAULTROLE_NOTTHATROLE, context.argAsString(0)); + return; + } + + context.faction.setDefaultRole(target); + context.msg(TL.COMMAND_SETDEFAULTROLE_SUCCESS, target.nicename); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETDEFAULTROLE_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java new file mode 100644 index 0000000..bed69d5 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java @@ -0,0 +1,45 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + +public class CmdSetMaxVaults extends FCommand { + + public CmdSetMaxVaults() { + this.aliases.add("setmaxvaults"); + this.aliases.add("smv"); + + this.requiredArgs.add("faction"); + this.requiredArgs.add("number"); + + this.requirements = new CommandRequirements.Builder(Permission.SETMAXVAULTS) + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + Faction targetFaction = context.argAsFaction(0); + int value = context.argAsInt(1, -1); + if (value < 0) { + context.sender.sendMessage(ChatColor.RED + "Number must be greater than 0."); + return; + } + + if (targetFaction == null) { + context.sender + .sendMessage(ChatColor.RED + "Couldn't find Faction: " + ChatColor.YELLOW + context.argAsString(0)); + return; + } + + targetFaction.setMaxVaults(value); + context.sender.sendMessage(TL.COMMAND_SETMAXVAULTS_SUCCESS.format(targetFaction.getTag(), value)); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETMAXVAULTS_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetPaypal.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetPaypal.java new file mode 100644 index 0000000..f5d0ed4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetPaypal.java @@ -0,0 +1,46 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdSetPaypal extends FCommand{ + + public CmdSetPaypal(){ + super(); + this.aliases.add("setpaypal"); + + this.requiredArgs.add("paypal link"); + + this.requirements = new CommandRequirements.Builder(Permission.SETPAYPAL).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + if(context.fPlayer.getRole() != Role.ADMIN && !context.fPlayer.isAdminBypassing()){ + context.fPlayer.msg(TL.COMMAND_SETPAYPAL_NOTADMIN); + return; + } + + String payPalLink = context.argAsString(0); + + if(payPalLink == null || payPalLink.isEmpty()){ + context.fPlayer.msg(TL.COMMAND_SETPAYPAL_NOTVALID, "null"); + return; + } + + if(!payPalLink.contains("@") || !payPalLink.contains(".")){ + context.fPlayer.msg(TL.COMMAND_SETPAYPAL_NOTVALID, payPalLink); + return; + } + + context.fPlayer.getFaction().setPayPal(payPalLink); + + context.fPlayer.msg(TL.COMMAND_SETPAYPAL_SUCCESS, payPalLink); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETPAYPAL_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetWarp.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetWarp.java new file mode 100644 index 0000000..bcd342c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSetWarp.java @@ -0,0 +1,64 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.LazyLocation; +import com.massivecraft.factions.util.TL; + +public class CmdSetWarp extends FCommand { + + public CmdSetWarp() { + super(); + + this.aliases.add("setwarp"); + this.aliases.add("sw"); + + this.requiredArgs.add("warp"); + this.optionalArgs.put("password", "password"); + + this.requirements = new CommandRequirements.Builder(Permission.SETWARP) + .memberOnly() + .withAction(PermissibleAction.SETWARP) + .build(); + } + + @Override + public void perform(CommandContext context) { + if (!(context.fPlayer.getRelationToLocation() == Relation.MEMBER)) { + context.fPlayer.msg(TL.COMMAND_SETFWARP_NOTCLAIMED); + return; + } + + int maxWarps = context.faction.getMaxWarps(); + if (maxWarps <= context.faction.getWarps().size()) { + context.fPlayer.msg(TL.COMMAND_SETFWARP_LIMIT, maxWarps); + return; + } + + if (!transact(context.fPlayer, context)) { + return; + } + + String warp = context.argAsString(0); + String password = context.argAsString(1); + + LazyLocation loc = new LazyLocation(context.fPlayer.getPlayer().getLocation()); + context.faction.setWarp(warp, loc); + if (password != null) { + context.faction.setWarpPassword(warp, password); + } + context.fPlayer.msg(TL.COMMAND_SETFWARP_SET, warp, password != null ? password : ""); + } + + private boolean transact(FPlayer player, CommandContext context) { + return player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostSetWarp(), TL.COMMAND_SETFWARP_TOSET.toString(), TL.COMMAND_SETFWARP_FORSET.toString()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETFWARP_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java new file mode 100644 index 0000000..967ae7a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java @@ -0,0 +1,56 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdSethome extends FCommand { + + public CmdSethome() { + this.aliases.add("sethome"); + + this.requirements = new CommandRequirements.Builder(Permission.SETHOME) + .memberOnly() + .withAction(PermissibleAction.SETHOME) + .build(); + } + + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().conf().factions().homes().isEnabled()) { + context.msg(TL.COMMAND_SETHOME_DISABLED); + return; + } + + // Can the player set the faction home HERE? + if (!Permission.BYPASS.has(context.player) && + FactionsPlugin.getInstance().conf().factions().homes().isMustBeInClaimedTerritory() && + Board.getInstance().getFactionAt(new FLocation(context.player)) != context.faction) { + context.msg(TL.COMMAND_SETHOME_NOTCLAIMED); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostSethome(), TL.COMMAND_SETHOME_TOSET, TL.COMMAND_SETHOME_FORSET)) { + return; + } + + context.faction.setHome(context.player.getLocation()); + + context.faction.msg(TL.COMMAND_SETHOME_SET, context.fPlayer.describeTo(context.faction, true)); + context.faction.sendMessage(FCmdRoot.getInstance().cmdHome.getUsageTemplate(context)); + /* + if (faction != context.faction) { + context.msg(TL.COMMAND_SETHOME_SETOTHER, faction.getTag(context.fPlayer)); + }*/ + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETHOME_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdShow.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdShow.java new file mode 100644 index 0000000..dd60594 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdShow.java @@ -0,0 +1,276 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.tag.FactionTag; +import com.massivecraft.factions.tag.FancyTag; +import com.massivecraft.factions.tag.Tag; +import com.massivecraft.factions.util.CC; +import com.massivecraft.factions.util.MiscUtil; +import com.massivecraft.factions.util.TL; +import mkremins.fanciful.FancyMessage; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +public class CmdShow extends FCommand { + + List defaults = new ArrayList<>(); + + public CmdShow() { + this.aliases.add("show"); + this.aliases.add("who"); + this.aliases.add("f"); + + + // add defaults to /f show in case config doesnt have it + defaults.add("{header}"); + defaults.add("Description: {description}"); + defaults.add("Joining: {joining} {peaceful}"); + defaults.add("Land / Power / Maxpower: {chunks} / {power} / {maxPower}"); + defaults.add("Raidable: {raidable}"); + defaults.add("Founded: {create-date}"); + defaults.add("This faction is permanent, remaining even with no members."); + defaults.add("Land value: {land-value} {land-refund}"); + defaults.add("Balance: {faction-balance}"); + defaults.add("Bans: {faction-bancount}"); + defaults.add("Allies({allies}/{max-allies}): {allies-list}"); + defaults.add("Online: ({online}/{members}): {online-list}"); + defaults.add("Offline: ({offline}/{members}): {offline-list}"); + defaults.add("Alts: ({alts}): {alt-list}"); + + this.optionalArgs.put("faction tag", "yours"); + + this.requirements = new CommandRequirements.Builder(Permission.SHOW).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.faction; + if (context.argIsSet(0)) { + faction = context.argAsFaction(0); + } + if (faction == null) { + return; + } + + if (context.fPlayer != null && !context.player.hasPermission(Permission.SHOW_BYPASS_EXEMPT.toString()) + && FactionsPlugin.getInstance().conf().commands().show().getExempt().contains(faction.getTag())) { + context.msg(TL.COMMAND_SHOW_EXEMPT); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostShow(), TL.COMMAND_SHOW_TOSHOW, TL.COMMAND_SHOW_FORSHOW)) { + return; + } + + List show = FactionsPlugin.getInstance().conf().commands().show().getFormat(); + if (show == null || show.isEmpty()) { + show = defaults; + } + + if (!faction.isNormal()) { + String tag = faction.getTag(context.fPlayer); + // send header and that's all + String header = show.get(0); + if (FactionTag.HEADER.foundInString(header)) { + context.msg(plugin.txt().titleize(tag)); + } else { + String message = header.replace(FactionTag.FACTION.getTag(), tag); + message = Tag.parsePlain(faction, context.fPlayer, message); + context.msg(plugin.txt().parse(message)); + } + return; // we only show header for non-normal factions + } + + List messageList = new ArrayList<>(); + for (String raw : show) { + if(context.fPlayer != null && faction != context.fPlayer.getFaction() && !Permission.CLAIM_SEEALL.has(context.sender)){ + raw = raw.replace("{chunks}", "???"); + } + + String parsed = Tag.parsePlain(faction, context.fPlayer, raw); // use relations + if (parsed == null) { + continue; // Due to minimal f show. + } + + if (context.fPlayer != null) { + parsed = Tag.parsePlaceholders(context.fPlayer.getPlayer(), parsed); + } + + if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) { + if (parsed.contains("{ig}")) { + // replaces all variables with no home TL + parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString(); + } + parsed = parsed.replace("%", ""); // Just in case it got in there before we disallowed it. + messageList.add(parsed); + } + } + //messageList.add(CC.translate("&6 * &eKoth Wins: &f" + CosmicKOTHAPI.getFactionKothWins(faction))); + //messageList.add(CC.translate("&6 * &eFtop: &f#" + FactionsTopAPI.getFactionTop(faction))); + + messageList.add(CC.translate("&8&m---------------------------------")); + + if (context.fPlayer != null && this.groupPresent()) { + new GroupGetter(messageList, context.fPlayer, faction).runTaskAsynchronously(FactionsPlugin.getInstance()); + } else { + this.sendMessages(messageList, context.sender, faction, context.fPlayer); + } + } + + private void sendMessages(List messageList, CommandSender recipient, Faction faction, FPlayer player) { + this.sendMessages(messageList, recipient, faction, player, null); + } + + private void sendMessages(List messageList, CommandSender recipient, Faction faction, FPlayer player, Map groupMap) { + FancyTag tag; + for (String parsed : messageList) { + if ((tag = FancyTag.getMatch(parsed)) != null) { + if (player != null) { + List fancy = FancyTag.parse(parsed, faction, player, groupMap); + if (fancy != null) { + for (FancyMessage fancyMessage : fancy) { + fancyMessage.send(recipient); + } + } + } else { + StringBuilder builder = new StringBuilder(); + builder.append(parsed.replace(tag.getTag(), "")); + switch (tag) { + case ALT_LIST: + this.onAltMessage(builder, recipient, faction); + break; + case ONLINE_LIST: + this.onOffLineMessage(builder, recipient, faction, true); + break; + case OFFLINE_LIST: + this.onOffLineMessage(builder, recipient, faction, false); + break; + case ALLIES_LIST: + this.relationMessage(builder, recipient, faction, Relation.ALLY); + break; + case ENEMIES_LIST: + this.relationMessage(builder, recipient, faction, Relation.ENEMY); + break; + case TRUCES_LIST: + this.relationMessage(builder, recipient, faction, Relation.TRUCE); + break; + default: + // NO + } + } + } else { + recipient.sendMessage(FactionsPlugin.getInstance().txt().parse(parsed)); + } + } + } + + private void onOffLineMessage(StringBuilder builder, CommandSender recipient, Faction faction, boolean online) { + boolean first = true; + for (FPlayer p : MiscUtil.rankOrder(faction.getFPlayersWhereOnline(online))) { + String name = p.getNameAndTitle(); + builder.append(first ? name : ", " + name); + first = false; + } + recipient.sendMessage(FactionsPlugin.getInstance().txt().parse(builder.toString())); + } + + private void onAltMessage(StringBuilder builder, CommandSender recipient, Faction faction) { + boolean first = true; + for (FPlayer p : MiscUtil.rankOrder(faction.getFPlayersWhereRole(Role.ALT))) { + String name = p.getNameAndTitle(); + builder.append(first ? name : ", " + name); + first = false; + } + recipient.sendMessage(FactionsPlugin.getInstance().txt().parse(builder.toString())); + } + + private void relationMessage(StringBuilder builder, CommandSender recipient, Faction faction, Relation relation) { + boolean first = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction != faction && otherFaction.getRelationTo(faction) == relation) { + String s = otherFaction.getTag(); + builder.append(first ? s : ", " + s); + first = false; + } + } + recipient.sendMessage(FactionsPlugin.getInstance().txt().parse(builder.toString())); + } + + private boolean groupPresent() { + for (String line : FactionsPlugin.getInstance().conf().commands().toolTips().getPlayer()) { + if (line.contains("{group}")) { + return true; + } + } + return false; + } + + private class GroupGetter extends BukkitRunnable { + private final List messageList; + private final FPlayer sender; + private final Faction faction; + private final Set players; + + private GroupGetter(List messageList, FPlayer sender, Faction faction) { + this.messageList = messageList; + this.sender = sender; + this.faction = faction; + this.players = faction.getFPlayers().stream().map(fp -> Bukkit.getOfflinePlayer(UUID.fromString(fp.getId()))).collect(Collectors.toSet()); + } + + @Override + public void run() { + Map map = new HashMap<>(); + for (OfflinePlayer player : this.players) { + map.put(player.getUniqueId(), FactionsPlugin.getInstance().getPrimaryGroup(player)); + } + new Sender(this.messageList, this.sender, this.faction, map).runTask(FactionsPlugin.getInstance()); + } + } + + private class Sender extends BukkitRunnable { + private final List messageList; + private final FPlayer sender; + private final Faction faction; + private final Map map; + + private Sender(List messageList, FPlayer sender, Faction faction, Map map) { + this.messageList = messageList; + this.sender = sender; + this.faction = faction; + this.map = map; + } + + @Override + public void run() { + Player player = Bukkit.getPlayerExact(sender.getName()); + if (player != null) { + CmdShow.this.sendMessages(messageList, player, faction, sender, map); + } + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SHOW_COMMANDDESCRIPTION; + } + +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java new file mode 100644 index 0000000..3cf9eda --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java @@ -0,0 +1,40 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import mkremins.fanciful.FancyMessage; +import org.bukkit.ChatColor; + +public class CmdShowInvites extends FCommand { + + public CmdShowInvites() { + super(); + this.aliases.add("showinvites"); + + this.requirements = new CommandRequirements.Builder(Permission.SHOW_INVITES) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + FancyMessage msg = new FancyMessage(TL.COMMAND_SHOWINVITES_PENDING.toString()).color(ChatColor.GOLD); + for (String id : context.faction.getInvites()) { + FPlayer fp = FPlayers.getInstance().getById(id); + String name = fp != null ? fp.getName() : id; + msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_SHOWINVITES_CLICKTOREVOKE.format(name)).command("/" + FactionsPlugin.getInstance().conf().getCommandBase().get(0) + " deinvite " + name); + } + + context.sendFancyMessage(msg); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SHOWINVITES_DESCRIPTION; + } + + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSotw.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSotw.java new file mode 100644 index 0000000..c2aa160 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdSotw.java @@ -0,0 +1,43 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + +public class CmdSotw extends FCommand { + public CmdSotw() { + super(); + + this.aliases.add("sotw"); + + this.requirements = new CommandRequirements.Builder(Permission.SOTW).build(); + } + + @Override + public void perform(CommandContext context) { + boolean on = !FactionsPlugin.getInstance().isSOTW(); + + FactionsPlugin.getInstance().setSOTW(on); + + if (on) { + context.sender.sendMessage(ChatColor.GREEN + "Turned on SOTW."); + + for (FPlayer fPlayer : FPlayers.getInstance().getOnlinePlayers()) { + if (Permission.SOTW.has(fPlayer.getPlayer())) continue; + fPlayer.msg(TL.PLAYER_SOTW_NOFLY); + //fPlayer.setFlying(false, false); + //fPlayer.setAutoFlying(false); + } + } else { + context.sender.sendMessage(ChatColor.RED + "Turned off SOTW"); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SOTW_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java new file mode 100644 index 0000000..d2d218c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java @@ -0,0 +1,47 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.landraidcontrol.PowerControl; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.ChatColor; + +import java.util.ArrayList; + +public class CmdStatus extends FCommand { + + public CmdStatus() { + super(); + this.aliases.add("status"); + this.aliases.add("s"); + + this.requirements = new CommandRequirements.Builder(Permission.STATUS) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + ArrayList ret = new ArrayList<>(); + for (FPlayer fp : context.faction.getFPlayers()) { + String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; + String last = fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); + String power = ""; + if (FactionsPlugin.getInstance().getLandRaidControl() instanceof PowerControl) { + power = ChatColor.YELLOW + String.valueOf(fp.getPowerRounded()) + " / " + fp.getPowerMaxRounded() + ChatColor.RESET; + } else { + power = "n/a"; + } + ret.add(String.format(TL.COMMAND_STATUS_FORMAT.toString(), ChatColor.GOLD + fp.getRole().getPrefix() + fp.getName() + ChatColor.RESET, power, last).trim()); + } + context.fPlayer.sendMessage(ret); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STATUS_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java new file mode 100644 index 0000000..6614a6d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java @@ -0,0 +1,32 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + +public class CmdStealth extends FCommand { + + public CmdStealth() { + super(); + this.aliases.add("stealth"); + + this.requirements = new CommandRequirements.Builder(Permission.STEALTH) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer fPlayer = context.fPlayer; + + fPlayer.setStealth(!fPlayer.isStealth()); + fPlayer.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&a!&8) &7Stealth mode has been " + (fPlayer.isStealth() ? "&aenabled" : "&cdisabled"))); + } + + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STEALTH_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java new file mode 100644 index 0000000..cb646a7 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java @@ -0,0 +1,120 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerTeleportEvent; +import com.massivecraft.factions.integration.Essentials; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.SpiralTask; +import com.massivecraft.factions.util.TL; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +public class CmdStuck extends FCommand { + + public CmdStuck() { + super(); + + this.aliases.add("stuck"); + this.aliases.add("halp!"); // halp! c: + + this.requirements = new CommandRequirements.Builder(Permission.STUCK).build(); + } + + @Override + public void perform(final CommandContext context) { + final Player player = context.fPlayer.getPlayer(); + final Location sentAt = player.getLocation(); + final FLocation chunk = context.fPlayer.getLastStoodAt(); + // TODO handle delay 0 + final long delay = FactionsPlugin.getInstance().conf().commands().stuck().getDelay(); + final int radius = FactionsPlugin.getInstance().conf().commands().stuck().getRadius(); + + if (FactionsPlugin.getInstance().getStuckMap().containsKey(player.getUniqueId())) { + long wait = FactionsPlugin.getInstance().getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); + String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); + context.msg(TL.COMMAND_STUCK_EXISTS, time); + } else { + + FPlayerTeleportEvent tpEvent = new FPlayerTeleportEvent(context.fPlayer, null, FPlayerTeleportEvent.PlayerTeleportReason.STUCK); + Bukkit.getServer().getPluginManager().callEvent(tpEvent); + if (tpEvent.isCancelled()) { + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostStuck(), TL.COMMAND_STUCK_TOSTUCK.format(context.fPlayer.getName()), TL.COMMAND_STUCK_FORSTUCK.format(context.fPlayer.getName()))) { + return; + } + + final int id = new BukkitRunnable() { + + @Override + public void run() { + if (!FactionsPlugin.getInstance().getStuckMap().containsKey(player.getUniqueId())) { + return; + } + + // check for world difference or radius exceeding + final World world = chunk.getWorld(); + if (world.getUID() != player.getWorld().getUID() || sentAt.distance(player.getLocation()) > radius) { + context.msg(TL.COMMAND_STUCK_OUTSIDE.format(radius)); + FactionsPlugin.getInstance().getTimers().remove(player.getUniqueId()); + FactionsPlugin.getInstance().getStuckMap().remove(player.getUniqueId()); + return; + } + + final Board board = Board.getInstance(); + // spiral task to find nearest wilderness chunk + new SpiralTask(new FLocation(context.player), radius * 2) { + + final int buffer = FactionsPlugin.getInstance().conf().worldBorder().getBuffer(); + + @Override + public boolean work() { + FLocation chunk = currentFLocation(); + if (chunk.isOutsideWorldBorder(buffer)) { + return true; + } + + Faction faction = board.getFactionAt(chunk); + if (faction.isWilderness()) { + int cx = FLocation.chunkToBlock((int) chunk.getX()); + int cz = FLocation.chunkToBlock((int) chunk.getZ()); + int y = world.getHighestBlockYAt(cx, cz); + Location tp = new Location(world, cx, y, cz); + context.msg(TL.COMMAND_STUCK_TELEPORT, tp.getBlockX(), tp.getBlockY(), tp.getBlockZ()); + FactionsPlugin.getInstance().getTimers().remove(player.getUniqueId()); + FactionsPlugin.getInstance().getStuckMap().remove(player.getUniqueId()); + if (!Essentials.handleTeleport(player, tp)) { + FactionsPlugin.getInstance().teleport(player, tp); + FactionsPlugin.getInstance().debug("/f stuck used regular teleport, not essentials!"); + } + this.stop(); + return false; + } + return true; + } + }; + } + }.runTaskLater(FactionsPlugin.getInstance(), delay * 20).getTaskId(); + + FactionsPlugin.getInstance().getTimers().put(player.getUniqueId(), System.currentTimeMillis() + (delay * 1000)); + long wait = FactionsPlugin.getInstance().getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); + String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); + context.msg(TL.COMMAND_STUCK_START, time); + FactionsPlugin.getInstance().getStuckMap().put(player.getUniqueId(), id); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STUCK_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTNT.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTNT.java new file mode 100644 index 0000000..4b75ff3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTNT.java @@ -0,0 +1,34 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.cmd.tnt.*; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdTNT extends FCommand { + private final CmdTNTInfo infoCmd; + + public CmdTNT() { + super(); + this.aliases.add("tnt"); + + this.addSubCommand(this.infoCmd = new CmdTNTInfo()); + this.addSubCommand(new CmdTNTFill()); + this.addSubCommand(new CmdTNTDeposit()); + this.addSubCommand(new CmdTNTWithdraw()); + this.addSubCommand(new CmdTNTSiphon()); + this.addSubCommand(new CmdTNTAdminSet()); + + this.requirements = new CommandRequirements.Builder(Permission.TNT_INFO).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + FCmdRoot.getInstance().cmdAutoHelp.execute(context); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNT_INFO_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTag.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTag.java new file mode 100644 index 0000000..97fef18 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTag.java @@ -0,0 +1,90 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FactionRenameEvent; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.scoreboards.FTeamWrapper; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.MiscUtil; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +import java.util.ArrayList; + +public class CmdTag extends FCommand { + + public CmdTag() { + this.aliases.add("tag"); + this.aliases.add("rename"); + + this.requiredArgs.add("faction tag"); + + this.requirements = new CommandRequirements.Builder(Permission.TAG) + .memberOnly() + .withRole(Role.MODERATOR) + .build(); + } + + @Override + public void perform(CommandContext context) { + String tag = context.argAsString(0); + + // TODO does not first shouldCancel cover selfcase? + if (Factions.getInstance().isTagTaken(tag) && !MiscUtil.getComparisonString(tag).equals(context.faction.getComparisonTag())) { + context.msg(TL.COMMAND_TAG_TAKEN); + return; + } + + ArrayList errors = MiscUtil.validateTag(tag); + if (errors.size() > 0) { + context.sendMessage(errors); + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!context.canAffordCommand(FactionsPlugin.getInstance().conf().economy().getCostTag(), TL.COMMAND_TAG_TOCHANGE.toString())) { + return; + } + + // trigger the faction rename event (cancellable) + FactionRenameEvent renameEvent = new FactionRenameEvent(context.fPlayer, tag); + Bukkit.getServer().getPluginManager().callEvent(renameEvent); + if (renameEvent.isCancelled()) { + return; + } + + // then make 'em pay (if applicable) + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostTag(), TL.COMMAND_TAG_TOCHANGE, TL.COMMAND_TAG_FORCHANGE)) { + return; + } + + String oldtag = context.faction.getTag(); + context.faction.setTag(tag); + + // Inform + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fplayer.getFactionId().equals(context.faction.getId())) { + fplayer.msg(TL.COMMAND_TAG_FACTION, context.fPlayer.describeTo(context.faction, true), context.faction.getTag(context.faction)); + continue; + } + + // Broadcast the tag change (if applicable) + if (FactionsPlugin.getInstance().conf().factions().chat().isBroadcastTagChanges()) { + Faction faction = fplayer.getFaction(); + fplayer.msg(TL.COMMAND_TAG_CHANGED, context.fPlayer.getColorTo(faction) + oldtag, context.faction.getTag(faction)); + } + } + + FTeamWrapper.updatePrefixes(context.faction); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TAG_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java new file mode 100644 index 0000000..1e488cb --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java @@ -0,0 +1,56 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.TextUtil; + +public class CmdTitle extends FCommand { + + public CmdTitle() { + this.aliases.add("title"); + + this.requiredArgs.add("player"); + this.optionalArgs.put("title", "title"); + + this.requirements = new CommandRequirements.Builder(Permission.TITLE) + .memberOnly() + .withRole(Role.MODERATOR) + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer you = context.argAsBestFPlayerMatch(0); + if (you == null) { + return; + } + + context.args.remove(0); + String title = TextUtil.implode(context.args, " "); + + title = title.replaceAll(",", ""); + + if (!context.canIAdministerYou(context.fPlayer, you)) { + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostTitle(), TL.COMMAND_TITLE_TOCHANGE, TL.COMMAND_TITLE_FORCHANGE)) { + return; + } + + you.setTitle(context.sender, title); + + // Inform + context.faction.msg(TL.COMMAND_TITLE_CHANGED, context.fPlayer.describeTo(context.faction, true), you.describeTo(context.faction, true)); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TITLE_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java new file mode 100644 index 0000000..e53328a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java @@ -0,0 +1,38 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdToggleAllianceChat extends FCommand { + + public CmdToggleAllianceChat() { + super(); + this.aliases.add("tac"); + this.aliases.add("togglealliancechat"); + this.aliases.add("ac"); + + this.requirements = new CommandRequirements.Builder(Permission.TOGGLE_ALLIANCE_CHAT) + .memberOnly() + .noDisableOnLock() + .build(); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TOGGLEALLIANCECHAT_DESCRIPTION; + } + + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().conf().factions().chat().isFactionOnlyChat()) { + context.msg(TL.COMMAND_CHAT_DISABLED.toString()); + return; + } + + boolean ignoring = context.fPlayer.isIgnoreAllianceChat(); + + context.msg(ignoring ? TL.COMMAND_TOGGLEALLIANCECHAT_UNIGNORE : TL.COMMAND_TOGGLEALLIANCECHAT_IGNORE); + context.fPlayer.setIgnoreAllianceChat(!ignoring); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTop.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTop.java new file mode 100644 index 0000000..757ad70 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTop.java @@ -0,0 +1,172 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.landraidcontrol.PowerControl; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.entity.Player; + +import java.util.ArrayList; + +public class CmdTop extends FCommand { + + public CmdTop() { + super(); + this.aliases.add("top"); + this.aliases.add("t"); + + this.requiredArgs.add("criteria"); + this.optionalArgs.put("page", "1"); + + this.requirements = new CommandRequirements.Builder(Permission.TOP).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + // Can sort by: money, members, online, allies, enemies, power, land. + // Get all Factions and remove non player ones. + ArrayList factionList = Factions.getInstance().getAllFactions(); + factionList.remove(Factions.getInstance().getWilderness()); + factionList.remove(Factions.getInstance().getSafeZone()); + factionList.remove(Factions.getInstance().getWarZone()); + + String criteria = context.argAsString(0); + + // TODO: Better way to sort? + if (criteria.equalsIgnoreCase("members")) { + factionList.sort((f1, f2) -> { + int f1Size = f1.getFPlayers().size(); + int f2Size = f2.getFPlayers().size(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); + } else if (criteria.equalsIgnoreCase("start")) { + factionList.sort((f1, f2) -> { + long f1start = f1.getFoundedDate(); + long f2start = f2.getFoundedDate(); + // flip signs because a smaller date is farther in the past + if (f1start > f2start) { + return 1; + } else if (f1start < f2start) { + return -1; + } + return 0; + }); + } else if (FactionsPlugin.getInstance().getLandRaidControl() instanceof PowerControl && criteria.equalsIgnoreCase("power")) { + factionList.sort((f1, f2) -> { + int f1Size = f1.getPowerRounded(); + int f2Size = f2.getPowerRounded(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); + } else if (criteria.equalsIgnoreCase("land")) { + factionList.sort((f1, f2) -> { + int f1Size = f1.getLandRounded(); + int f2Size = f2.getLandRounded(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); + } else if (criteria.equalsIgnoreCase("online")) { + factionList.sort((f1, f2) -> { + int f1Size = f1.getFPlayersWhereOnline(true).size(); + int f2Size = f2.getFPlayersWhereOnline(true).size(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); + } else if (criteria.equalsIgnoreCase("money") || criteria.equalsIgnoreCase("balance") || criteria.equalsIgnoreCase("bal")) { + factionList.sort((f1, f2) -> { + double f1Size = Econ.getBalance(f1); + // Lets get the balance of /all/ the players in the Faction. + for (FPlayer fp : f1.getFPlayers()) { + f1Size = f1Size + Econ.getBalance(fp); + } + double f2Size = Econ.getBalance(f2); + for (FPlayer fp : f2.getFPlayers()) { + f2Size = f2Size + Econ.getBalance(fp); + } + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); + } else { + context.msg(TL.COMMAND_TOP_INVALID, criteria); + return; + } + + ArrayList lines = new ArrayList<>(); + + final int pageheight = 9; + int pagenumber = context.argAsInt(1, 1); + int pagecount = (factionList.size() / pageheight) + 1; + if (pagenumber > pagecount) { + pagenumber = pagecount; + } else if (pagenumber < 1) { + pagenumber = 1; + } + int start = (pagenumber - 1) * pageheight; + int end = start + pageheight; + if (end > factionList.size()) { + end = factionList.size(); + } + + lines.add(TL.COMMAND_TOP_TOP.format(criteria.toUpperCase(), pagenumber, pagecount)); + + int rank = 1; + for (Faction faction : factionList.subList(start, end)) { + // Get the relation color if player is executing this. + String fac = context.sender instanceof Player ? faction.getRelationTo(context.fPlayer).getColor() + faction.getTag() : faction.getTag(); + lines.add(TL.COMMAND_TOP_LINE.format(rank, fac, getValue(faction, criteria))); + rank++; + } + + context.sendMessage(lines); + } + + private String getValue(Faction faction, String criteria) { + if (criteria.equalsIgnoreCase("online")) { + return String.valueOf(faction.getFPlayersWhereOnline(true).size()); + } else if (criteria.equalsIgnoreCase("start")) { + return TL.sdf.format(faction.getFoundedDate()); + } else if (criteria.equalsIgnoreCase("members")) { + return String.valueOf(faction.getFPlayers().size()); + } else if (criteria.equalsIgnoreCase("land")) { + return String.valueOf(faction.getLandRounded()); + } else if (FactionsPlugin.getInstance().getLandRaidControl() instanceof PowerControl && criteria.equalsIgnoreCase("power")) { + return String.valueOf(faction.getPowerRounded()); + } else { // Last one is balance, and it has 3 different things it could be. + double balance = Econ.getBalance(faction); + for (FPlayer fp : faction.getFPlayers()) { + balance = balance + Econ.getBalance(fp); + } + return String.valueOf(balance); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TOP_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTrail.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTrail.java new file mode 100644 index 0000000..4a0eee0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdTrail.java @@ -0,0 +1,55 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdTrail extends FCommand { + + public CmdTrail() { + super(); + this.aliases.add("trail"); + this.aliases.add("trails"); + + this.optionalArgs.put("on/off/effect", "flip"); + this.optionalArgs.put("particle", "particle"); + + this.requirements = new CommandRequirements.Builder(Permission.FLY_TRAILS).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + // Let's flip it + if (!context.argIsSet(0)) { + context.fPlayer.setFlyTrailsState(!context.fPlayer.getFlyTrailsState()); + } else { + // They are setting a particle type + if (context.argAsString(0).equalsIgnoreCase("effect")) { + if (context.argIsSet(1)) { + String effectName = context.argAsString(1); + Object particleEffect = plugin.getParticleProvider().effectFromString(effectName); + if (particleEffect == null) { + context.fPlayer.msg(TL.COMMAND_FLYTRAILS_PARTICLE_INVALID); + return; + } + + if (context.player.hasPermission(Permission.FLY_TRAILS.node + "." + effectName)) { + context.fPlayer.setFlyTrailsEffect(effectName); + } else { + context.fPlayer.msg(TL.COMMAND_FLYTRAILS_PARTICLE_PERMS, effectName); + } + } else { + context.msg(getUsageTranslation()); + } + } else { + boolean state = context.argAsBool(0); + context.fPlayer.setFlyTrailsState(state); + } + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_FLY_DESCRIPTION; + } + +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java new file mode 100644 index 0000000..7114b55 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java @@ -0,0 +1,46 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdUnban extends FCommand { + + public CmdUnban() { + super(); + this.aliases.add("unban"); + + this.requiredArgs.add("target"); + + this.requirements = new CommandRequirements.Builder(Permission.BAN) + .memberOnly() + .withAction(PermissibleAction.BAN) + .withRole(Role.MODERATOR) + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsFPlayer(0); + if (target == null) { + return; // the above method sends a message if fails to find someone. + } + + if (!context.faction.isBanned(target)) { + context.msg(TL.COMMAND_UNBAN_NOTBANNED, target.getName()); + return; + } + + context.faction.unban(target); + + context.faction.msg(TL.COMMAND_UNBAN_UNBANNED, context.fPlayer.getName(), target.getName()); + target.msg(TL.COMMAND_UNBAN_TARGET, context.faction.getTag(target)); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UNBAN_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdUpgrade.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdUpgrade.java new file mode 100644 index 0000000..917eaaf --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdUpgrade.java @@ -0,0 +1,28 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.gui.UpgradeGUI; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdUpgrade extends FCommand{ + + public CmdUpgrade() { + super(); + this.aliases.add("upgrade"); + + this.requirements = new CommandRequirements.Builder(Permission.UPGRADE).memberOnly().playerOnly().build(); + } + + @Override + public void perform(CommandContext context) { + UpgradeGUI upgradeGUI = new UpgradeGUI(context.fPlayer); + + upgradeGUI.open(); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UPGRADE_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdVault.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdVault.java new file mode 100644 index 0000000..1f8cf80 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdVault.java @@ -0,0 +1,39 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; + +public class CmdVault extends FCommand { + + public CmdVault() { + this.aliases.add("vault"); + this.aliases.add("chest"); + + this.requirements = new CommandRequirements.Builder(Permission.VAULT) + .memberOnly() + .noDisableOnLock() + .build(); + } + + @Override + public void perform(CommandContext context) { + /* + /f vault + */ + + Player player = context.player; + + if(context.faction.isWilderness())return; + + Inventory inventory = context.faction.getChest(); + + player.openInventory(inventory); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_VAULT_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java new file mode 100644 index 0000000..a516f77 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java @@ -0,0 +1,26 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + + +public class CmdVersion extends FCommand { + + public CmdVersion() { + this.aliases.add("version"); + this.aliases.add("ver"); + + this.requirements = new CommandRequirements.Builder(Permission.VERSION).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + context.msg(TL.COMMAND_VERSION_VERSION, FactionsPlugin.getInstance().getDescription().getFullName()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_VERSION_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdWarp.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdWarp.java new file mode 100644 index 0000000..49939c3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdWarp.java @@ -0,0 +1,90 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerTeleportEvent; +import com.massivecraft.factions.gui.WarpGUI; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.WarmUpUtil; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.UUID; + +public class CmdWarp extends FCommand { + + public CmdWarp() { + super(); + this.aliases.add("warp"); + this.aliases.add("warps"); + this.optionalArgs.put("warp", "warp"); + this.optionalArgs.put("password", "password"); + + this.requirements = new CommandRequirements.Builder(Permission.WARP) + .memberOnly() + .withAction(PermissibleAction.WARP) + .build(); + } + + @Override + public void perform(CommandContext context) { + // TODO: check if in combat. + + if (!context.faction.hasAccess(context.fPlayer, PermissibleAction.WARP)) { + context.msg(TL.COMMAND_FWARP_NOACCESS, context.faction.getTag(context.fPlayer)); + return; + } + + if (context.args.size() == 0) { + WarpGUI ui = new WarpGUI(context.fPlayer, context.faction); + ui.open(); + } else if (context.args.size() > 2) { + context.msg(TL.COMMAND_FWARP_COMMANDFORMAT); + } else { + final String warpName = context.argAsString(0); + final String passwordAttempt = context.argAsString(1); + + if (context.faction.isWarp(context.argAsString(0))) { + // Check if requires password and if so, check if valid. CASE SENSITIVE + if (!context.fPlayer.isAdminBypassing() && context.faction.hasWarpPassword(warpName) && !context.faction.isWarpPassword(warpName, passwordAttempt)) { + context.fPlayer.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); + return; + } + FPlayerTeleportEvent tpEvent = new FPlayerTeleportEvent(context.fPlayer, context.fPlayer.getFaction().getWarp(warpName).getLocation(), FPlayerTeleportEvent.PlayerTeleportReason.WARP); + Bukkit.getServer().getPluginManager().callEvent(tpEvent); + if (tpEvent.isCancelled()) { + return; + } + // Check transaction AFTER password check. + if (!transact(context.fPlayer, context)) { + return; + } + final FPlayer fPlayer = context.fPlayer; + final UUID uuid = context.fPlayer.getPlayer().getUniqueId(); + context.doWarmUp(WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warpName, () -> { + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + FactionsPlugin.getInstance().teleport(player, fPlayer.getFaction().getWarp(warpName).getLocation()).thenAccept(success -> { + if (success) { + fPlayer.msg(TL.COMMAND_FWARP_WARPED, warpName); + } + }); + } + }, this.plugin.conf().commands().warp().getDelay()); + } else { + context.fPlayer.msg(TL.COMMAND_FWARP_INVALID_WARP, warpName); + } + } + } + + private boolean transact(FPlayer player, CommandContext context) { + return player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostWarp(), TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_FWARP_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CmdWarpOther.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdWarpOther.java new file mode 100644 index 0000000..18ca6ac --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CmdWarpOther.java @@ -0,0 +1,97 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerTeleportEvent; +import com.massivecraft.factions.gui.WarpGUI; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.WarmUpUtil; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.UUID; + +public class CmdWarpOther extends FCommand { + + public CmdWarpOther() { + super(); + this.aliases.add("warpother"); + this.requiredArgs.add("faction"); + this.optionalArgs.put("warp", "warp"); + this.optionalArgs.put("password", "password"); + + this.requirements = new CommandRequirements.Builder(Permission.WARP) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + // TODO: check if in combat. + if (context.args.size() < 1) { + context.msg(TL.COMMAND_WARPOTHER_COMMANDFORMAT); + return; + } + Faction faction = context.argAsFaction(0); + if (faction == null) { + context.msg(TL.GENERIC_NOFACTIONMATCH, context.argAsString(0)); + return; + } + + if (!context.fPlayer.isAdminBypassing() && !faction.hasAccess(context.fPlayer, PermissibleAction.WARP)) { + context.msg(TL.COMMAND_FWARP_NOACCESS, faction.getTag(context.fPlayer)); + return; + } + + if (context.args.size() == 1) { + WarpGUI ui = new WarpGUI(context.fPlayer, faction); + ui.open(); + } else { + final String warpName = context.argAsString(1); + final String passwordAttempt = context.argAsString(2); + + if (faction.isWarp(warpName)) { + // Check if requires password and if so, check if valid. CASE SENSITIVE + if (!context.fPlayer.isAdminBypassing() && faction.hasWarpPassword(warpName) && !faction.isWarpPassword(warpName, passwordAttempt)) { + context.fPlayer.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); + return; + } + FPlayerTeleportEvent tpEvent = new FPlayerTeleportEvent(context.fPlayer, faction.getWarp(warpName).getLocation(), FPlayerTeleportEvent.PlayerTeleportReason.WARP); + Bukkit.getServer().getPluginManager().callEvent(tpEvent); + if (tpEvent.isCancelled()) { + return; + } + // Check transaction AFTER password check. + if (!transact(context.fPlayer, context)) { + return; + } + final FPlayer fPlayer = context.fPlayer; + final UUID uuid = context.fPlayer.getPlayer().getUniqueId(); + context.doWarmUp(WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warpName, () -> { + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + FactionsPlugin.getInstance().teleport(player, faction.getWarp(warpName).getLocation()).thenAccept(success -> { + if (success) { + fPlayer.msg(TL.COMMAND_FWARP_WARPED, warpName); + } + }); + } + }, this.plugin.conf().commands().warp().getDelay()); + } else { + context.fPlayer.msg(TL.COMMAND_FWARP_INVALID_WARP, warpName); + } + } + } + + private boolean transact(FPlayer player, CommandContext context) { + return player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostWarp(), TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_FWARP_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CommandContext.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CommandContext.java new file mode 100644 index 0000000..c9404ea --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CommandContext.java @@ -0,0 +1,418 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.WarmUpUtil; +import mkremins.fanciful.FancyMessage; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +/* + Object that contains information about a command being executed, + args, player, faction + */ +public class CommandContext { + + public CommandSender sender; + + public Player player; + public FPlayer fPlayer; + public Faction faction; + + public List args; + public String alias; + + public List commandChain = new ArrayList<>(); // The command chain used to execute this command + + public CommandContext(CommandSender sender, List args, String alias) { + this.sender = sender; + this.args = args; + this.alias = alias; + + if (sender instanceof Player) { + this.player = (Player) sender; + this.fPlayer = FPlayers.getInstance().getByPlayer(player); + this.faction = fPlayer.getFaction(); + } + } + + // -------------------------------------------- // + // Message Sending Helpers + // -------------------------------------------- // + + public void msg(String str, Object... args) { + sender.sendMessage(FactionsPlugin.getInstance().txt().parse(str, args)); + } + + public void msg(TL translation, Object... args) { + sender.sendMessage(FactionsPlugin.getInstance().txt().parse(translation.toString(), args)); + } + + public void sendMessage(String msg) { + sender.sendMessage(msg); + } + + public void sendMessage(List msgs) { + for (String msg : msgs) { + this.sendMessage(msg); + } + } + + public void sendFancyMessage(FancyMessage message) { + message.send(sender); + } + + public void sendFancyMessage(List messages) { + for (FancyMessage m : messages) { + sendFancyMessage(m); + } + } + + // TODO: Clean this UP + // -------------------------------------------- // + // Argument Readers + // -------------------------------------------- // + + // Is set? ====================== + public boolean argIsSet(int idx) { + return args.size() >= idx + 1; + } + + // STRING ====================== + public String argAsString(int idx, String def) { + if (args.size() < idx + 1) { + return def; + } + return args.get(idx); + } + + public String argAsString(int idx) { + return argAsString(idx, null); + } + + // INT ====================== + public Integer strAsInt(String str, Integer def) { + if (str == null) { + return def; + } + try { + return Integer.parseInt(str); + } catch (Exception e) { + return def; + } + } + + public Integer argAsInt(int idx, Integer def) { + return strAsInt(argAsString(idx), def); + } + + public Integer argAsInt(int idx) { + return argAsInt(idx, null); + } + + // Double ====================== + public Double strAsDouble(String str, Double def) { + if (str == null) { + return def; + } + try { + return Double.parseDouble(str); + } catch (Exception e) { + return def; + } + } + + public Double argAsDouble(int idx, Double def) { + return strAsDouble(argAsString(idx), def); + } + + public Double argAsDouble(int idx) { + return argAsDouble(idx, null); + } + + // TODO: Go through the str conversion for the other arg-readers as well. + // Boolean ====================== + public Boolean strAsBool(String str) { + str = str.toLowerCase(); + return str.startsWith("y") || str.startsWith("t") || str.startsWith("on") || str.startsWith("+") || str.startsWith("1"); + } + + public Boolean argAsBool(int idx, boolean def) { + String str = argAsString(idx); + if (str == null) { + return def; + } + + return strAsBool(str); + } + + public Boolean argAsBool(int idx) { + return argAsBool(idx, false); + } + + // PLAYER ====================== + public Player strAsPlayer(String name, Player def, boolean msg) { + Player ret = def; + + if (name != null) { + Player player = Bukkit.getServer().getPlayer(name); + if (player != null) { + ret = player; + } + } + + if (msg && ret == null) { + sender.sendMessage(TL.GENERIC_NOPLAYERFOUND.format(name)); + } + + return ret; + } + + public Player argAsPlayer(int idx, Player def, boolean msg) { + return this.strAsPlayer(argAsString(idx), def, msg); + } + + public Player argAsPlayer(int idx, Player def) { + return argAsPlayer(idx, def, true); + } + + public Player argAsPlayer(int idx) { + return argAsPlayer(idx, null); + } + + // BEST PLAYER MATCH ====================== + public Player strAsBestPlayerMatch(String name, Player def, boolean msg) { + Player ret = def; + + if (name != null) { + List players = Bukkit.getServer().matchPlayer(name); + if (players.size() > 0) { + ret = players.get(0); + } + } + + if (msg && ret == null) { + sender.sendMessage(TL.GENERIC_NOPLAYERMATCH.format(name)); + } + + return ret; + } + + public Player argAsBestPlayerMatch(int idx, Player def, boolean msg) { + return this.strAsBestPlayerMatch(argAsString(idx), def, msg); + } + + public Player argAsBestPlayerMatch(int idx, Player def) { + return argAsBestPlayerMatch(idx, def, true); + } + + public Player argAsBestPlayerMatch(int idx) { + return argAsPlayer(idx, null); + } + + + // -------------------------------------------- // + // Faction Argument Readers + // -------------------------------------------- // + + // FPLAYER ====================== + public FPlayer strAsFPlayer(String name, FPlayer def, boolean msg) { + FPlayer ret = def; + + if (name != null) { + for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { + if (fplayer.getName().equalsIgnoreCase(name)) { + ret = fplayer; + break; + } + } + } + + if (msg && ret == null) { + sender.sendMessage(TL.GENERIC_NOPLAYERFOUND.format(name)); + } + + return ret; + } + + public FPlayer argAsFPlayer(int idx, FPlayer def, boolean msg) { + return this.strAsFPlayer(argAsString(idx), def, msg); + } + + public FPlayer argAsFPlayer(int idx, FPlayer def) { + return argAsFPlayer(idx, def, true); + } + + public FPlayer argAsFPlayer(int idx) { + return argAsFPlayer(idx, null); + } + + // BEST FPLAYER MATCH ====================== + public FPlayer strAsBestFPlayerMatch(String name, FPlayer def, boolean msg) { + return strAsFPlayer(name, def, msg); + } + + public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def, boolean msg) { + return this.strAsBestFPlayerMatch(argAsString(idx), def, msg); + } + + public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def) { + return argAsBestFPlayerMatch(idx, def, true); + } + + public FPlayer argAsBestFPlayerMatch(int idx) { + return argAsBestFPlayerMatch(idx, null); + } + + // FACTION ====================== + public Faction strAsFaction(String name, Faction def, boolean msg) { + Faction ret = def; + + if (name != null) { + // First we try an exact match + Faction faction = Factions.getInstance().getByTag(name); // Checks for faction name match. + + // Now lets try for warzone / safezone. Helpful for custom warzone / safezone names. + // Do this after we check for an exact match in case they rename the warzone / safezone + // and a player created faction took one of the names. + if (faction == null) { + if (name.equalsIgnoreCase("warzone")) { + faction = Factions.getInstance().getWarZone(); + } else if (name.equalsIgnoreCase("safezone")) { + faction = Factions.getInstance().getSafeZone(); + } + } + + // Next we match faction tags + if (faction == null) { + faction = Factions.getInstance().getBestTagMatch(name); + } + + // Next we match player names + if (faction == null) { + FPlayer fplayer = strAsFPlayer(name, null, false); + if (fplayer != null) { + faction = fplayer.getFaction(); + } + } + + if (faction != null) { + ret = faction; + } + } + + if (msg && ret == null) { + sender.sendMessage(TL.GENERIC_NOFACTIONMATCH.format(name)); + } + + return ret; + } + + public Faction argAsFaction(int idx, Faction def, boolean msg) { + return this.strAsFaction(argAsString(idx), def, msg); + } + + public Faction argAsFaction(int idx, Faction def) { + return argAsFaction(idx, def, true); + } + + public Faction argAsFaction(int idx) { + return argAsFaction(idx, null); + } + + /* + Assertions + */ + + public boolean assertHasFaction() { + if (player == null) { + return true; + } + + if (!fPlayer.hasFaction()) { + sendMessage("You are not member of any faction."); + return false; + } + return true; + } + + public boolean assertMinRole(Role role) { + if (player == null) { + return true; + } + + if (fPlayer.getRole().value < role.value) { + msg("You must be " + role); + return false; + } + return true; + } + + /* + Common Methods + */ + public boolean canIAdministerYou(FPlayer i, FPlayer you) { + if (!i.getFaction().equals(you.getFaction())) { + i.sendMessage(FactionsPlugin.getInstance().txt().parse("%s is not in the same faction as you.", you.describeTo(i, true))); + return false; + } + + if (i.getRole().value >= you.getRole().value || i.getRole() == Role.ADMIN) { + return true; + } + + i.sendMessage(FactionsPlugin.getInstance().txt().parse("%s has a higher rank than you.", you.describeTo(i, true))); + + return false; + } + + // if economy is enabled and they're not on the bypass list, make 'em pay; returns true unless person can't afford the cost + public boolean payForCommand(double cost, String toDoThis, String forDoingThis) { + if (!Econ.shouldBeUsed() || this.fPlayer == null || cost == 0.0 || fPlayer.isAdminBypassing()) { + return true; + } + + if (FactionsPlugin.getInstance().conf().economy().isBankEnabled() && FactionsPlugin.getInstance().conf().economy().isBankFactionPaysCosts() && fPlayer.hasFaction() && fPlayer.getFaction().hasAccess(fPlayer, PermissibleAction.ECONOMY)) { + return Econ.modifyMoney(faction, -cost, toDoThis, forDoingThis); + } else { + return Econ.modifyMoney(fPlayer, -cost, toDoThis, forDoingThis); + } + } + + public boolean payForCommand(double cost, TL toDoThis, TL forDoingThis) { + return payForCommand(cost, toDoThis.toString(), forDoingThis.toString()); + } + + // like above, but just make sure they can pay; returns true unless person can't afford the cost + public boolean canAffordCommand(double cost, String toDoThis) { + if (!Econ.shouldBeUsed() || fPlayer == null || cost == 0.0 || fPlayer.isAdminBypassing()) { + return true; + } + + if (FactionsPlugin.getInstance().conf().economy().isBankEnabled() && FactionsPlugin.getInstance().conf().economy().isBankFactionPaysCosts() && fPlayer.hasFaction()) { + return Econ.hasAtLeast(faction, cost, toDoThis); + } else { + return Econ.hasAtLeast(fPlayer, cost, toDoThis); + } + } + + public void doWarmUp(WarmUpUtil.Warmup warmup, TL translationKey, String action, Runnable runnable, long delay) { + this.doWarmUp(fPlayer, warmup, translationKey, action, runnable, delay); + } + + public void doWarmUp(FPlayer player, WarmUpUtil.Warmup warmup, TL translationKey, String action, Runnable runnable, long delay) { + WarmUpUtil.process(player, warmup, translationKey, action, runnable, delay); + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/CommandRequirements.java b/Factions/src/main/java/com/massivecraft/factions/cmd/CommandRequirements.java new file mode 100644 index 0000000..27d4160 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/CommandRequirements.java @@ -0,0 +1,149 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CommandRequirements { + + // Permission required to execute command + private final Permission permission; + + // Must be player + private final boolean playerOnly; + // Must be member of faction + private final boolean memberOnly; + + // Must be at least this role + private final Role role; + + // PermissibleAction check if the player has allow for this before checking the role + private final PermissibleAction action; + + // Edge case handling + private boolean errorOnManyArgs; + private boolean disableOnLock; + + private CommandRequirements(Permission permission, boolean playerOnly, boolean memberOnly, Role role, PermissibleAction action) { + this.permission = permission; + this.playerOnly = playerOnly; + this.memberOnly = memberOnly; + this.role = role; + this.action = action; + } + + public boolean computeRequirements(CommandContext context, boolean informIfNot) { + // Did not modify CommandRequirements return true + if (permission == null) { + return true; + } + + if (context.player != null) { + // Is Player + if (!context.fPlayer.hasFaction() && memberOnly) { + if (informIfNot) { + context.msg(TL.GENERIC_MEMBERONLY); + } + return false; + } + + if (!FactionsPlugin.getInstance().getPermUtil().has(context.sender, permission.node, informIfNot)) { + return false; + } + + // Permissible Action provided compute that before role + if (action != null) { + boolean access = context.faction.hasAccess(context.fPlayer, action); + if (!access) { + if (informIfNot) { + context.msg(TL.GENERIC_NOPERMISSION, action.name()); + } + return false; + } + // They have been explicitly allowed + return true; + } else { + if ((role != null && !context.fPlayer.getRole().isAtLeast(role)) && informIfNot) { + context.msg(TL.GENERIC_YOUMUSTBE, role.translation); + } + return role == null || context.fPlayer.getRole().isAtLeast(role); + } + } else { + if (playerOnly) { + if (informIfNot) { + context.sender.sendMessage(TL.GENERIC_PLAYERONLY.toString()); + } + return false; + } + return context.sender.hasPermission(permission.node); + } + } + + public boolean isErrorOnManyArgs() { + return errorOnManyArgs; + } + + public boolean isDisableOnLock() { + return disableOnLock; + } + + public static class Builder { + + private final Permission permission; + + private boolean playerOnly = false; + private boolean memberOnly = false; + + private Role role = null; + private PermissibleAction action; + + private boolean errorOnManyArgs = true; + private boolean disableOnLock = true; + + public Builder(Permission permission) { + this.permission = permission; + } + + public Builder playerOnly() { + playerOnly = true; + return this; + } + + public Builder memberOnly() { + playerOnly = true; + memberOnly = true; + return this; + } + + public Builder withRole(Role role) { + this.role = role; + return this; + } + + public Builder withAction(PermissibleAction action) { + this.action = action; + return this; + } + + public CommandRequirements build() { + CommandRequirements requirements = new CommandRequirements(permission, playerOnly, memberOnly, role, action); + requirements.errorOnManyArgs = errorOnManyArgs; + requirements.disableOnLock = disableOnLock; + return requirements; + } + + public Builder noErrorOnManyArgs() { + errorOnManyArgs = false; + return this; + } + + public Builder noDisableOnLock() { + disableOnLock = false; + return this; + } + + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java b/Factions/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java new file mode 100644 index 0000000..80c2f6f --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java @@ -0,0 +1,286 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.alts.CmdAlts; +import com.massivecraft.factions.cmd.claim.*; +import com.massivecraft.factions.cmd.money.CmdMoney; +import com.massivecraft.factions.cmd.relations.CmdRelationAlly; +import com.massivecraft.factions.cmd.relations.CmdRelationEnemy; +import com.massivecraft.factions.cmd.relations.CmdRelationNeutral; +import com.massivecraft.factions.cmd.relations.CmdRelationTruce; +import com.massivecraft.factions.cmd.role.CmdDemote; +import com.massivecraft.factions.cmd.role.CmdPromote; +import com.massivecraft.factions.cmd.strikes.CmdStrike; +import com.massivecraft.factions.landraidcontrol.DTRControl; +import com.massivecraft.factions.landraidcontrol.PowerControl; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; + +public class FCmdRoot extends FCommand implements CommandExecutor { + + private static FCmdRoot cmdBase; + + public static FCmdRoot getInstance() { + return cmdBase; + } + + public CmdAutoHelp cmdAutoHelp = new CmdAutoHelp(); + + public CmdAdmin cmdAdmin = new CmdAdmin(); + public CmdAutoClaim cmdAutoClaim = new CmdAutoClaim(); + public CmdBoom cmdBoom = new CmdBoom(); + public CmdBypass cmdBypass = new CmdBypass(); + public CmdChat cmdChat = new CmdChat(); + public CmdChatSpy cmdChatSpy = new CmdChatSpy(); + public CmdClaim cmdClaim = new CmdClaim(); + public CmdCoords cmdCoords = new CmdCoords(); + public CmdCreate cmdCreate = new CmdCreate(); + public CmdDeinvite cmdDeinvite = new CmdDeinvite(); + public CmdDescription cmdDescription = new CmdDescription(); + public CmdDisband cmdDisband = new CmdDisband(); + public CmdFly cmdFly = new CmdFly(); + public CmdHelp cmdHelp = new CmdHelp(); + public CmdHome cmdHome = new CmdHome(); + public CmdInvite cmdInvite = new CmdInvite(); + public CmdJoin cmdJoin = new CmdJoin(); + public CmdKick cmdKick = new CmdKick(); + public CmdLeave cmdLeave = new CmdLeave(); + public CmdList cmdList = new CmdList(); + public CmdLock cmdLock = new CmdLock(); + public CmdMap cmdMap = new CmdMap(); + public CmdMod cmdMod = new CmdMod(); + public CmdMoney cmdMoney = new CmdMoney(); + public CmdOpen cmdOpen = new CmdOpen(); + public CmdOwner cmdOwner = new CmdOwner(); + public CmdOwnerList cmdOwnerList = new CmdOwnerList(); + public CmdPeaceful cmdPeaceful = new CmdPeaceful(); + public CmdPermanent cmdPermanent = new CmdPermanent(); + public CmdPermanentPower cmdPermanentPower = new CmdPermanentPower(); + public CmdPowerBoost cmdPowerBoost = new CmdPowerBoost(); + public CmdRally cmdRally = new CmdRally(); + public CmdPower cmdPower = new CmdPower(); + public CmdDTR cmdDTR = new CmdDTR(); + public CmdRelationAlly cmdRelationAlly = new CmdRelationAlly(); + public CmdRelationEnemy cmdRelationEnemy = new CmdRelationEnemy(); + public CmdRelationNeutral cmdRelationNeutral = new CmdRelationNeutral(); + public CmdRelationTruce cmdRelationTruce = new CmdRelationTruce(); + public CmdReload cmdReload = new CmdReload(); + public CmdSafeunclaimall cmdSafeunclaimall = new CmdSafeunclaimall(); + public CmdSaveAll cmdSaveAll = new CmdSaveAll(); + public CmdSethome cmdSethome = new CmdSethome(); + public CmdDelhome cmdDelhome = new CmdDelhome(); + public CmdShow cmdShow = new CmdShow(); + public CmdStatus cmdStatus = new CmdStatus(); + public CmdStuck cmdStuck = new CmdStuck(); + public CmdTag cmdTag = new CmdTag(); + public CmdTitle cmdTitle = new CmdTitle(); + public CmdToggleAllianceChat cmdToggleAllianceChat = new CmdToggleAllianceChat(); + public CmdUnclaim cmdUnclaim = new CmdUnclaim(); + public CmdUnclaimall cmdUnclaimall = new CmdUnclaimall(); + public CmdVersion cmdVersion = new CmdVersion(); + public CmdWarunclaimall cmdWarunclaimall = new CmdWarunclaimall(); + public CmdSB cmdSB = new CmdSB(); + public CmdShowInvites cmdShowInvites = new CmdShowInvites(); + public CmdAnnounce cmdAnnounce = new CmdAnnounce(); + public CmdSeeChunk cmdSeeChunk = new CmdSeeChunk(); + public CmdWarp cmdWarp = new CmdWarp(); + public CmdWarpOther cmdWarpOther = new CmdWarpOther(); + public CmdSetWarp cmdSetWarp = new CmdSetWarp(); + public CmdDelWarp cmdDelWarp = new CmdDelWarp(); + public CmdModifyPower cmdModifyPower = new CmdModifyPower(); + public CmdLogins cmdLogins = new CmdLogins(); + public CmdClaimLine cmdClaimLine = new CmdClaimLine(); + public CmdClaimFill cmdClaimFill = new CmdClaimFill(); + public CmdTop cmdTop = new CmdTop(); + public CmdAHome cmdAHome = new CmdAHome(); + public CmdPerm cmdPerm = new CmdPerm(); + public CmdPromote cmdPromote = new CmdPromote(); + public CmdDemote cmdDemote = new CmdDemote(); + public CmdSetDefaultRole cmdSetDefaultRole = new CmdSetDefaultRole(); + public CmdMapHeight cmdMapHeight = new CmdMapHeight(); + public CmdClaimAt cmdClaimAt = new CmdClaimAt(); + public CmdBan cmdban = new CmdBan(); + public CmdUnban cmdUnban = new CmdUnban(); + public CmdBanlist cmdbanlist = new CmdBanlist(); + public CmdColeader cmdColeader = new CmdColeader(); + public CmdNear cmdNear = new CmdNear(); + public CmdTrail cmdTrail = new CmdTrail(); + public CmdDebug cmdDebug = new CmdDebug(); + public CmdTNT cmdTNT = new CmdTNT(); + public CmdUpgrade cmdUpgrade = new CmdUpgrade(); + public CmdListClaims cmdListClaims = new CmdListClaims(); + public CmdStrike cmdStrike = new CmdStrike(); + public CmdStealth cmdStealth = new CmdStealth(); + public CmdCorner cmdCorner = new CmdCorner(); + public CmdInspect cmdInspect = new CmdInspect(); + public CmdRaidClaim cmdRaidClaim = new CmdRaidClaim(); + + public CmdSotw cmdSotw = new CmdSotw(); + + public CmdAlts cmdAlts = new CmdAlts(); + + public CmdSeePaypal cmdSeePaypal = new CmdSeePaypal(); + + public CmdSetPaypal cmdSetPaypal = new CmdSetPaypal(); + + public FCmdRoot() { + super(); + + cmdBase = this; + + this.aliases.addAll(FactionsPlugin.getInstance().conf().getCommandBase()); + this.aliases.removeAll(Collections.singletonList(null)); // remove any nulls from extra commas + + this.setHelpShort("The faction base command"); + this.helpLong.add(FactionsPlugin.getInstance().txt().parseTags("This command contains all faction stuff.")); + + this.addSubCommand(this.cmdRally); + this.addSubCommand(this.cmdAlts); + this.addSubCommand(this.cmdAdmin); + this.addSubCommand(this.cmdAutoClaim); + this.addSubCommand(this.cmdBoom); + this.addSubCommand(this.cmdSetPaypal); + this.addSubCommand(this.cmdSeePaypal); + this.addSubCommand(this.cmdBypass); + this.addSubCommand(this.cmdChat); + this.addSubCommand(this.cmdToggleAllianceChat); + this.addSubCommand(this.cmdChatSpy); + this.addSubCommand(this.cmdClaim); + this.addSubCommand(this.cmdCoords); + this.addSubCommand(this.cmdCreate); + this.addSubCommand(this.cmdDeinvite); + this.addSubCommand(this.cmdDescription); + this.addSubCommand(this.cmdDisband); + this.addSubCommand(this.cmdHelp); + this.addSubCommand(this.cmdHome); + this.addSubCommand(this.cmdInvite); + this.addSubCommand(this.cmdJoin); + this.addSubCommand(this.cmdKick); + this.addSubCommand(this.cmdLeave); + this.addSubCommand(this.cmdList); + this.addSubCommand(this.cmdLock); + this.addSubCommand(this.cmdMap); + this.addSubCommand(this.cmdMod); + this.addSubCommand(this.cmdMoney); + this.addSubCommand(this.cmdOpen); + this.addSubCommand(this.cmdOwner); + this.addSubCommand(this.cmdOwnerList); + this.addSubCommand(this.cmdPeaceful); + this.addSubCommand(this.cmdPermanent); + this.addSubCommand(this.cmdRelationAlly); + this.addSubCommand(this.cmdRelationEnemy); + this.addSubCommand(this.cmdRelationNeutral); + this.addSubCommand(this.cmdRelationTruce); + this.addSubCommand(this.cmdReload); + this.addSubCommand(this.cmdSafeunclaimall); + this.addSubCommand(this.cmdSaveAll); + this.addSubCommand(this.cmdSethome); + this.addSubCommand(this.cmdDelhome); + this.addSubCommand(this.cmdShow); + this.addSubCommand(this.cmdStatus); + this.addSubCommand(this.cmdStuck); + this.addSubCommand(this.cmdTag); + this.addSubCommand(this.cmdTitle); + this.addSubCommand(this.cmdUnclaim); + this.addSubCommand(this.cmdUnclaimall); + this.addSubCommand(this.cmdVersion); + this.addSubCommand(this.cmdWarunclaimall); + this.addSubCommand(this.cmdSB); + this.addSubCommand(this.cmdShowInvites); + this.addSubCommand(this.cmdAnnounce); + this.addSubCommand(this.cmdSeeChunk); + this.addSubCommand(this.cmdWarp); + this.addSubCommand(this.cmdWarpOther); + this.addSubCommand(this.cmdSetWarp); + this.addSubCommand(this.cmdDelWarp); + this.addSubCommand(this.cmdLogins); + this.addSubCommand(this.cmdClaimLine); + this.addSubCommand(this.cmdClaimFill); + this.addSubCommand(this.cmdAHome); + this.addSubCommand(this.cmdPerm); + this.addSubCommand(this.cmdPromote); + this.addSubCommand(this.cmdDemote); + this.addSubCommand(this.cmdSetDefaultRole); + this.addSubCommand(this.cmdMapHeight); + this.addSubCommand(this.cmdClaimAt); + this.addSubCommand(this.cmdban); + this.addSubCommand(this.cmdUnban); + this.addSubCommand(this.cmdbanlist); + this.addSubCommand(this.cmdColeader); + this.addSubCommand(this.cmdNear); + this.addSubCommand(this.cmdDebug); + this.addSubCommand(this.cmdListClaims); + this.addSubCommand(this.cmdUpgrade); + this.addSubCommand(this.cmdStrike); + this.addSubCommand(this.cmdSotw); + this.addSubCommand(this.cmdStealth); + this.addSubCommand(this.cmdCorner); + this.addSubCommand(this.cmdInspect); + this.addSubCommand(this.cmdRaidClaim); + if (FactionsPlugin.getInstance().getLandRaidControl() instanceof PowerControl) { + FactionsPlugin.getInstance().getLogger().info("Using POWER for land/raid control. Enabling power commands."); + this.addSubCommand(this.cmdPermanentPower); + this.addSubCommand(this.cmdPower); + this.addSubCommand(this.cmdPowerBoost); + this.addSubCommand(this.cmdModifyPower); + } else if (FactionsPlugin.getInstance().getLandRaidControl() instanceof DTRControl) { + FactionsPlugin.getInstance().getLogger().info("Using DTR for land/raid control. Enabling DTR commands."); + this.addSubCommand(this.cmdDTR); + } + if (FactionsPlugin.getInstance().conf().commands().tnt().isEnable()) { + this.addSubCommand(this.cmdTNT); + FactionsPlugin.getInstance().getLogger().info("Enabling TNT bank management"); + } + if (FactionsPlugin.getInstance().conf().commands().fly().isEnable()) { + this.addSubCommand(this.cmdFly); + this.addSubCommand(this.cmdTrail); + FactionsPlugin.getInstance().getLogger().info("Enabling /f fly command"); + } else { + FactionsPlugin.getInstance().getLogger().info("Faction flight set to false in main.conf. Not enabling /f fly command."); + } + + } + + public void done() { + if (Bukkit.getServer().getPluginManager().isPluginEnabled("FactionsTop")) { + FactionsPlugin.getInstance().getLogger().info("Found FactionsTop plugin. Disabling our own /f top command."); + } else { + this.addSubCommand(this.cmdTop); + } + } + + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + this.cmdHelp.execute(context); + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (!plugin.worldUtil().isEnabled(sender)) { + sender.sendMessage(TL.GENERIC_DISABLEDWORLD.toString()); + return false; + } + + this.execute(new CommandContext(sender, new ArrayList<>(Arrays.asList(args)), label)); + return true; + } + + @Override + public void addSubCommand(FCommand subCommand) { + super.addSubCommand(subCommand); + } + + @Override + public TL getUsageTranslation() { + return TL.GENERIC_PLACEHOLDER; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/FCommand.java b/Factions/src/main/java/com/massivecraft/factions/cmd/FCommand.java new file mode 100644 index 0000000..85ee551 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/FCommand.java @@ -0,0 +1,211 @@ +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.tag.Tag; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.TextUtil; +import org.bukkit.ChatColor; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + + +public abstract class FCommand { + public enum CommandVisibility { + VISIBLE, // Visible commands are visible to anyone. Even those who don't have permission to use it or is of invalid sender type. + SECRET, // Secret commands are visible only to those who can use the command. These commands are usually some kind of admin commands. + INVISIBLE // Invisible commands are invisible to everyone, even those who can use the command. + } + + public FactionsPlugin plugin; + public SimpleDateFormat sdf = new SimpleDateFormat(TL.DATE_FORMAT.toString()); + + // Command Aliases + public List aliases; + + // Information on the args + public List requiredArgs; + public LinkedHashMap optionalArgs; + + // Requirements to execute this command + public CommandRequirements requirements; + + public FCommand() { + plugin = FactionsPlugin.getInstance(); + + requirements = new CommandRequirements.Builder(null).build(); + + this.subCommands = new ArrayList<>(); + this.aliases = new ArrayList<>(); + + this.requiredArgs = new ArrayList<>(); + this.optionalArgs = new LinkedHashMap<>(); + + this.helpShort = null; + this.helpLong = new ArrayList<>(); + this.visibility = CommandVisibility.VISIBLE; + } + + public abstract void perform(CommandContext context); + + public void execute(CommandContext context) { + // Is there a matching sub command? + if (context.args.size() > 0) { + for (FCommand subCommand : this.subCommands) { + if (subCommand.aliases.contains(context.args.get(0).toLowerCase())) { + context.args.remove(0); + context.commandChain.add(this); + subCommand.execute(context); + return; + } + } + } + + if (!validCall(context)) { + return; + } + + if (!this.isEnabled(context)) { + return; + } + + perform(context); + } + + public boolean validCall(CommandContext context) { + return requirements.computeRequirements(context, true) && validArgs(context); + } + + public boolean isEnabled(CommandContext context) { + if (FactionsPlugin.getInstance().getLocked() && requirements.isDisableOnLock()) { + context.msg("Factions was locked by an admin. Please try again later."); + return false; + } + return true; + } + + public boolean validArgs(CommandContext context) { + if (context.args.size() < this.requiredArgs.size()) { + if (context.sender != null) { + context.msg(TL.GENERIC_ARGS_TOOFEW); + context.sender.sendMessage(this.getUsageTemplate(context)); + } + return false; + } + + if (context.args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.requirements.isErrorOnManyArgs()) { + if (context.sender != null) { + // Get the to many string slice + List theToMany = context.args.subList(this.requiredArgs.size() + this.optionalArgs.size(), context.args.size()); + context.msg(TL.GENERIC_ARGS_TOOMANY, TextUtil.implode(theToMany, " ")); + context.sender.sendMessage(this.getUsageTemplate(context)); + } + return false; + } + return true; + } + + /* + Subcommands + */ + public List subCommands; + + public void addSubCommand(FCommand subCommand) { + this.subCommands.add(subCommand); + } + + /* + Help + */ + public List helpLong; + public CommandVisibility visibility; + + private String helpShort; + + public void setHelpShort(String val) { + this.helpShort = val; + } + + public String getHelpShort() { + if (this.helpShort == null) { + return getUsageTranslation().toString(); + } + + return this.helpShort; + } + + public abstract TL getUsageTranslation(); + + /* + Common Logic + */ + public List getToolTips(FPlayer player) { + List lines = new ArrayList<>(); + for (String s : FactionsPlugin.getInstance().conf().commands().toolTips().getPlayer()) { + lines.add(ChatColor.translateAlternateColorCodes('&', Tag.parsePlain(player, s))); + } + return lines; + } + + public List getToolTips(Faction faction) { + List lines = new ArrayList<>(); + for (String s : FactionsPlugin.getInstance().conf().commands().toolTips().getFaction()) { + lines.add(ChatColor.translateAlternateColorCodes('&', Tag.parsePlain(faction, s))); + } + return lines; + } + + /* + Help and Usage information + */ + public String getUsageTemplate(CommandContext context, boolean addShortHelp) { + StringBuilder ret = new StringBuilder(); + ret.append(FactionsPlugin.getInstance().txt().parseTags("")); + ret.append('/'); + + for (FCommand fc : context.commandChain) { + ret.append(TextUtil.implode(fc.aliases, ",")); + ret.append(' '); + } + + ret.append(TextUtil.implode(this.aliases, ",")); + + List args = new ArrayList<>(); + + for (String requiredArg : this.requiredArgs) { + args.add("<" + requiredArg + ">"); + } + + for (Map.Entry optionalArg : this.optionalArgs.entrySet()) { + String val = optionalArg.getValue(); + if (val == null) { + val = ""; + } else { + val = "=" + val; + } + args.add("[" + optionalArg.getKey() + val + "]"); + } + + if (args.size() > 0) { + ret.append(FactionsPlugin.getInstance().txt().parseTags(" ")); + ret.append(TextUtil.implode(args, " ")); + } + + if (addShortHelp) { + ret.append(FactionsPlugin.getInstance().txt().parseTags(" ")); + ret.append(this.getHelpShort()); + } + + return ret.toString(); + } + + public String getUsageTemplate(CommandContext context) { + return getUsageTemplate(context, false); + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltClear.java b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltClear.java new file mode 100644 index 0000000..e1b04cc --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltClear.java @@ -0,0 +1,46 @@ +package com.massivecraft.factions.cmd.alts; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.CC; +import com.massivecraft.factions.util.TL; + +public class CmdAltClear extends FCommand { + + public CmdAltClear() { + super(); + this.aliases.add("clear"); + + this.requirements = new CommandRequirements.Builder(Permission.ALTS).withAction(PermissibleAction.INVITE).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.faction; + + int amountKicked = 0; + for (FPlayer fPlayer : faction.getFPlayersWhereRole(Role.ALT)) { + faction.removeFPlayer(fPlayer); + amountKicked++; + } + if (amountKicked == 0) { + context.fPlayer.sendMessage(CC.translate("&6&lFactions &8⎜ &cError&8: &eThere are no alts in your faction")); + } else { + context.fPlayer.sendMessage(CC.translate("&6&lFactions &8⎜ &cError&8: &eRemoved a total of &7" + amountKicked + " &ealts from your faction")); + + } + + + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ALT_OPENUSAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltClose.java b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltClose.java new file mode 100644 index 0000000..09018a7 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltClose.java @@ -0,0 +1,38 @@ +package com.massivecraft.factions.cmd.alts; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdAltClose extends FCommand { + + public CmdAltClose(){ + super(); + this.aliases.add("close"); + + this.requirements = new CommandRequirements.Builder(Permission.ALTS).withAction(PermissibleAction.INVITE).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.faction; + + if(faction.getAltJoinString().equals("-1")){ + context.msg(TL.COMMAND_ALT_ALREADYCLOSED, faction.describeTo(context.fPlayer)); + return; + } + + faction.setAltClosed(); + + context.msg(TL.COMMAND_ALT_CLOSE, faction.describeTo(context.fPlayer)); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ALT_CLOSEUSAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltJoin.java b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltJoin.java new file mode 100644 index 0000000..aa9fcba --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltJoin.java @@ -0,0 +1,72 @@ +package com.massivecraft.factions.cmd.alts; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdAltJoin extends FCommand { + public CmdAltJoin(){ + super(); + this.aliases.add("join"); + + this.requiredArgs.add("faction"); + this.requiredArgs.add("joinString"); + + this.requirements = new CommandRequirements.Builder(Permission.ALTS).build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.argAsFaction(0); + + String other = context.argAsString(1); + + if(faction == null)return; + + if(other == null)return; + + if (context.fPlayer.hasFaction()) { + context.msg(TL.COMMAND_JOIN_INOTHERFACTION, context.fPlayer.describeTo(context.fPlayer, true), "your"); + return; + } + + if (FactionsPlugin.getInstance().conf().factions().other().maxAlts() > 0 && faction.getFPlayersWhereRole(Role.ALT).size() >= FactionsPlugin.getInstance().conf().factions().other().maxAlts()) { + context.msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(context.fPlayer), FactionsPlugin.getInstance().conf().factions().other().maxAlts(), context.fPlayer.describeTo(context.fPlayer, false)); + return; + } + + if(faction == context.fPlayer.getFaction()){ + context.msg(TL.COMMAND_JOIN_ALREADYMEMBER, context.fPlayer.describeTo(context.fPlayer, true), "are", faction.getTag(context.fPlayer)); + return; + } + + if(faction.getAltJoinString().equals("-1")){ + context.msg(TL.COMMAND_ALT_NOTOPEN, faction.describeTo(context.fPlayer)); + return; + } + + if(!faction.getAltJoinString().equals(other)){ + context.msg(TL.COMMAND_ALT_WRONGCODE, other, faction.describeTo(context.fPlayer)); + return; + } + + context.fPlayer.resetFactionData(); + + context.fPlayer.setFaction(faction); + + context.msg(TL.COMMAND_JOIN_SUCCESS, context.fPlayer.describeTo(context.fPlayer, true), faction.getTag(context.fPlayer)); + + context.fPlayer.setRole(Role.ALT); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ALT_JOINUSAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltOpen.java b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltOpen.java new file mode 100644 index 0000000..fb831c6 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltOpen.java @@ -0,0 +1,38 @@ +package com.massivecraft.factions.cmd.alts; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdAltOpen extends FCommand { + + public CmdAltOpen(){ + super(); + this.aliases.add("open"); + + this.requirements = new CommandRequirements.Builder(Permission.ALTS).withAction(PermissibleAction.INVITE).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.faction; + + if(!faction.getAltJoinString().equals("-1")){ + context.msg(TL.COMMAND_ALT_ALREADYOPEN, faction.describeTo(context.fPlayer), faction.getAltJoinString()); + return; + } + + String string = faction.setAltOpen(); + + context.msg(TL.COMMAND_ALT_OPEN, faction.describeTo(context.fPlayer), string); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ALT_OPENUSAGE; + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAlts.java b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAlts.java new file mode 100644 index 0000000..97ee687 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/alts/CmdAlts.java @@ -0,0 +1,37 @@ +package com.massivecraft.factions.cmd.alts; + +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCmdRoot; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdAlts extends FCommand { + public CmdAlts(){ + super(); + this.aliases.add("alts"); + this.aliases.add("alt"); + + this.addSubCommand(new CmdAltJoin()); + + this.addSubCommand(new CmdAltOpen()); + + this.addSubCommand(new CmdAltClose()); + + this.addSubCommand(new CmdAltClear()); + + this.requirements = new CommandRequirements.Builder(Permission.ALTS).build(); + } + + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + FCmdRoot.getInstance().cmdAutoHelp.execute(context); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ALT_USAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdAutoClaim.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdAutoClaim.java new file mode 100644 index 0000000..238dc62 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdAutoClaim.java @@ -0,0 +1,54 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdAutoClaim extends FCommand { + + public CmdAutoClaim() { + super(); + this.aliases.add("autoclaim"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("faction", "your"); + + this.requirements = new CommandRequirements.Builder(Permission.AUTOCLAIM) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + Faction forFaction = context.argAsFaction(0, context.faction); + if (forFaction == null || forFaction == context.fPlayer.getAutoClaimFor()) { + context.fPlayer.setAutoClaimFor(null); + context.msg(TL.COMMAND_AUTOCLAIM_DISABLED); + return; + } + + if (!context.fPlayer.canClaimForFaction(forFaction)) { + if (context.faction == forFaction) { + context.msg(TL.CLAIM_CANTCLAIM, forFaction.describeTo(context.fPlayer)); + } else { + context.msg(TL.COMMAND_AUTOCLAIM_OTHERFACTION, forFaction.describeTo(context.fPlayer)); + } + + return; + } + + context.fPlayer.setAutoClaimFor(forFaction); + + context.msg(TL.COMMAND_AUTOCLAIM_ENABLED, forFaction.describeTo(context.fPlayer)); + context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), true); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_AUTOCLAIM_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaim.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaim.java new file mode 100644 index 0000000..523a411 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaim.java @@ -0,0 +1,140 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.event.LandClaimRadiusEvent; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.SpiralTask; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.Triplet; +import org.bukkit.Bukkit; + +import java.util.*; + + +public class CmdClaim extends FCommand { + + public CmdClaim() { + super(); + this.aliases.add("claim"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("radius", "1"); + this.optionalArgs.put("faction", "your"); + + this.requirements = new CommandRequirements.Builder(Permission.CLAIM) + .playerOnly() + .build(); + } + + public static final Map> attemptingBypass = new HashMap<>(); + + @Override + public void perform(final CommandContext context) { + // Read and validate input + int radius = context.argAsInt(0, 1); // Default to 1 + Faction forFaction = context.argAsFaction(1, context.faction); // Default to own + String arg = context.argAsString(0); + + boolean bypassed = false; + + if (arg != null && !arg.isEmpty() && arg.equalsIgnoreCase("confirm")) { + if (!attemptingBypass.containsKey(context.player.getUniqueId())) { + context.msg("&cYou don't have a claim to confirm!"); + return; + } + Triplet integerLongPair = attemptingBypass.get(context.player.getUniqueId()); + long timeAt = integerLongPair.getRight(); + + if (timeAt + 5000 < System.currentTimeMillis()) { + context.msg("&cThat claim confirm has expired! Try again!"); + attemptingBypass.remove(context.player.getUniqueId()); + return; + } + + radius = integerLongPair.getLeft(); + + forFaction = integerLongPair.getMiddle(); + + bypassed = true; + } + + if (radius < 1) { + context.msg(TL.COMMAND_CLAIM_INVALIDRADIUS); + return; + } + + if (radius > FactionsPlugin.getInstance().conf().factions().claims().getMaxRadiusClaim() && !bypassed) { + if (context.fPlayer.isAdminBypassing() || context.player.hasPermission("factions.claim.bypasslimit")) { + attemptingBypass.put(context.player.getUniqueId(), Triplet.of(radius, forFaction, System.currentTimeMillis())); + context.msg(TL.COMMAND_CLAIM_TOOBIGCONFIRM, radius); + return; + } + context.msg(TL.COMMAND_CLAIM_TOOBIG, FactionsPlugin.getInstance().conf().factions().claims().getMaxRadiusClaim()); + return; + } + + if (radius < 2) { + // single chunk + context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), true); + } else { + // radius claim + if (!Permission.CLAIM_RADIUS.has(context.sender, false)) { + context.msg(TL.COMMAND_CLAIM_DENIED); + return; + } + + FLocation fLocation = new FLocation(context.player); + + context.msg(TL.COMMAND_CLAIM_RADIUS, radius, fLocation.getChunk().getX(), fLocation.getChunk().getZ(), forFaction.describeTo(context.fPlayer, true)); + + final Faction loopFac = forFaction; + + int finalRadius = radius; + Faction finalForFaction = forFaction; + new SpiralTask(fLocation, finalRadius) { + private int failCount = 0; + private final int limit = FactionsPlugin.getInstance().conf().factions().claims().getRadiusClaimFailureLimit() - 1; + + private int claimed = 0; + + @Override + public boolean work() { + boolean success = context.fPlayer.attemptClaim(loopFac, this.currentFLocation(), true, this); + if (success) { + failCount = 0; + claimed++; + } else return failCount++ < limit; + + return true; + } + + @Override + public void finish() { + Set informTheseFPlayers = new HashSet<>(loopFac.getFPlayersWhereOnline(true)); + informTheseFPlayers.remove(context.fPlayer); + for (FPlayer fp : informTheseFPlayers) { + fp.msg(TL.CLAIM_CLAIMEDAMOUNT, context.fPlayer.describeTo(fp, true), claimed, loopFac.describeTo(fp)); + } + + context.fPlayer.msg(TL.CLAIM_CLAIMEDAMOUNT, context.fPlayer.describeTo(context.fPlayer, true), claimed, loopFac.describeTo(context.fPlayer)); + LandClaimRadiusEvent landClaimRadiusEvent = new LandClaimRadiusEvent(fLocation, finalRadius, finalForFaction, context.fPlayer); + Bukkit.getServer().getPluginManager().callEvent(landClaimRadiusEvent); + super.finish(); + } + }; + + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CLAIM_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimAt.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimAt.java new file mode 100644 index 0000000..92bb899 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimAt.java @@ -0,0 +1,37 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdClaimAt extends FCommand { + + public CmdClaimAt() { + super(); + this.aliases.add("claimat"); + + this.requiredArgs.add("world"); + this.requiredArgs.add("x"); + this.requiredArgs.add("z"); + + this.requirements = new CommandRequirements.Builder(Permission.CLAIMAT) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + int x = context.argAsInt(1); + int z = context.argAsInt(2); + FLocation location = new FLocation(context.argAsString(0), x, z); + context.fPlayer.attemptClaim(context.faction, location, true); + } + + @Override + public TL getUsageTranslation() { + return null; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimFill.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimFill.java new file mode 100644 index 0000000..9441dc3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimFill.java @@ -0,0 +1,125 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Location; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Set; + +public class CmdClaimFill extends FCommand { + + public CmdClaimFill() { + + // Aliases + this.aliases.add("claimfill"); + this.aliases.add("cf"); + + // Args + this.optionalArgs.put("limit", String.valueOf(FactionsPlugin.getInstance().conf().factions().claims().getFillClaimMaxClaims())); + this.optionalArgs.put("faction", "you"); + + this.requirements = new CommandRequirements.Builder(Permission.CLAIM_FILL) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + // Args + final int limit = context.argAsInt(0, FactionsPlugin.getInstance().conf().factions().claims().getFillClaimMaxClaims()); + + if (limit > FactionsPlugin.getInstance().conf().factions().claims().getFillClaimMaxClaims()) { + context.msg(TL.COMMAND_CLAIMFILL_ABOVEMAX, FactionsPlugin.getInstance().conf().factions().claims().getFillClaimMaxClaims()); + return; + } + + final Faction forFaction = context.argAsFaction(2, context.faction); + Location location = context.player.getLocation(); + FLocation loc = new FLocation(location); + + Faction currentFaction = Board.getInstance().getFactionAt(loc); + + if (currentFaction.equals(forFaction)) { + context.msg(TL.CLAIM_ALREADYOWN, forFaction.describeTo(context.fPlayer, true)); + return; + } + + if (!currentFaction.isWilderness()) { + context.msg(TL.COMMAND_CLAIMFILL_ALREADYCLAIMED); + return; + } + + if (!context.fPlayer.isAdminBypassing() && !forFaction.hasAccess(context.fPlayer, PermissibleAction.TERRITORY)) { + context.msg(TL.CLAIM_CANTCLAIM, forFaction.describeTo(context.fPlayer)); + return; + } + + final double distance = FactionsPlugin.getInstance().conf().factions().claims().getFillClaimMaxDistance(); + long startX = loc.getX(); + long startZ = loc.getZ(); + + Set toClaim = new HashSet<>(); + Queue queue = new LinkedList<>(); + FLocation currentHead; + queue.add(loc); + toClaim.add(loc); + while (!queue.isEmpty() && toClaim.size() <= limit) { + currentHead = queue.poll(); + + if (Math.abs(currentHead.getX() - startX) > distance || Math.abs(currentHead.getZ() - startZ) > distance) { + context.msg(TL.COMMAND_CLAIMFILL_TOOFAR, distance); + return; + } + + addIf(toClaim, queue, currentHead.getRelative(0, 1)); + addIf(toClaim, queue, currentHead.getRelative(0, -1)); + addIf(toClaim, queue, currentHead.getRelative(1, 0)); + addIf(toClaim, queue, currentHead.getRelative(-1, 0)); + } + + if (toClaim.size() > limit) { + context.msg(TL.COMMAND_CLAIMFILL_PASTLIMIT); + return; + } + + if (toClaim.size() > this.plugin.getLandRaidControl().getPossibleClaimCount(forFaction)) { + context.msg(TL.COMMAND_CLAIMFILL_NOTENOUGHLANDLEFT, forFaction.describeTo(context.fPlayer), toClaim.size()); + return; + } + + final int limFail = FactionsPlugin.getInstance().conf().factions().claims().getRadiusClaimFailureLimit(); + int fails = 0; + for (FLocation currentLocation : toClaim) { + if (!context.fPlayer.attemptClaim(forFaction, currentLocation, true)) { + fails++; + } + if (fails >= limFail) { + context.msg(TL.COMMAND_CLAIMFILL_TOOMUCHFAIL, fails); + return; + } + } + } + + private void addIf(Set toClaim, Queue queue, FLocation examine) { + if (Board.getInstance().getFactionAt(examine).isWilderness() && !toClaim.contains(examine)) { + toClaim.add(examine); + queue.add(examine); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CLAIMFILL_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimLine.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimLine.java new file mode 100644 index 0000000..d60277b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimLine.java @@ -0,0 +1,75 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Location; +import org.bukkit.block.BlockFace; + +public class CmdClaimLine extends FCommand { + + public static final BlockFace[] axis = {BlockFace.SOUTH, BlockFace.WEST, BlockFace.NORTH, BlockFace.EAST}; + + public CmdClaimLine() { + + // Aliases + this.aliases.add("claimline"); + this.aliases.add("cl"); + + // Args + this.optionalArgs.put("amount", "1"); + this.optionalArgs.put("direction", "facing"); + this.optionalArgs.put("faction", "you"); + + this.requirements = new CommandRequirements.Builder(Permission.CLAIM_LINE) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + // Args + Integer amount = context.argAsInt(0, 1); // Default to 1 + + if (amount > FactionsPlugin.getInstance().conf().factions().claims().getLineClaimLimit()) { + context.msg(TL.COMMAND_CLAIMLINE_ABOVEMAX, FactionsPlugin.getInstance().conf().factions().claims().getLineClaimLimit()); + return; + } + + String direction = context.argAsString(1); + BlockFace blockFace; + + if (direction == null) { + blockFace = axis[Math.round(context.player.getLocation().getYaw() / 90f) & 0x3]; + } else if (direction.equalsIgnoreCase("north")) { + blockFace = BlockFace.NORTH; + } else if (direction.equalsIgnoreCase("east")) { + blockFace = BlockFace.EAST; + } else if (direction.equalsIgnoreCase("south")) { + blockFace = BlockFace.SOUTH; + } else if (direction.equalsIgnoreCase("west")) { + blockFace = BlockFace.WEST; + } else { + context.fPlayer.msg(TL.COMMAND_CLAIMLINE_NOTVALID, direction); + return; + } + + final Faction forFaction = context.argAsFaction(2, context.faction); + Location location = context.player.getLocation(); + + // TODO: make this a task like claiming a radius? + for (int i = 0; i < amount; i++) { + context.fPlayer.attemptClaim(forFaction, location, true); + location = location.add(blockFace.getModX() * 16, 0, blockFace.getModZ() * 16); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CLAIMLINE_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdCorner.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdCorner.java new file mode 100644 index 0000000..f9985e6 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdCorner.java @@ -0,0 +1,72 @@ +package com.massivecraft.factions.cmd.claim; + + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Location; + +public class CmdCorner extends FCommand { + public CmdCorner(){ + this.aliases.add("claimcorner"); + this.aliases.add("corner"); + + this.requirements = new CommandRequirements.Builder(Permission.CLAIM_CORNER) + .withAction(PermissibleAction.CLAIM_CORNER) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer fPlayer = context.fPlayer; + FLocation fLocation = fPlayer.getFLocation(); + + if(!FactionsPlugin.getInstance().isSOTW() && !FactionsPlugin.getInstance().conf().corner().onlyAllowInSOTW()){ + fPlayer.msg(TL.COMMAND_CORNER_ISNTSOTW); + return; + } + + FLocation.EnumCorner corner = fLocation.getCorner(); + + if(corner == null){ + fPlayer.msg(TL.COMMAND_CORNER_MUSTBEINCORNER); + return; + } + + if(fPlayer.getRelationToLocation() != Relation.MEMBER && !Board.getInstance().getFactionAt(new FLocation(fPlayer)).isWilderness()){ + fPlayer.msg(TL.COMMAND_CORNER_MUSTOWN); + return; + } + + int xStart = corner == FLocation.EnumCorner.NEG_NEG || corner == FLocation.EnumCorner.NEG_POS ? 0 : -FactionsPlugin.getInstance().conf().corner().diameterClaim(); + int zStart = corner == FLocation.EnumCorner.NEG_NEG || corner == FLocation.EnumCorner.POS_NEG ? 0 : -FactionsPlugin.getInstance().conf().corner().diameterClaim(); + int xEnd = xStart + FactionsPlugin.getInstance().conf().corner().diameterClaim(); + int zEnd = zStart + FactionsPlugin.getInstance().conf().corner().diameterClaim(); + + Location location = fPlayer.getPlayer().getLocation(); + int myCX = location.getBlockX() >> 4; + int myCZ = location.getBlockZ() >> 4; + + for(int x = xStart; x <= xEnd; x++){ + for(int z = zStart; z <= zEnd; z++){ + Board.getInstance().setFactionAt(fPlayer.getFaction(), new FLocation(fPlayer.getPlayer().getWorld().getName(), myCX + x, myCZ + z)); + } + } + + fPlayer.msg(TL.COMMAND_CORNER_SUCCESS); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CORNER_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdRaidClaim.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdRaidClaim.java new file mode 100644 index 0000000..d96b953 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdRaidClaim.java @@ -0,0 +1,86 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.SpiralTask; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.Triplet; + +import java.util.*; + +public class CmdRaidClaim extends FCommand { + + public CmdRaidClaim() { + super(); + this.aliases.add("raidclaim"); + this.aliases.add("rclaim"); + this.aliases.add("rc"); + + this.requirements = new CommandRequirements.Builder(Permission.CLAIM) + .playerOnly() + .build(); + } + + public static final Map> attemptingBypass = new HashMap<>(); + + @Override + public void perform(final CommandContext context) { + int radius = FactionsPlugin.getInstance().conf().commands().raidClaim().getRaidClaimRadius(); + Faction forFaction = context.faction; + + if (!Permission.CLAIM_RADIUS.has(context.sender, false)) { + context.msg(TL.COMMAND_CLAIM_DENIED); + return; + } + + FLocation fLocation = new FLocation(context.player); + + context.msg(TL.COMMAND_CLAIM_RADIUS, radius, fLocation.getChunk().getX(), fLocation.getChunk().getZ(), forFaction.describeTo(context.fPlayer, true)); + + final Faction loopFac = forFaction; + + new SpiralTask(fLocation, radius) { + private int failCount = 0; + private final int limit = FactionsPlugin.getInstance().conf().factions().claims().getRadiusClaimFailureLimit() - 1; + + private int claimed = 0; + + @Override + public boolean work() { + boolean success = context.fPlayer.attemptClaim(loopFac, this.currentFLocation(), true, this); + if (success) { + failCount = 0; + claimed++; + } else return failCount++ < limit; + + return true; + } + + @Override + public void finish() { + Set informTheseFPlayers = new HashSet<>(loopFac.getFPlayersWhereOnline(true)); + informTheseFPlayers.remove(context.fPlayer); + for (FPlayer fp : informTheseFPlayers) { + fp.msg(TL.CLAIM_CLAIMEDAMOUNT, context.fPlayer.describeTo(fp, true), claimed, loopFac.describeTo(fp)); + } + + context.fPlayer.msg(TL.CLAIM_CLAIMEDAMOUNT, context.fPlayer.describeTo(context.fPlayer, true), claimed, loopFac.describeTo(context.fPlayer)); + super.finish(); + } + }; + + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CLAIM_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdSafeunclaimall.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdSafeunclaimall.java new file mode 100644 index 0000000..d4629b0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdSafeunclaimall.java @@ -0,0 +1,54 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; +import org.bukkit.World; + +public class CmdSafeunclaimall extends FCommand { + + public CmdSafeunclaimall() { + this.aliases.add("safeunclaimall"); + this.aliases.add("safedeclaimall"); + + this.optionalArgs.put("world", "all"); + + this.requirements = new CommandRequirements.Builder(Permission.MANAGE_SAFE_ZONE).build(); + } + + @Override + public void perform(CommandContext context) { + String worldName = context.argAsString(0); + World world = null; + + if (worldName != null) { + world = Bukkit.getWorld(worldName); + } + + String id = Factions.getInstance().getSafeZone().getId(); + + if (world == null) { + Board.getInstance().unclaimAll(id); + } else { + Board.getInstance().unclaimAllInWorld(id, world); + } + + context.msg(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMED); + + if (FactionsPlugin.getInstance().conf().logging().isLandUnclaims()) { + FactionsPlugin.getInstance().log(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMEDLOG.format(context.sender.getName())); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SAFEUNCLAIMALL_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java new file mode 100644 index 0000000..ce94734 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java @@ -0,0 +1,203 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.*; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.event.LandUnclaimEvent; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.AsyncSpiralTask; +import com.massivecraft.factions.util.SpiralTask; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +import java.util.HashSet; +import java.util.Set; + +public class CmdUnclaim extends FCommand { + + public CmdUnclaim() { + this.aliases.add("unclaim"); + this.aliases.add("declaim"); + + this.optionalArgs.put("radius", "1"); + this.optionalArgs.put("faction", "your"); + + this.requirements = new CommandRequirements.Builder(Permission.UNCLAIM) + .playerOnly() + .build(); + } + + @Override + public void perform(final CommandContext context) { + // Read and validate input + int radius = context.argAsInt(0, 1); // Default to 1 + final Faction forFaction = context.argAsFaction(1, context.faction); // Default to own + + if (radius < 1) { + context.msg(TL.COMMAND_CLAIM_INVALIDRADIUS); + return; + } + + if (radius < 2) { + // single chunk + unClaim(new FLocation(context.player), context, forFaction); + } else { + // radius claim + if (!Permission.CLAIM_RADIUS.has(context.sender, false)) { + context.msg(TL.COMMAND_CLAIM_DENIED); + return; + } + + new SpiralTask(new FLocation(context.player), radius) { + private int failCount = 0; + private int unclaimed = 0; + private final int limit = FactionsPlugin.getInstance().conf().factions().claims().getRadiusClaimFailureLimit() - 1; + + @Override + public boolean work() { + boolean success = unClaim(this.currentFLocation(), context, forFaction, this); + if (success) { + failCount = 0; + unclaimed++; + } else return failCount++ < limit; + + return true; + } + + @Override + public void finish() { + if(unclaimed > 0){ + Set informTheseFPlayers = new HashSet<>(forFaction.getFPlayersWhereOnline(true)); + informTheseFPlayers.remove(context.fPlayer); + for (FPlayer fp : informTheseFPlayers) { + fp.msg(TL.COMMAND_UNCLAIM_UNCLAIMEDAMOUNT, context.fPlayer.describeTo(fp, true), unclaimed); + } + + context.fPlayer.msg(TL.COMMAND_UNCLAIM_UNCLAIMEDAMOUNT, context.fPlayer.describeTo(context.fPlayer, true), unclaimed); + } + super.finish(); + } + }; + } + } + + private boolean unClaim(FLocation target, CommandContext context, Faction faction) { + return this.unClaim(target, context, faction, null); + } + + private boolean unClaim(FLocation target, CommandContext context, Faction faction, SpiralTask spiralTask) { + Faction targetFaction = Board.getInstance().getFactionAt(target); + + if (!targetFaction.equals(faction)) { + context.msg(TL.COMMAND_UNCLAIM_WRONGFACTIONOTHER); + return false; + } + + if (targetFaction.isSafeZone()) { + if (Permission.MANAGE_SAFE_ZONE.has(context.sender)) { + Board.getInstance().removeAt(target); + if(spiralTask == null){ + context.msg(TL.COMMAND_UNCLAIM_SAFEZONE_SUCCESS); + } + + if (FactionsPlugin.getInstance().conf().logging().isLandUnclaims()) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); + } + return true; + } else { + context.msg(TL.COMMAND_UNCLAIM_SAFEZONE_NOPERM); + return false; + } + } else if (targetFaction.isWarZone()) { + if (Permission.MANAGE_WAR_ZONE.has(context.sender)) { + Board.getInstance().removeAt(target); + if(spiralTask == null){ + context.msg(TL.COMMAND_UNCLAIM_WARZONE_SUCCESS); + } + + if (FactionsPlugin.getInstance().conf().logging().isLandUnclaims()) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); + } + return true; + } else { + context.msg(TL.COMMAND_UNCLAIM_WARZONE_NOPERM); + return false; + } + } + + if (context.fPlayer.isAdminBypassing()) { + LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, context.fPlayer); + Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); + if (unclaimEvent.isCancelled()) { + return false; + } + + Board.getInstance().removeAt(target); + + if(spiralTask == null){ + targetFaction.msg(TL.COMMAND_UNCLAIM_UNCLAIMED, context.fPlayer.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_UNCLAIM_UNCLAIMS); + } + + if (FactionsPlugin.getInstance().conf().logging().isLandUnclaims()) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); + } + + return true; + } + + if (!context.assertHasFaction()) { + return false; + } + + if (!targetFaction.hasAccess(context.fPlayer, PermissibleAction.TERRITORY)) { + context.msg(TL.CLAIM_CANTCLAIM, targetFaction.describeTo(context.fPlayer)); + return false; + } + + if (context.faction != targetFaction) { + context.msg(TL.COMMAND_UNCLAIM_WRONGFACTION); + return false; + } + + LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, context.fPlayer); + Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); + if (unclaimEvent.isCancelled()) { + return false; + } + + if (Econ.shouldBeUsed()) { + double refund = Econ.calculateClaimRefund(context.faction.getLandRounded()); + + if (FactionsPlugin.getInstance().conf().economy().isBankEnabled() && FactionsPlugin.getInstance().conf().economy().isBankFactionPaysLandCosts()) { + if (!Econ.modifyMoney(context.faction, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { + return false; + } + } else { + if (!Econ.modifyMoney(context.fPlayer, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { + return false; + } + } + } + + Board.getInstance().removeAt(target); + if(spiralTask == null){ + context.faction.msg(TL.COMMAND_UNCLAIM_FACTIONUNCLAIMED, context.fPlayer.describeTo(context.faction, true)); + } + + if (FactionsPlugin.getInstance().conf().logging().isLandUnclaims()) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); + } + + return true; + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UNCLAIM_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java new file mode 100644 index 0000000..6117f13 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java @@ -0,0 +1,65 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.event.LandUnclaimAllEvent; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +public class CmdUnclaimall extends FCommand { + + public CmdUnclaimall() { + this.aliases.add("unclaimall"); + this.aliases.add("declaimall"); + + this.requirements = new CommandRequirements.Builder(Permission.UNCLAIM_ALL) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + if (!context.faction.hasAccess(context.fPlayer, PermissibleAction.TERRITORY)) { + context.msg(TL.CLAIM_CANTCLAIM, context.faction.describeTo(context.fPlayer)); + return; + } + + if (Econ.shouldBeUsed()) { + double refund = Econ.calculateTotalLandRefund(context.faction.getLandRounded()); + if (FactionsPlugin.getInstance().conf().economy().isBankEnabled() && FactionsPlugin.getInstance().conf().economy().isBankFactionPaysLandCosts()) { + if (!Econ.modifyMoney(context.faction, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + return; + } + } else { + if (!Econ.modifyMoney(context.fPlayer, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + return; + } + } + } + + LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(context.faction, context.fPlayer); + Bukkit.getServer().getPluginManager().callEvent(unclaimAllEvent); + if (unclaimAllEvent.isCancelled()) { + return; + } + + Board.getInstance().unclaimAll(context.faction.getId()); + context.faction.msg(TL.COMMAND_UNCLAIMALL_UNCLAIMED, context.fPlayer.describeTo(context.faction, true)); + + if (FactionsPlugin.getInstance().conf().logging().isLandUnclaims()) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIMALL_LOG.format(context.fPlayer.getName(), context.faction.getTag())); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UNCLAIMALL_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdWarunclaimall.java b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdWarunclaimall.java new file mode 100644 index 0000000..1716010 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/claim/CmdWarunclaimall.java @@ -0,0 +1,53 @@ +package com.massivecraft.factions.cmd.claim; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; +import org.bukkit.World; + +public class CmdWarunclaimall extends FCommand { + + public CmdWarunclaimall() { + this.aliases.add("warunclaimall"); + this.aliases.add("wardeclaimall"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("world", "all"); + + this.requirements = new CommandRequirements.Builder(Permission.MANAGE_WAR_ZONE).build(); + } + + @Override + public void perform(CommandContext context) { + String worldName = context.argAsString(0); + World world = null; + + if (worldName != null) { + world = Bukkit.getWorld(worldName); + } + + String id = Factions.getInstance().getWarZone().getId(); + + if (world == null) { + Board.getInstance().unclaimAll(id); + } else { + Board.getInstance().unclaimAllInWorld(id, world); + } + + if (FactionsPlugin.getInstance().conf().logging().isLandUnclaims()) { + FactionsPlugin.getInstance().log(TL.COMMAND_WARUNCLAIMALL_LOG.format(context.fPlayer.getName())); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_WARUNCLAIMALL_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRGet.java b/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRGet.java new file mode 100644 index 0000000..c263aca --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRGet.java @@ -0,0 +1,46 @@ +package com.massivecraft.factions.cmd.dtr; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.landraidcontrol.DTRControl; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdDTRGet extends FCommand { + public CmdDTRGet() { + super(); + this.aliases.add("get"); + this.optionalArgs.put("faction", "yours"); + + this.requirements = new CommandRequirements.Builder(Permission.DTR).noDisableOnLock().build(); + } + + @Override + public void perform(CommandContext context) { + Faction target = context.argAsFaction(0, context.faction); + if (target == null) { + return; + } + + if (target != context.faction && !Permission.DTR_ANY.has(context.sender, true)) { + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(FactionsPlugin.getInstance().conf().economy().getCostDTR(), TL.COMMAND_DTR_TOSHOW, TL.COMMAND_DTR_FORSHOW)) { + return; + } + + DTRControl dtr = (DTRControl) FactionsPlugin.getInstance().getLandRaidControl(); + context.msg(TL.COMMAND_DTR_DTR, target.describeTo(context.fPlayer, false), DTRControl.round(target.getDTR()), DTRControl.round(dtr.getMaxDTR(target))); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DTR_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRModify.java b/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRModify.java new file mode 100644 index 0000000..1f3ca01 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRModify.java @@ -0,0 +1,44 @@ +package com.massivecraft.factions.cmd.dtr; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.landraidcontrol.DTRControl; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdDTRModify extends FCommand { + + public CmdDTRModify() { + super(); + this.aliases.add("modify"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("amount"); + + this.requirements = new CommandRequirements.Builder(Permission.MODIFY_DTR).build(); + } + + @Override + public void perform(CommandContext context) { + Faction target = context.argAsFaction(0, null); + if (target == null) { + return; + } + + double amount = context.argAsDouble(1, 0.0D); + if (amount == 0.0D) { + return; + } + + DTRControl dtr = (DTRControl) FactionsPlugin.getInstance().getLandRaidControl(); + target.setDTR(Math.max(Math.min(target.getDTR() + amount, dtr.getMaxDTR(target)), FactionsPlugin.getInstance().conf().factions().landRaidControl().dtr().getMinDTR())); + context.msg(TL.COMMAND_DTR_MODIFY_DONE, target.describeTo(context.fPlayer, false), DTRControl.round(target.getDTR())); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DTR_MODIFY_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRResetAll.java b/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRResetAll.java new file mode 100644 index 0000000..ccb69da --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/dtr/CmdDTRResetAll.java @@ -0,0 +1,36 @@ +package com.massivecraft.factions.cmd.dtr; + +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.landraidcontrol.DTRControl; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdDTRResetAll extends FCommand { + + public CmdDTRResetAll() { + super(); + this.aliases.add("resetall"); + + this.requirements = new CommandRequirements.Builder(Permission.MODIFY_DTR).build(); + } + + @Override + public void perform(CommandContext context) { + if (context.fPlayer != null) { + return; + } + + DTRControl dtr = (DTRControl) FactionsPlugin.getInstance().getLandRaidControl(); + Factions.getInstance().getAllFactions().forEach(target -> target.setDTR(dtr.getMaxDTR(target))); + context.msg(TL.COMMAND_DTR_MODIFY_DONE, "EVERYONE", "MAX"); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DTR_MODIFY_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/missions/CmdMission.java b/Factions/src/main/java/com/massivecraft/factions/cmd/missions/CmdMission.java new file mode 100644 index 0000000..9492836 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/missions/CmdMission.java @@ -0,0 +1,30 @@ +package com.massivecraft.factions.cmd.missions; + +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCmdRoot; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdMission extends FCommand { + public CmdMission(){ + super(); + + this.aliases.add("missions"); + this.aliases.add("mission"); + + this.requirements = new CommandRequirements.Builder(Permission.MISSIONS).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + FCmdRoot.getInstance().cmdAutoHelp.execute(context); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MISSIONS_USAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoney.java b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoney.java new file mode 100644 index 0000000..607e428 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoney.java @@ -0,0 +1,34 @@ +package com.massivecraft.factions.cmd.money; + +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.FCmdRoot; +import com.massivecraft.factions.util.TL; + +public class CmdMoney extends MoneyCommand { + + public CmdMoney() { + super(); + this.aliases.add("money"); + + this.helpLong.add(plugin.txt().parseTags(TL.COMMAND_MONEY_LONG.toString())); + + this.addSubCommand(new CmdMoneyBalance()); + this.addSubCommand(new CmdMoneyDeposit()); + this.addSubCommand(new CmdMoneyWithdraw()); + this.addSubCommand(new CmdMoneyTransferFf()); + this.addSubCommand(new CmdMoneyTransferFp()); + this.addSubCommand(new CmdMoneyTransferPf()); + } + + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + FCmdRoot.getInstance().cmdAutoHelp.execute(context); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEY_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyBalance.java b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyBalance.java new file mode 100644 index 0000000..7eff6d0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyBalance.java @@ -0,0 +1,51 @@ +package com.massivecraft.factions.cmd.money; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdMoneyBalance extends MoneyCommand { + + public CmdMoneyBalance() { + super(); + this.aliases.add("b"); + this.aliases.add("balance"); + + //this.requiredArgs.add(""); + this.optionalArgs.put("faction", "yours"); + + this.requirements = new CommandRequirements.Builder(Permission.MONEY_BALANCE).build(); + + this.setHelpShort(TL.COMMAND_MONEYBALANCE_SHORT.toString()); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.faction; + if (context.argIsSet(0)) { + faction = context.argAsFaction(0); + } + + if (faction == null) { + return; + } + if (faction != context.faction && !Permission.MONEY_BALANCE_ANY.has(context.sender, true)) { + return; + } + + if (context.fPlayer != null) { + Econ.sendBalanceInfo(context.fPlayer, faction); + } else { + Econ.sendBalanceInfo(context.sender, faction); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYBALANCE_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyDeposit.java b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyDeposit.java new file mode 100644 index 0000000..8c6feb4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyDeposit.java @@ -0,0 +1,47 @@ +package com.massivecraft.factions.cmd.money; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + + +public class CmdMoneyDeposit extends MoneyCommand { + + public CmdMoneyDeposit() { + super(); + this.aliases.add("d"); + this.aliases.add("deposit"); + + this.requiredArgs.add("amount"); + this.optionalArgs.put("faction", "yours"); + + this.requirements = new CommandRequirements.Builder(Permission.MONEY_DEPOSIT) + .memberOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator faction = context.argAsFaction(1, context.faction); + if (faction == null) { + return; + } + boolean success = Econ.transferMoney(context.fPlayer, context.fPlayer, faction, amount); + + if (success && FactionsPlugin.getInstance().conf().logging().isMoneyTransactions()) { + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt().parse(TL.COMMAND_MONEYDEPOSIT_DEPOSITED.toString(), context.fPlayer.getName(), Econ.moneyString(amount), faction.describeTo(null)))); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYDEPOSIT_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferFf.java b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferFf.java new file mode 100644 index 0000000..f3b2e0d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferFf.java @@ -0,0 +1,50 @@ +package com.massivecraft.factions.cmd.money; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + + +public class CmdMoneyTransferFf extends MoneyCommand { + + public CmdMoneyTransferFf() { + this.aliases.add("ff"); + + this.requiredArgs.add("amount"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("faction"); + + this.requirements = new CommandRequirements.Builder(Permission.MONEY_F2F).build(); + } + + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator from = context.argAsFaction(1); + if (from == null) { + return; + } + EconomyParticipator to = context.argAsFaction(2); + if (to == null) { + return; + } + + boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); + + if (success && FactionsPlugin.getInstance().conf().logging().isMoneyTransactions()) { + String name = context.sender instanceof Player ? context.fPlayer.getName() : context.sender.getName(); + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt().parse(TL.COMMAND_MONEYTRANSFERFF_TRANSFER.toString(), name, Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYTRANSFERFF_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferFp.java b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferFp.java new file mode 100644 index 0000000..ed8560b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferFp.java @@ -0,0 +1,48 @@ +package com.massivecraft.factions.cmd.money; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + + +public class CmdMoneyTransferFp extends MoneyCommand { + + public CmdMoneyTransferFp() { + this.aliases.add("fp"); + + this.requiredArgs.add("amount"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("player"); + + this.requirements = new CommandRequirements.Builder(Permission.MONEY_F2P).build(); + } + + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator from = context.argAsFaction(1); + if (from == null) { + return; + } + EconomyParticipator to = context.argAsBestFPlayerMatch(2); + if (to == null) { + return; + } + + boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); + + if (success && FactionsPlugin.getInstance().conf().logging().isMoneyTransactions()) { + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt().parse(TL.COMMAND_MONEYTRANSFERFP_TRANSFER.toString(), context.fPlayer.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYTRANSFERFP_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferPf.java b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferPf.java new file mode 100644 index 0000000..72de48a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyTransferPf.java @@ -0,0 +1,48 @@ +package com.massivecraft.factions.cmd.money; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + + +public class CmdMoneyTransferPf extends MoneyCommand { + + public CmdMoneyTransferPf() { + this.aliases.add("pf"); + + this.requiredArgs.add("amount"); + this.requiredArgs.add("player"); + this.requiredArgs.add("faction"); + + this.requirements = new CommandRequirements.Builder(Permission.MONEY_P2F).build(); + } + + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator from = context.argAsBestFPlayerMatch(1); + if (from == null) { + return; + } + EconomyParticipator to = context.argAsFaction(2); + if (to == null) { + return; + } + + boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); + + if (success && FactionsPlugin.getInstance().conf().logging().isMoneyTransactions()) { + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt().parse(TL.COMMAND_MONEYTRANSFERPF_TRANSFER.toString(), context.fPlayer.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYTRANSFERPF_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyWithdraw.java b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyWithdraw.java new file mode 100644 index 0000000..717151d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/money/CmdMoneyWithdraw.java @@ -0,0 +1,52 @@ +package com.massivecraft.factions.cmd.money; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + + +public class CmdMoneyWithdraw extends MoneyCommand { + + public CmdMoneyWithdraw() { + this.aliases.add("w"); + this.aliases.add("withdraw"); + + this.requiredArgs.add("amount"); + this.optionalArgs.put("faction", "yours"); + + this.requirements = new CommandRequirements.Builder(Permission.MONEY_F2P) + .playerOnly() + .build(); + } + + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator faction = context.argAsFaction(1, context.faction); + if (faction == null) { + return; + } + + if (!context.faction.hasAccess(context.fPlayer, PermissibleAction.ECONOMY)) { + context.msg(TL.GENERIC_NOPERMISSION, "withdraw"); + return; + } + + boolean success = Econ.transferMoney(context.fPlayer, faction, context.fPlayer, amount); + + if (success && FactionsPlugin.getInstance().conf().logging().isMoneyTransactions()) { + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt().parse(TL.COMMAND_MONEYWITHDRAW_WITHDRAW.toString(), context.fPlayer.getName(), Econ.moneyString(amount), faction.describeTo(null)))); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYWITHDRAW_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/money/MoneyCommand.java b/Factions/src/main/java/com/massivecraft/factions/cmd/money/MoneyCommand.java new file mode 100644 index 0000000..5d4c0d5 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/money/MoneyCommand.java @@ -0,0 +1,27 @@ +package com.massivecraft.factions.cmd.money; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.FCommand; + +public abstract class MoneyCommand extends FCommand { + + public boolean isEnabled(CommandContext context) { + if (!super.isEnabled(context)) { + return false; + } + + if (!FactionsPlugin.getInstance().conf().economy().isEnabled()) { + context.msg("Faction economy features are disabled on this server."); + return false; + } + + if (!FactionsPlugin.getInstance().conf().economy().isBankEnabled()) { + context.msg("The faction bank system is disabled on this server."); + return false; + } + + return true; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationAlly.java b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationAlly.java new file mode 100644 index 0000000..f48c0d1 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationAlly.java @@ -0,0 +1,10 @@ +package com.massivecraft.factions.cmd.relations; + +import com.massivecraft.factions.perms.Relation; + +public class CmdRelationAlly extends FRelationCommand { + + public CmdRelationAlly() { + super(Relation.ALLY, "ally"); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationEnemy.java b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationEnemy.java new file mode 100644 index 0000000..7935643 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationEnemy.java @@ -0,0 +1,10 @@ +package com.massivecraft.factions.cmd.relations; + +import com.massivecraft.factions.perms.Relation; + +public class CmdRelationEnemy extends FRelationCommand { + + public CmdRelationEnemy() { + super(Relation.ENEMY, "enemy"); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationNeutral.java b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationNeutral.java new file mode 100644 index 0000000..17ad485 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationNeutral.java @@ -0,0 +1,10 @@ +package com.massivecraft.factions.cmd.relations; + +import com.massivecraft.factions.perms.Relation; + +public class CmdRelationNeutral extends FRelationCommand { + + public CmdRelationNeutral() { + super(Relation.NEUTRAL, "neutral"); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationTruce.java b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationTruce.java new file mode 100644 index 0000000..ef67ac2 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/CmdRelationTruce.java @@ -0,0 +1,10 @@ +package com.massivecraft.factions.cmd.relations; + +import com.massivecraft.factions.perms.Relation; + +public class CmdRelationTruce extends FRelationCommand { + + public CmdRelationTruce() { + super(Relation.TRUCE, "truce"); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/relations/FRelationCommand.java b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/FRelationCommand.java new file mode 100644 index 0000000..ddfc878 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/relations/FRelationCommand.java @@ -0,0 +1,127 @@ +package com.massivecraft.factions.cmd.relations; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.event.FactionRelationEvent; +import com.massivecraft.factions.event.FactionRelationWishEvent; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.scoreboards.FTeamWrapper; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; + +public abstract class FRelationCommand extends FCommand { + + public Relation targetRelation; + + public FRelationCommand(Relation targetRelation, String alias) { + super(); + this.targetRelation = targetRelation; + this.aliases.add(alias); + this.requiredArgs.add("faction tag"); + + this.requirements = new CommandRequirements.Builder(Permission.RELATION) + .memberOnly() + .withRole(Role.MODERATOR) + .build(); + } + + @Override + public void perform(CommandContext context) { + Faction them = context.argAsFaction(0); + if (them == null) { + return; + } + + if (!them.isNormal()) { + context.msg(TL.COMMAND_RELATIONS_ALLTHENOPE); + return; + } + + if (them == context.faction) { + context.msg(TL.COMMAND_RELATIONS_MORENOPE); + return; + } + + if (context.faction.getRelationWish(them) == targetRelation) { + context.msg(TL.COMMAND_RELATIONS_ALREADYINRELATIONSHIP, them.getTag()); + return; + } + + if (hasMaxRelations(them, targetRelation, context)) { + // We message them down there with the count. + return; + } + Relation oldRelation = context.faction.getRelationTo(them, true); + FactionRelationWishEvent wishEvent = new FactionRelationWishEvent(context.fPlayer, context.faction, them, oldRelation, targetRelation); + Bukkit.getPluginManager().callEvent(wishEvent); + if (wishEvent.isCancelled()) { + return; + } + + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(targetRelation.getRelationCost(), TL.COMMAND_RELATIONS_TOMARRY, TL.COMMAND_RELATIONS_FORMARRY)) { + return; + } + + // try to set the new relation + context.faction.setRelationWish(them, targetRelation); + Relation currentRelation = context.faction.getRelationTo(them, true); + ChatColor currentRelationColor = currentRelation.getColor(); + + // if the relation change was successful + if (targetRelation.value == currentRelation.value) { + // trigger the faction relation event + FactionRelationEvent relationEvent = new FactionRelationEvent(context.faction, them, oldRelation, currentRelation); + Bukkit.getServer().getPluginManager().callEvent(relationEvent); + + them.msg(TL.COMMAND_RELATIONS_MUTUAL, currentRelationColor + targetRelation.getTranslation(), currentRelationColor + context.faction.getTag()); + context.faction.msg(TL.COMMAND_RELATIONS_MUTUAL, currentRelationColor + targetRelation.getTranslation(), currentRelationColor + them.getTag()); + } else { + // inform the other faction of your request + them.msg(TL.COMMAND_RELATIONS_PROPOSAL_1, currentRelationColor + context.faction.getTag(), targetRelation.getColor() + targetRelation.getTranslation()); + them.msg(TL.COMMAND_RELATIONS_PROPOSAL_2, FactionsPlugin.getInstance().conf().getCommandBase().get(0), targetRelation, context.faction.getTag()); + context.faction.msg(TL.COMMAND_RELATIONS_PROPOSAL_SENT, currentRelationColor + them.getTag(), "" + targetRelation.getColor() + targetRelation); + } + + if (!targetRelation.isNeutral() && them.isPeaceful()) { + them.msg(TL.COMMAND_RELATIONS_PEACEFUL); + context.faction.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); + } + + if (!targetRelation.isNeutral() && context.faction.isPeaceful()) { + them.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); + context.faction.msg(TL.COMMAND_RELATIONS_PEACEFUL); + } + + FTeamWrapper.updatePrefixes(context.faction); + FTeamWrapper.updatePrefixes(them); + } + + private boolean hasMaxRelations(Faction them, Relation targetRelation, CommandContext context) { + if (FactionsPlugin.getInstance().conf().factions().maxRelations().isEnabled()) { + int max = targetRelation.getMax(); + if (max != -1) { + if (context.faction.getRelationCount(targetRelation) >= max) { + context.msg(TL.COMMAND_RELATIONS_EXCEEDS_ME, max, targetRelation.getPluralTranslation()); + return true; + } + if (them.getRelationCount(targetRelation) >= max) { + context.msg(TL.COMMAND_RELATIONS_EXCEEDS_THEY, max, targetRelation.getPluralTranslation()); + return true; + } + } + } + return false; + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_RELATIONS_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/role/CmdDemote.java b/Factions/src/main/java/com/massivecraft/factions/cmd/role/CmdDemote.java new file mode 100644 index 0000000..bd48541 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/role/CmdDemote.java @@ -0,0 +1,9 @@ +package com.massivecraft.factions.cmd.role; + +public class CmdDemote extends FPromoteCommand { + + public CmdDemote() { + aliases.add("demote"); + this.relative = -1; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/role/CmdPromote.java b/Factions/src/main/java/com/massivecraft/factions/cmd/role/CmdPromote.java new file mode 100644 index 0000000..59e696a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/role/CmdPromote.java @@ -0,0 +1,10 @@ +package com.massivecraft.factions.cmd.role; + +public class CmdPromote extends FPromoteCommand { + + public CmdPromote() { + aliases.add("promote"); + aliases.add("promo"); + this.relative = 1; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/role/FPromoteCommand.java b/Factions/src/main/java/com/massivecraft/factions/cmd/role/FPromoteCommand.java new file mode 100644 index 0000000..482f436 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/role/FPromoteCommand.java @@ -0,0 +1,86 @@ +package com.massivecraft.factions.cmd.role; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.CC; +import com.massivecraft.factions.util.TL; + +public class FPromoteCommand extends FCommand { + + public int relative = 0; + + public FPromoteCommand() { + super(); + + this.requiredArgs.add("player"); + + this.requirements = new CommandRequirements.Builder(Permission.PROMOTE) + .memberOnly() + .withAction(PermissibleAction.PROMOTE) + .build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0); + if (target == null) { + // context.msg(TL.GENERIC_NOPLAYERFOUND, context.argAsString(0)); + return; + } + + if(target.getRole() == Role.ALT){ + context.msg(TL.COMMAND_PROMOTE_ISALT); + return; + } + + if (!target.getFaction().equals(context.faction)) { + context.msg(TL.COMMAND_PROMOTE_WRONGFACTION, target.getName()); + return; + } + + Role current = target.getRole(); + Role promotion = Role.getRelative(current, +relative); + + if (promotion == null) { + context.msg(TL.COMMAND_PROMOTE_NOTTHATPLAYER); + return; + } + + // Don't allow people to promote people to their same or higher rnak. + if (context.fPlayer.getRole().value <= promotion.value) { + context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); + return; + } + + if (context.fPlayer.getRole().value == target.getRole().value) { + context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); + return; + } + + if (target.getRole() == Role.RECRUIT && promotion.value < target.getRole().value) { + context.sendMessage(CC.translate("&c&l(!)&c This player is already the lowest role")); + return; + } + + String action = relative > 0 ? TL.COMMAND_PROMOTE_PROMOTED.toString() : TL.COMMAND_PROMOTE_DEMOTED.toString(); + + // Success! + target.setRole(promotion); + if (target.isOnline()) { + target.msg(TL.COMMAND_PROMOTE_TARGET, action, promotion.nicename); + } + + context.msg(TL.COMMAND_PROMOTE_SUCCESS, action, target.getName(), promotion.nicename); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PROMOTE_DESCRIPTION; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrike.java b/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrike.java new file mode 100644 index 0000000..91cee7e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrike.java @@ -0,0 +1,32 @@ +package com.massivecraft.factions.cmd.strikes; + +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.FCmdRoot; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.util.TL; + +public class CmdStrike extends FCommand { + + public CmdStrike(){ + super(); + + this.addSubCommand(new CmdStrikeGive()); + this.addSubCommand(new CmdStrikeInfo()); + this.addSubCommand(new CmdStrikeTake()); + + this.aliases.add("strike"); + + this.aliases.add("strikes"); + } + + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + FCmdRoot.getInstance().cmdAutoHelp.execute(context); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKE_USAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeGive.java b/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeGive.java new file mode 100644 index 0000000..01fc1c0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeGive.java @@ -0,0 +1,47 @@ +package com.massivecraft.factions.cmd.strikes; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdStrikeGive extends FCommand { + public CmdStrikeGive(){ + super(); + this.aliases.add("give"); + this.aliases.add("add"); + + this.requiredArgs.add("faction"); + + this.requiredArgs.add("reason"); + + this.requirements = new CommandRequirements.Builder(Permission.STRIKE_MANAGE).noErrorOnManyArgs().build(); + } + + @Override + public void perform(CommandContext context) { + Faction toStrike = context.argAsFaction(0); + + if(toStrike == null){ + return; + } + + StringBuilder stringBuilder = new StringBuilder(); + + for(int i = 1; i < context.args.size(); i++){ + stringBuilder.append(context.args.get(i)).append(" "); + } + + String trim = stringBuilder.toString().trim(); + toStrike.addStrike(trim, System.currentTimeMillis()); + + if(context.fPlayer != null)context.fPlayer.msg(TL.COMMAND_STRIKE_GIVE_SUCCESS, toStrike.describeTo(context.fPlayer), trim); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKE_GIVE_USAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeInfo.java b/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeInfo.java new file mode 100644 index 0000000..640c053 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeInfo.java @@ -0,0 +1,70 @@ +package com.massivecraft.factions.cmd.strikes; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.StrikeInfo; +import com.massivecraft.factions.util.TL; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.List; + +public class CmdStrikeInfo extends FCommand { + + public CmdStrikeInfo(){ + super(); + this.aliases.add("list"); + this.aliases.add("info"); + this.aliases.add("view"); + + this.optionalArgs.put("faction", "your faction"); + + this.requirements = new CommandRequirements.Builder(Permission.STRIKE_VIEW).playerOnly().build(); + } + + @Override + public void perform(CommandContext context) { + FPlayer fPlayer = context.fPlayer; + + Faction faction = context.args.size() != 0 && Permission.STRIKE_MANAGE.has(fPlayer.getPlayer()) ? context.argAsFaction(0) : context.fPlayer.getFaction(); + + if(faction == null){ + if(fPlayer.hasFaction()){ + fPlayer.msg(TL.GENERIC_MEMBERONLY); + }else{ + fPlayer.msg(TL.COMMAND_STRIKE_LIST_NOFACTION); + } + return; + } + + ZonedDateTime now = ZonedDateTime.now(ZoneId.of(FactionsPlugin.getInstance().conf().getTimeZone())); + + List strikes = faction.getStrikes(); + if(strikes == null || strikes.isEmpty()){ + fPlayer.msg(TL.COMMAND_STRIKE_LIST_BLAMELESS, faction.describeTo(fPlayer)); + return; + } + + fPlayer.msg(TL.COMMAND_STRIKE_LIST_HEADER, faction.describeTo(fPlayer)); + + int i = 1; + + for(StrikeInfo strikeInfo : strikes){ + ZonedDateTime wayBackWhen = now.minus(System.currentTimeMillis() - strikeInfo.getGivenAt(), ChronoUnit.MILLIS); + + fPlayer.msg(TL.COMMAND_STRIKE_LIST_FORMAT, i++, strikeInfo.getStrikeReason(), wayBackWhen.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKE_LIST_USAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeTake.java b/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeTake.java new file mode 100644 index 0000000..8ef2014 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/strikes/CmdStrikeTake.java @@ -0,0 +1,51 @@ +package com.massivecraft.factions.cmd.strikes; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdStrikeTake extends FCommand { + public CmdStrikeTake(){ + super(); + + this.aliases.add("take"); + this.aliases.add("remove"); + + this.requiredArgs.add("faction"); + + this.requiredArgs.add("index"); + + this.requirements = new CommandRequirements.Builder(Permission.STRIKE_MANAGE).build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.argAsFaction(0); + + int index = context.argAsInt(1); + + if(index < 0){ + return; + } + + if(faction == null){ + return; + } + + boolean success = faction.takeStrike(index - 1); + + if(!success){ + if(context.fPlayer != null)context.fPlayer.msg(TL.COMMAND_STRIKE_TAKE_DOESNTEXIST); + }else{ + if(context.fPlayer != null)context.fPlayer.msg(TL.COMMAND_STRIKE_TAKE_SUCCESS, faction.describeTo(context.fPlayer)); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKE_TAKE_USAGE; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTAdminSet.java b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTAdminSet.java new file mode 100644 index 0000000..0333f7a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTAdminSet.java @@ -0,0 +1,36 @@ +package com.massivecraft.factions.cmd.tnt; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +public class CmdTNTAdminSet extends FCommand { + public CmdTNTAdminSet(){ + super(); + this.aliases.add("adminset"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("amount"); + + this.requirements = new CommandRequirements.Builder(Permission.TNT_ADMIN).playerOnly().build(); + } + + @Override + public void perform(CommandContext context) { + Faction faction = context.argAsFaction(0); + if(faction == null)return; + int amount = context.argAsInt(1); + if(amount < 0)return; + + faction.setTNTBank(amount); + + context.msg(TL.COMMAND_TNT_ADMINSET_DESCRIPTION, faction.describeTo(context.fPlayer), amount + ""); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNT_ADMINSET_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTDeposit.java b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTDeposit.java new file mode 100644 index 0000000..48370af --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTDeposit.java @@ -0,0 +1,77 @@ +package com.massivecraft.factions.cmd.tnt; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Map; + +public class CmdTNTDeposit extends FCommand { + public CmdTNTDeposit() { + super(); + this.aliases.add("deposit"); + this.aliases.add("d"); + this.requiredArgs.add("amount"); + + this.requirements = new CommandRequirements.Builder(Permission.TNT_DEPOSIT).withAction(PermissibleAction.TNTDEPOSIT).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + Player player = context.player; + if (!context.faction.equals(Board.getInstance().getFactionAt(new FLocation(player.getLocation())))) { + context.msg(TL.COMMAND_TNT_TERRITORYONLY); + return; + } + int amount = context.argAsInt(0, -1); + if (amount <= 0) { + context.msg(TL.COMMAND_TNT_DEPOSIT_FAIL_POSITIVE, amount); + return; + } + + if (!player.getInventory().containsAtLeast(new ItemStack(Material.TNT), amount)) { + context.msg(TL.COMMAND_TNT_DEPOSIT_FAIL_NOTENOUGH, amount); + return; + } + + int max = context.faction.getMaxTNT(); + if (context.faction.getTNTBank() + amount > max) { + if (max == context.faction.getTNTBank()) { + context.msg(TL.COMMAND_TNT_DEPOSIT_FAIL_FULL, max); + return; + } + amount = max - context.faction.getTNTBank(); + } + int current = amount; + Map all = player.getInventory().all(Material.TNT); + for (Map.Entry entry : all.entrySet()) { + final int count = entry.getValue().getAmount(); + final int newCount = Math.max(0, count - current); + current -= (count - newCount); + if (newCount == 0) { + player.getInventory().setItem(entry.getKey(), null); + } else { + player.getInventory().getItem(entry.getKey()).setAmount(newCount); + } + if (current == 0) { + break; + } + } + context.faction.setTNTBank(context.faction.getTNTBank() + amount); + context.msg(TL.COMMAND_TNT_DEPOSIT_SUCCESS, context.faction.getTNTBank()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNT_DEPOSIT_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTFill.java b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTFill.java new file mode 100644 index 0000000..eddbdf9 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTFill.java @@ -0,0 +1,129 @@ +package com.massivecraft.factions.cmd.tnt; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.Pair; +import com.massivecraft.factions.util.TL; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Dispenser; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; + +public class CmdTNTFill extends FCommand { + public CmdTNTFill() { + super(); + this.aliases.add("fill"); + this.aliases.add("f"); + this.requiredArgs.add("radius"); + this.requiredArgs.add("amount"); + + this.requirements = new CommandRequirements.Builder(Permission.TNT_FILL).withAction(PermissibleAction.TNTWITHDRAW).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + if (!context.faction.equals(Board.getInstance().getFactionAt(new FLocation(context.player.getLocation())))) { + context.msg(TL.COMMAND_TNT_TERRITORYONLY); + return; + } + final int radius = context.argAsInt(0, -1); + final int amount = context.argAsInt(1, -1); + + if (radius <= 0 || amount <= 0) { + context.msg(TL.COMMAND_TNT_FILL_FAIL_POSITIVE); + return; + } + + if (radius > FactionsPlugin.getInstance().conf().commands().tnt().getMaxRadius()) { + context.msg(TL.COMMAND_TNT_FILL_FAIL_MAXRADIUS, radius, FactionsPlugin.getInstance().conf().commands().tnt().getMaxRadius()); + return; + } + + List list = getDispensers(context.player.getLocation(), radius, context.faction.getId()); + + if (amount * list.size() > context.faction.getTNTBank()) { + context.msg(TL.COMMAND_TNT_FILL_FAIL_NEEDMORE, amount * list.size(), context.faction.getTNTBank() / list.size()); + return; + } + + int totalCount = list.size(); + + int remaining = amount * totalCount; + int dispenserCount = 0; + + Iterator iterator = list.iterator(); + while (iterator.hasNext() && remaining >= amount) { + int left = getCount(iterator.next().getInventory().addItem(getStacks(amount)).values()); + remaining -= amount - left; + if (((amount - left) > 0)) { + dispenserCount++; + } + if (left > 0) { + iterator.remove(); + } + } + + context.faction.setTNTBank(context.faction.getTNTBank() - (amount * totalCount) + remaining); + + context.msg(TL.COMMAND_TNT_FILL_MESSAGE, (amount * totalCount) - remaining, dispenserCount, context.faction.getTNTBank()); + } + + static ItemStack[] getStacks(int count) { + if (count < 65) { + return new ItemStack[]{new ItemStack(Material.TNT, count)}; + } else { + List stack = new ArrayList<>(); + while (count > 0) { + stack.add(new ItemStack(Material.TNT, Math.min(64, count))); + count -= Math.min(64, count); + } + return stack.toArray(new ItemStack[0]); + } + } + + static List getDispensers(Location location, int radius, String id) { + List list = new ArrayList<>(); + for (int x = location.getBlockX() - radius; x <= location.getBlockX() + radius; x++) { + for (int y = location.getBlockY() - radius; y <= location.getBlockY() + radius; y++) { + for (int z = location.getBlockZ() - radius; z <= location.getBlockZ() + radius; z++) { + Block block = location.getWorld().getBlockAt(x, y, z); + if (!Board.getInstance().getIdAt(new FLocation(block)).equals(id)) { + continue; + } + if (block.getType() == Material.DISPENSER) { + list.add((Dispenser) block.getState()); + } + } + } + } + return list; + } + + static int getCount(Collection items) { + int count = 0; + for (ItemStack stack : items) { + count += stack.getAmount(); + } + return count; + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNT_FILL_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTInfo.java b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTInfo.java new file mode 100644 index 0000000..5954975 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTInfo.java @@ -0,0 +1,29 @@ +package com.massivecraft.factions.cmd.tnt; + +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; + +import java.text.NumberFormat; + +public class CmdTNTInfo extends FCommand { + public CmdTNTInfo() { + super(); + this.aliases.add("info"); + this.aliases.add("status"); + + this.requirements = new CommandRequirements.Builder(Permission.TNT_INFO).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + context.msg(TL.COMMAND_TNT_INFO_MESSAGE, NumberFormat.getIntegerInstance().format(context.faction.getTNTBank()), NumberFormat.getIntegerInstance().format(context.faction.getMaxTNT())); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNT_INFO_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTSiphon.java b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTSiphon.java new file mode 100644 index 0000000..1775e0c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTSiphon.java @@ -0,0 +1,94 @@ +package com.massivecraft.factions.cmd.tnt; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Material; +import org.bukkit.block.Dispenser; + +import java.util.List; + +public class CmdTNTSiphon extends FCommand { + public CmdTNTSiphon() { + super(); + this.aliases.add("siphon"); + this.aliases.add("s"); + this.aliases.add("unfill"); + this.requiredArgs.add("radius"); + this.optionalArgs.put("amount", "all"); + + this.requirements = new CommandRequirements.Builder(Permission.TNT_SIPHON).withAction(PermissibleAction.TNTDEPOSIT).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + if (!context.faction.equals(Board.getInstance().getFactionAt(new FLocation(context.player.getLocation())))) { + context.msg(TL.COMMAND_TNT_TERRITORYONLY); + return; + } + final int radius = context.argAsInt(0, -1); + final int amount = context.argAsInt(1, -1); + + if (radius <= 0) { + context.msg(TL.COMMAND_TNT_SIPHON_FAIL_POSITIVE); + return; + } + + if (FactionsPlugin.getInstance().conf().commands().tnt().isAboveMaxStorage(context.faction.getTNTBank() + 1)) { + context.msg(TL.COMMAND_TNT_SIPHON_FAIL_FULL); + return; + } + + if (radius > FactionsPlugin.getInstance().conf().commands().tnt().getMaxRadius()) { + context.msg(TL.COMMAND_TNT_SIPHON_FAIL_MAXRADIUS, radius, FactionsPlugin.getInstance().conf().commands().tnt().getMaxRadius()); + return; + } + + List list = CmdTNTFill.getDispensers(context.player.getLocation(), radius, context.faction.getId()); + + int canTake; + int maxLevel = context.faction.getMaxTNT(); + if (maxLevel < 0) { + canTake = Integer.MAX_VALUE; + } else { + canTake = maxLevel; + } + + canTake -= context.faction.getTNTBank(); + + if (amount > 0 && amount < canTake) { + canTake = amount; + } + + int remaining = canTake; + + for (Dispenser dispenser : list) { + if (remaining > (64 * 9)) { + remaining -= CmdTNTFill.getCount(dispenser.getInventory().all(Material.TNT).values()); + dispenser.getInventory().remove(Material.TNT); + } else { + remaining = CmdTNTFill.getCount(dispenser.getInventory().removeItem(CmdTNTFill.getStacks(remaining)).values()); + } + if (remaining == 0) { + break; + } + } + + int acquired = canTake - remaining; + + context.faction.setTNTBank(context.faction.getTNTBank() + acquired); + + context.msg(TL.COMMAND_TNT_SIPHON_MESSAGE, acquired, context.faction.getTNTBank()); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNT_SIPHON_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTWithdraw.java b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTWithdraw.java new file mode 100644 index 0000000..ae910ff --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTNTWithdraw.java @@ -0,0 +1,71 @@ +package com.massivecraft.factions.cmd.tnt; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.cmd.CommandRequirements; +import com.massivecraft.factions.cmd.FCommand; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class CmdTNTWithdraw extends FCommand { + public CmdTNTWithdraw() { + super(); + this.aliases.add("withdraw"); + this.aliases.add("w"); + this.requiredArgs.add("amount"); + + this.requirements = new CommandRequirements.Builder(Permission.TNT_WITHDRAW).withAction(PermissibleAction.TNTWITHDRAW).memberOnly().build(); + } + + @Override + public void perform(CommandContext context) { + Player player = context.player; + if (!context.faction.equals(Board.getInstance().getFactionAt(new FLocation(player.getLocation())))) { + context.msg(TL.COMMAND_TNT_TERRITORYONLY); + return; + } + int amount = context.argAsInt(0, -1); + if (amount <= 0) { + context.msg(TL.COMMAND_TNT_WITHDRAW_FAIL_POSITIVE, amount); + return; + } + + if (context.faction.getTNTBank() < amount) { + context.msg(TL.COMMAND_TNT_WITHDRAW_FAIL_NOTENOUGH, amount); + return; + } + + List stacks = new ArrayList<>(); + int toGive = amount; + while (toGive > 0) { + int giving = Math.min(toGive, 64); + stacks.add(new ItemStack(Material.TNT, giving)); + toGive -= giving; + } + Map remaining = player.getInventory().addItem(stacks.toArray(new ItemStack[0])); + + int notTaken = 0; + + for (ItemStack stack : remaining.values()) { + notTaken += stack.getAmount(); + } + + context.faction.setTNTBank(context.faction.getTNTBank() - amount + notTaken); + context.msg(TL.COMMAND_TNT_WITHDRAW_MESSAGE, (amount - notTaken), context.faction.getTNTBank()); + } + + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNT_WITHDRAW_DESCRIPTION; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/ConfigManager.java b/Factions/src/main/java/com/massivecraft/factions/config/ConfigManager.java new file mode 100644 index 0000000..59219b2 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/ConfigManager.java @@ -0,0 +1,54 @@ +package com.massivecraft.factions.config; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.file.DefaultOfflinePermissionsConfig; +import com.massivecraft.factions.config.file.DefaultPermissionsConfig; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.config.transition.Transitioner; + +import java.io.IOException; +import java.util.logging.Level; + +public class ConfigManager { + private final FactionsPlugin plugin; + private final DefaultPermissionsConfig permissionsConfig = new DefaultPermissionsConfig(); + private final DefaultOfflinePermissionsConfig offlinePermissionsConfig = new DefaultOfflinePermissionsConfig(); + private final MainConfig mainConfig = new MainConfig(); + + public ConfigManager(FactionsPlugin plugin) { + this.plugin = plugin; + } + + public void startup() { + Transitioner.transition(this.plugin); + this.loadConfigs(); + } + + public void loadConfigs() { + this.loadConfig("default_permissions", this.permissionsConfig); + this.loadConfig("default_permissions_offline", this.offlinePermissionsConfig); + this.loadConfig("main", this.mainConfig); + this.mainConfig.factions().other().actualDefaultRelation = null; + } + + private void loadConfig(String name, Object config) { + try { + Loader.loadAndSave(name, config); + } catch (IOException | IllegalAccessException e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Could not load config '" + name + ".conf'", e); + } + } + + public DefaultPermissionsConfig getPermissionsConfig() { + return this.permissionsConfig; + } + + public DefaultOfflinePermissionsConfig getOfflinePermissionsConfig() { + return this.offlinePermissionsConfig; + } + + public MainConfig getMainConfig() { + return this.mainConfig; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/Loader.java b/Factions/src/main/java/com/massivecraft/factions/config/Loader.java new file mode 100644 index 0000000..2e77aa0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/Loader.java @@ -0,0 +1,162 @@ +package com.massivecraft.factions.config; + +import com.google.common.reflect.TypeToken; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.annotation.Comment; +import com.massivecraft.factions.config.annotation.ConfigName; +import com.massivecraft.factions.config.annotation.DefinedType; +import com.massivecraft.factions.config.annotation.WipeOnReload; +import com.typesafe.config.ConfigRenderOptions; +import ninja.leaping.configurate.ConfigurationOptions; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.hocon.HoconConfigurationLoader; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class Loader { + public static void loadAndSave(String file, Object config) throws IOException, IllegalAccessException { + HoconConfigurationLoader loader = getLoader(file); + loadAndSave(loader, config); + } + + public static HoconConfigurationLoader getLoader(String file) { + Path configFolder = FactionsPlugin.getInstance().getDataFolder().toPath().resolve("config"); + if (!configFolder.toFile().exists()) { + configFolder.toFile().mkdir(); + } + Path path = configFolder.resolve(file + ".conf"); + return HoconConfigurationLoader.builder() + .setPath(path) + .setDefaultOptions(ConfigurationOptions.defaults().setAcceptedTypes(null)) + .setRenderOptions(ConfigRenderOptions.defaults().setComments(true).setOriginComments(false).setJson(false)) + .build(); + } + + public static void loadAndSave(HoconConfigurationLoader loader, Object config) throws IOException, IllegalAccessException { + CommentedConfigurationNode node = loader.load(); + CommentedConfigurationNode newNode = loader.createEmptyNode(); + + loadNode(node, newNode, config); + + loader.save(newNode); + } + + public static void load(HoconConfigurationLoader loader, Object config) throws IOException, IllegalAccessException { + CommentedConfigurationNode node = loader.load(); + + loadNode(node, loader.createEmptyNode(), config); + } + + private static Set> types = new HashSet<>(); + + static { + types.add(Boolean.TYPE); + types.add(Byte.TYPE); + types.add(Character.TYPE); + types.add(Double.TYPE); + types.add(Float.TYPE); + types.add(Integer.TYPE); + types.add(Long.TYPE); + types.add(Short.TYPE); + types.add(List.class); + types.add(Map.class); + types.add(Set.class); + types.add(String.class); + } + + private static void loadNode(CommentedConfigurationNode current, CommentedConfigurationNode newNode, Object object) throws IllegalAccessException { + for (Field field : getFields(object.getClass())) { + if (field.isSynthetic()) { + continue; + } + if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { + if (field.getAnnotation(WipeOnReload.class) != null) { + field.setAccessible(true); + field.set(object, null); + } + continue; + } + field.setAccessible(true); + ConfigName configName = field.getAnnotation(ConfigName.class); + Comment comment = field.getAnnotation(Comment.class); + DefinedType definedType = field.getAnnotation(DefinedType.class); + String confName = configName == null || configName.value().isEmpty() ? field.getName() : configName.value(); + CommentedConfigurationNode curNode = current.getNode(confName); + CommentedConfigurationNode newNewNode = newNode.getNode(confName); + boolean needsValue = curNode.isVirtual() || curNode.getValue() == null; + if (comment != null) { + newNewNode.setComment(comment.value()); + } + Object defaultValue = field.get(object); + if (types.contains(field.getType())) { + if (needsValue) { + if (definedType == null) { + newNewNode.setValue(defaultValue); + } else { + try { + Field tokenField = field.getDeclaringClass().getDeclaredField(field.getName() + "Token"); + tokenField.setAccessible(true); + newNewNode.setValue((TypeToken) tokenField.get(object), defaultValue); + } catch (ObjectMappingException | NoSuchFieldException e) { + System.out.println("Failed horrifically to handle " + confName); + } + } + } else { + try { + if (Set.class.isAssignableFrom(field.getType()) && List.class.isAssignableFrom(curNode.getValue().getClass())) { + field.set(object, new HashSet((List) curNode.getValue())); + } else { + field.set(object, curNode.getValue()); + } + newNewNode.setValue(curNode.getValue()); + } catch (IllegalArgumentException ex) { + System.out.println("Found incorrect type for " + getNodeName(curNode.getPath()) + ": Expected " + field.getType() + ", found " + curNode.getValue().getClass()); + field.set(object, defaultValue); + } + } + } else { + Object o = defaultValue; + if (o == null) { + curNode.setValue(null); + newNewNode.setValue(null); + } else { + loadNode(curNode, newNewNode, o); + } + } + } + } + + private static List getFields(Class clazz) { + return getFields(new ArrayList<>(), clazz); + } + + private static List getFields(List fields, Class clazz) { + fields.addAll(Arrays.asList(clazz.getDeclaredFields())); + + if (clazz.getSuperclass() != null) { + getFields(fields, clazz.getSuperclass()); + } + + return fields; + } + + private static String getNodeName(Object[] path) { + StringBuilder builder = new StringBuilder(); + for (Object o : path) { + if (o != null) { + builder.append(o.toString()).append('.'); + } + } + return builder.substring(0, builder.length() - 1); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/annotation/Comment.java b/Factions/src/main/java/com/massivecraft/factions/config/annotation/Comment.java new file mode 100644 index 0000000..d55dab0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/annotation/Comment.java @@ -0,0 +1,12 @@ +package com.massivecraft.factions.config.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Comment { + String value(); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/annotation/ConfigName.java b/Factions/src/main/java/com/massivecraft/factions/config/annotation/ConfigName.java new file mode 100644 index 0000000..6c43574 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/annotation/ConfigName.java @@ -0,0 +1,12 @@ +package com.massivecraft.factions.config.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigName { + String value(); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/annotation/DefinedType.java b/Factions/src/main/java/com/massivecraft/factions/config/annotation/DefinedType.java new file mode 100644 index 0000000..23aa0ee --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/annotation/DefinedType.java @@ -0,0 +1,11 @@ +package com.massivecraft.factions.config.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface DefinedType { +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/annotation/WipeOnReload.java b/Factions/src/main/java/com/massivecraft/factions/config/annotation/WipeOnReload.java new file mode 100644 index 0000000..b86b2e9 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/annotation/WipeOnReload.java @@ -0,0 +1,11 @@ +package com.massivecraft.factions.config.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface WipeOnReload { +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/file/DefaultOfflinePermissionsConfig.java b/Factions/src/main/java/com/massivecraft/factions/config/file/DefaultOfflinePermissionsConfig.java new file mode 100644 index 0000000..fc044c3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/file/DefaultOfflinePermissionsConfig.java @@ -0,0 +1,45 @@ +package com.massivecraft.factions.config.file; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.annotation.Comment; + +import java.lang.reflect.Field; +import java.util.logging.Level; + +public class DefaultOfflinePermissionsConfig { + @Comment("Offline permissions settings\n" + + "If you don't enable offline permissions in the main config and never plan to do so,\n" + + " you can ignore this file entirely. If you plan to do so in the future, you should probably\n" + + " set this file up a bit as these defaults will sit in the faction configs regardless.\n" + + "\n" + + "Each main section represents one permission.\n" + + "Inside is each relation.\n" + + "Each relation has a default value (true=allowed, false=disallowed)\n" + + " and true/false for if it's locked to editing by factions admins.") + private DefaultPermissionsConfig.Permissions offlinePermissions = new DefaultPermissionsConfig.Permissions(); + + public DefaultOfflinePermissionsConfig() { + try { + for (Field field : DefaultPermissionsConfig.Permissions.class.getDeclaredFields()) { + field.setAccessible(true); + Object o = field.get(offlinePermissions); + if (o instanceof DefaultPermissionsConfig.Permissions.FullPermInfo) { + DefaultPermissionsConfig.Permissions.FullPermInfo i = (DefaultPermissionsConfig.Permissions.FullPermInfo) o; + i.recruit = null; + i.normal = null; + i.moderator = null; + i.coleader = null; + i.alt = null; + } else if (o instanceof DefaultPermissionsConfig.Permissions.FactionOnlyPermInfo) { + field.set(offlinePermissions, null); + } + } + } catch (IllegalAccessException e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to update offline permission special states", e); + } + } + + public DefaultPermissionsConfig.Permissions getPermissions() { + return this.offlinePermissions; + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/config/file/DefaultPermissionsConfig.java b/Factions/src/main/java/com/massivecraft/factions/config/file/DefaultPermissionsConfig.java new file mode 100644 index 0000000..ff09f07 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/file/DefaultPermissionsConfig.java @@ -0,0 +1,438 @@ +package com.massivecraft.factions.config.file; + +import com.massivecraft.factions.config.annotation.Comment; +import com.massivecraft.factions.config.annotation.ConfigName; +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; + +public class DefaultPermissionsConfig { + public static class Permissions { + public class PermissiblePermInfo { + public boolean isLocked() { + return this.locked; + } + + public boolean defaultAllowed() { + return this.value; + } + + private boolean locked = false; + @ConfigName("default") + private boolean value = false; + } + + public class FactionOnlyPermInfo { + protected PermissiblePermInfo coleader = new PermissiblePermInfo(); + protected PermissiblePermInfo moderator = new PermissiblePermInfo(); + protected PermissiblePermInfo normal = new PermissiblePermInfo(); + protected PermissiblePermInfo recruit = new PermissiblePermInfo(); + protected PermissiblePermInfo alt = new PermissiblePermInfo(); + + public PermissiblePermInfo get(Permissible permissible) { + if (permissible instanceof Role) { + switch ((Role) permissible) { + case COLEADER: + return this.coleader; + case MODERATOR: + return this.moderator; + case NORMAL: + return this.normal; + case RECRUIT: + return this.recruit; + case ALT: + return this.alt; + } + } + // TODO print warning + return null; + } + } + + public class FullPermInfo extends FactionOnlyPermInfo { + protected PermissiblePermInfo ally = new PermissiblePermInfo(); + protected PermissiblePermInfo truce = new PermissiblePermInfo(); + protected PermissiblePermInfo neutral = new PermissiblePermInfo(); + protected PermissiblePermInfo enemy = new PermissiblePermInfo(); + + public PermissiblePermInfo get(Permissible permissible) { + if (permissible instanceof Relation) { + switch ((Relation) permissible) { + case ALLY: + return this.ally; + case TRUCE: + return this.truce; + case NEUTRAL: + return this.neutral; + case ENEMY: + return this.enemy; + } + } + return super.get(permissible); + } + } + + public FactionOnlyPermInfo getBan() { + return this.ban; + } + + public FullPermInfo getBuild() { + return this.build; + } + + public FullPermInfo getDestroy() { + return this.destroy; + } + + public FullPermInfo getFrostWalk() { + return this.frostWalk; + } + + public FullPermInfo getPainBuild() { + return this.painBuild; + } + + public FullPermInfo getDoor() { + return this.door; + } + + public FullPermInfo getButton() { + return this.button; + } + + public FullPermInfo getLever() { + return this.lever; + } + + public FullPermInfo getContainer() { + return this.container; + } + + public FactionOnlyPermInfo getInvite() { + return this.invite; + } + + public FactionOnlyPermInfo getKick() { + return this.kick; + } + + public FullPermInfo getItem() { + return this.item; + } + + public FullPermInfo getHome() { + return this.home; + } + + public FactionOnlyPermInfo getSetHome() { + return this.sethome; + } + + public FactionOnlyPermInfo getListClaims() { + return this.listClaims; + } + + public FactionOnlyPermInfo getEconomy() { + return this.economy; + } + + public FactionOnlyPermInfo getTerritory() { + return this.territory; + } + + public FactionOnlyPermInfo getTNTDeposit() { + return this.tntDeposit; + } + + public FactionOnlyPermInfo getTNTWithdraw() { + return this.tntWithdraw; + } + + public FactionOnlyPermInfo getOwner() { + return this.owner; + } + + public FullPermInfo getPlate() { + return this.plate; + } + + public FactionOnlyPermInfo getDisband() { + return this.disband; + } + + public FactionOnlyPermInfo getPromote() { + return this.promote; + } + + public FactionOnlyPermInfo getSetWarp() { + return this.setwarp; + } + + public FullPermInfo getWarp() { + return this.warp; + } + + public FullPermInfo getFly() { + return this.fly; + } + + public FactionOnlyPermInfo getRosterControl(){ + return this.rosterControl; + } + + public FullPermInfo getRepeater(){ + return this.repeater; + } + + public FullPermInfo getCorner(){return this.corner;} + + public FactionOnlyPermInfo getCollectorAccess() { + return this.collectorAccess; + } + + @Comment("Can change repeaters") + private FullPermInfo repeater = new FullPermInfo(){ + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + } + }; + + @Comment("Can claim a corner") + private FullPermInfo corner = new FullPermInfo(){ + { + this.coleader.value = true; + } + }; + + @Comment("Can control roster") + private FactionOnlyPermInfo rosterControl = new FactionOnlyPermInfo(){ + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + + @Comment("Can ban others from the faction") + private FactionOnlyPermInfo ban = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + @Comment("Can build in faction territory (while not raidable)") + private FullPermInfo build = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + } + }; + @Comment("Can destroy in faction territory (while not raidable)") + private FullPermInfo destroy = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + } + }; + @Comment("Can frost walk in faction territory (while not raidable)") + private FullPermInfo frostWalk = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + } + }; + @Comment("Allows building/destroying in faction territory but causes pain (while not raidable)") + private FullPermInfo painBuild = new FullPermInfo(); + @Comment("Use doors in faction territory (while not raidable)") + private FullPermInfo door = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + this.alt.value = true; + this.ally.value = true; + } + }; + @Comment("Use buttons in faction territory (while not raidable)") + private FullPermInfo button = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + this.alt.value = true; + this.ally.value = true; + } + }; + @Comment("Use levers in faction territory (while not raidable)") + private FullPermInfo lever = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + this.alt.value = true; + this.ally.value = true; + } + }; + @Comment("Use containers in faction territory (while not raidable)") + private FullPermInfo container = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + } + }; + @Comment("Able to invite others to the faction") + private FactionOnlyPermInfo invite = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + private FactionOnlyPermInfo kick = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + @Comment("Use items in faction territory (while not raidable)") + private FullPermInfo item = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + } + }; + @Comment("Can visit the faction home") + private FullPermInfo home = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + this.alt.value = true; + } + }; + @Comment("Can see faction claim list") + private FactionOnlyPermInfo listClaims = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + @Comment("Can set the faction home") + private FactionOnlyPermInfo sethome = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + } + }; + @Comment("Can access faction economy") + private FactionOnlyPermInfo economy = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + } + }; + @Comment("Can claim/unclaim faction territory") + private FactionOnlyPermInfo territory = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + @Comment("Can deposit TNT into the bank") + private FactionOnlyPermInfo tntDeposit = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + } + }; + @Comment("Can withdraw TNT from the bank") + private FactionOnlyPermInfo tntWithdraw = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + @Comment("Can open collectors") + private FactionOnlyPermInfo collectorAccess = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + @Comment("Can created owned areas with /f owner") + private FactionOnlyPermInfo owner = new FactionOnlyPermInfo(); + @Comment("Can interact with plates") + private FullPermInfo plate = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + this.alt.value = true; + this.ally.value = true; + } + }; + private FactionOnlyPermInfo disband = new FactionOnlyPermInfo(); + @Comment("Can promote members up to their own role within the faction") + private FactionOnlyPermInfo promote = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + @Comment("Can set a faction warp") + private FactionOnlyPermInfo setwarp = new FactionOnlyPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + } + }; + @Comment("Can use faction warps") + private FullPermInfo warp = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + this.alt.value = true; + } + }; + @Comment("Can fly in faction territory") + private FullPermInfo fly = new FullPermInfo() { + { + this.coleader.value = true; + this.moderator.value = true; + this.normal.value = true; + this.recruit.value = true; + this.ally.value = true; + this.alt.value = true; + } + }; + } + + @Comment("Permissions settings\n" + + "Each main section represents one permission.\n" + + "Inside is each relation.\n" + + "Each relation has a default value (true=allowed, false=disallowed)\n" + + " and true/false for if it's locked to editing by factions admins.") + private Permissions permissions = new Permissions(); + + public Permissions getPermissions() { + return this.permissions; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/file/MainConfig.java b/Factions/src/main/java/com/massivecraft/factions/config/file/MainConfig.java new file mode 100644 index 0000000..e6f9fe0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/file/MainConfig.java @@ -0,0 +1,3514 @@ +package com.massivecraft.factions.config.file; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.annotation.Comment; +import com.massivecraft.factions.config.annotation.WipeOnReload; +import com.massivecraft.factions.gui.SimpleItem; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.util.MiscUtil; +import com.massivecraft.factions.util.TextUtil; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.entity.EntityType; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@SuppressWarnings({"FieldCanBeLocal", "FieldMayBeFinal", "InnerClassMayBeStatic", "BooleanMethodIsAlwaysInverted"}) +public class MainConfig { + public static class AVeryFriendlyFactionsConfig { + @Comment("Don't change this value yourself, unless you WANT a broken config!") + private int version = 4; + + @Comment("Debug\n" + + "Turn this on if you are having issues with something and working on resolving them.\n" + + "This will spam your console with information that is useful if you know how to read the source.\n" + + "It's suggested that you only turn this on at the direction of a developer.") + private boolean debug = false; + + public boolean isDebug() { + return debug; + } + } + + public class Corner { + private int diameterClaim = 15; + public int diameterClaim(){return 15;} + private boolean overrideOtherClaims = true; + public boolean overrideOtherClaims(){return overrideOtherClaims;} + private boolean onlyAllowInSOTW = true; + public boolean onlyAllowInSOTW(){return onlyAllowInSOTW;} + } + + public class Colors { + public class Relations { + private String member = "GREEN"; + @WipeOnReload + private transient ChatColor memberColor; + private String ally = "LIGHT_PURPLE"; + @WipeOnReload + private transient ChatColor allyColor; + private String truce = "DARK_PURPLE"; + @WipeOnReload + private transient ChatColor truceColor; + private String neutral = "WHITE"; + @WipeOnReload + private transient ChatColor neutralColor; + private String enemy = "RED"; + @WipeOnReload + private transient ChatColor enemyColor; + private String peaceful = "GOLD"; + @WipeOnReload + private transient ChatColor peacefulColor; + + public ChatColor getMember() { + return memberColor = Colors.this.getColor(this.member, this.memberColor, ChatColor.GREEN); + } + + public ChatColor getAlly() { + return allyColor = Colors.this.getColor(this.ally, this.allyColor, ChatColor.LIGHT_PURPLE); + } + + public ChatColor getTruce() { + return truceColor = Colors.this.getColor(this.truce, this.truceColor, ChatColor.DARK_PURPLE); + } + + public ChatColor getNeutral() { + return neutralColor = Colors.this.getColor(this.neutral, this.neutralColor, ChatColor.WHITE); + } + + public ChatColor getEnemy() { + return enemyColor = Colors.this.getColor(this.enemy, this.enemyColor, ChatColor.RED); + } + + public ChatColor getPeaceful() { + return peacefulColor = Colors.this.getColor(this.peaceful, this.peacefulColor, ChatColor.GOLD); + } + } + + public class Factions { + private String wilderness = "GRAY"; + @WipeOnReload + private transient ChatColor wildernessColor; + private String safezone = "GOLD"; + @WipeOnReload + private transient ChatColor safezoneColor; + private String warzone = "DARK_RED"; + @WipeOnReload + private transient ChatColor warzoneColor; + + public ChatColor getWilderness() { + return wildernessColor = Colors.this.getColor(this.wilderness, this.wildernessColor, ChatColor.GRAY); + } + + public ChatColor getSafezone() { + return safezoneColor = Colors.this.getColor(this.safezone, this.safezoneColor, ChatColor.GOLD); + } + + public ChatColor getWarzone() { + return warzoneColor = Colors.this.getColor(this.warzone, this.warzoneColor, ChatColor.DARK_RED); + } + } + + private Factions factions = new Factions(); + private Relations relations = new Relations(); + + private ChatColor getColor(String name, ChatColor current, ChatColor defaultColor) { + if (current != null) { + return current; + } + ChatColor ret; + try { + ret = ChatColor.valueOf(name); + } catch (IllegalArgumentException e) { + ret = defaultColor; + } + return ret; + } + + public Factions factions() { + return factions; + } + + public Relations relations() { + return relations; + } + } + + public class Commands { + public class Fly { + public class Particles { + @Comment("Speed of the particles, can be decimal value") + private double speed = 0.02; + @Comment("Amount spawned") + private int amount = 20; + @Comment("How often should we spawn these particles?\n" + + "0 disables this completely") + private double spawnRate = 0.2; + + public double getSpeed() { + return speed; + } + + public int getAmount() { + return amount; + } + + public double getSpawnRate() { + return spawnRate; + } + } + + @Comment("Warmup seconds before command executes. Set to 0 for no warmup.") + private int delay = 0; + @Comment("True to enable the fly command, false to disable") + private boolean enable = true; + @Comment("If a player leaves fly (out of territory or took damage)\n" + + "how long (in seconds) should they not take fall damage for?\n" + + "Set to 0 to have them always take fall damage.") + private int fallDamageCooldown = 3; + @Comment("This will intercept the default /fly command for those without essentials.fly and parse it to /f fly.") + private boolean interceptFlyCommand = true; + @Comment("From how far away a player can disable another's flight by being enemy\n" + + "Set to 0 if wanted disable\n" + + "Note: Will produce lag at higher numbers") + private int enemyRadius = 7; + @Comment("How frequently to check enemy radius, in seconds. Set to 0 to disable checking.") + private int radiusCheck = 1; + @Comment("Should we disable flight if the player has suffered generic damage") + private boolean disableOnGenericDamage = false; + @Comment("Should flight be disabled if the player has hurt mobs?") + private boolean disableOnHurtingMobs = false; + @Comment("Should flight be disabled if the player has hurt players?") + private boolean disableOnHurtingPlayers = true; + @Comment("Should players lose flight status while autoclaiming into territory they cannot fly in?") + private boolean disableFlightDuringAutoclaim = false; + @Comment("Should flight be disabled if the player is hurt by mobs?") + private boolean disableOnHurtByMobs = false; + + @Comment("Trails show below the players foot when flying, faction.fly.trails\n" + + "Players can enable them with /f trail on/off\n" + + "Players can also set which effect to show /f trail effect only if they have faction.fly.trails.") + private Particles particles = new Particles(); + + public int getDelay() { + return delay; + } + + public boolean isEnable() { + return enable; + } + + public int getFallDamageCooldown() { + return fallDamageCooldown; + } + + public int getEnemyRadius() { + return enemyRadius; + } + + public int getRadiusCheck() { + return radiusCheck; + } + + public boolean isDisableOnGenericDamage() { + return disableOnGenericDamage; + } + + public boolean isDisableOnHurtingMobs() { + return disableOnHurtingMobs; + } + + public boolean isInterceptFlyCommand() { + return interceptFlyCommand; + } + + public boolean isDisableOnHurtingPlayers() { + return disableOnHurtingPlayers; + } + + public boolean isDisableFlightDuringAutoclaim() { + return disableFlightDuringAutoclaim; + } + + public boolean isDisableOnHurtByMobs() { + return disableOnHurtByMobs; + } + + public Particles particles() { + return particles; + } + } + + public class Corner { + @Comment("Total length of claim down the line") + private int maxClaimLength = 25; + + @Comment("This will override ANY existing claim that the faction encounters while doing /f corner") + private boolean overrideClaims = true; + + + } + + public class RaidClaim { + @Comment("radius of a raid claim") + private int raidClaimRadius = 5; + + public int getRaidClaimRadius() { + return raidClaimRadius; + } + } + + + + public class Help { + @Comment("You can change the page name to whatever you like\n" + + "We use '1' to preserve default functionality of /f help 1") + private Map> entries = new HashMap>() { + { + this.put("1", Arrays.asList( + "&e&m----------------------------------------------", + " &c&lFactions Help ", + "&e&m----------------------------------------------", + "&3/f create &e>> &7Create your own faction", + "&3/f who &e>> &7Show factions info", + "&3/f tag &e>> &7Change faction tag", + "&3/f join &e>> &7Join faction", + "&3/f list &e>> &7List all factions", + "&e&m--------------&r &2/f help 2 for more &e&m--------------")); + this.put("2", Arrays.asList( + "&e&m------------------&r&c&l Page 2 &e&m--------------------", + "&3/f home &e>> &7Teleport to faction home", + "&3/f sethome &e>> &7Set your faction home", + "&3/f leave &e>> &7Leave your faction", + "&3/f invite &e>> &7Invite a player to your faction", + "&3/f deinvite &e>> &7Revoke invitation to player", + "&e&m--------------&r &2/f help 3 for more &e&m--------------")); + this.put("3", Arrays.asList( + "&e&m------------------&r&c&l Page 3 &e&m--------------------", + "&3/f claim &e>> &7Claim land", + "&3/f unclaim &e>> &7Unclaim land", + "&3/f kick &e>> &7Kick player from your faction", + "&3/f mod &e>> &7Set player role in faction", + "&3/f chat &e>> &7Switch to faction chat", + "&e&m--------------&r &2/f help 4 for more &e&m--------------")); + this.put("4", Arrays.asList( + "&e&m------------------&r&c&l Page 4 &e&m--------------------", + "&3/f version &e>> &7Display version information", + "&e&m--------------&r&2 End of /f help &e&m-----------------")); + } + }; + @Comment("set to true to use legacy factions help") + private boolean useOldHelp = true; + + public Map> getEntries() { + return entries != null ? Collections.unmodifiableMap(entries) : Collections.emptyMap(); + } + + public boolean isUseOldHelp() { + return useOldHelp; + } + } + + public class Home { + @Comment("Warmup seconds before command executes. Set to 0 for no warmup.") + private int delay = 0; + + public int getDelay() { + return delay; + } + } + + public class ListCmd { + @Comment("You can only use {pagenumber} and {pagecount} in the header.\nBlank entry results in nothing being displayed.") + private String header = "&e&m----------&r&e[ &2Faction List &9{pagenumber}&e/&9{pagecount} &e]&m----------"; + @Comment("You can only use {pagenumber} and {pagecount} in the footer.\nBlank entry results in nothing being displayed.") + private String footer = ""; + @Comment("You can use any variables here") + private String factionlessEntry = "Factionless {factionless} online"; + @Comment("You can use any variable here") + private String entry = "{faction-relation-color}{faction} {online} / {members} online, Land / Power / Maxpower: {chunks}/{power}/{maxPower}"; + + public String getHeader() { + return header; + } + + public String getFooter() { + return footer; + } + + public String getFactionlessEntry() { + return factionlessEntry; + } + + public String getEntry() { + return entry; + } + } + + public class MapCmd { + @Comment("This will help limit how many times a player can be sent a map of factions.\n" + + "Set this to the cooldown you want, in milliseconds, for a map to be shown to a player.\n" + + "This can prevent some teleportation-based exploits for finding factions.\n" + + "The old default was 2000, which blocks any movement faster than running.\n" + + "The new default is 700, which should also allow boats and horses.") + private int cooldown = 700; + + public int getCooldown() { + return cooldown; + } + } + + public class Near { + @Comment("Making this radius larger increases lag, do so at your own risk\n" + + "If on a high radius it is advised to add a cooldown to the command\n" + + "Also using {distance} placeholder in the lang would cause more lag on a bigger radius") + private int radius = 20; + + public int getRadius() { + return radius; + } + } + + public class Perms { + @Comment("Placeholders: {action-access-color}, {action-access}, {action-desc}") + private List guiLore = new ArrayList() { + { + this.add("&8Access: {action-access-color}{action-access}"); + this.add("&8{action-desc}"); + this.add(""); + this.add("&8Left click to &a&lAllow"); + this.add("&8Right click to &c&lDeny"); + } + }; + + public List getGuiLore() { + return Collections.unmodifiableList(guiLore); + } + } + + public class SeeChunk { + private boolean particles = true; + @Comment("Get a list of particle names here: https://factions.support/particles/") + private String particleName = "REDSTONE"; + @Comment("If the chosen particle is compatible with coloring we will color\n" + + "it based on the current chunk's faction") + private boolean relationalColor = true; + @Comment("How often should we update the particles to the current player's location?") + private double particleUpdateTime = 0.75; + + public boolean isParticles() { + return particles; + } + + public String getParticleName() { + return particleName; + } + + public boolean isRelationalColor() { + return relationalColor; + } + + public double getParticleUpdateTime() { + return particleUpdateTime; + } + } + + public class Show { + @Comment("You can use any variable here, including fancy messages. Color codes and or tags work fine.\n" + + "Lines that aren't defined wont be sent (home not set, faction not peaceful / permanent, dtr freeze)\n" + + "Supports placeholders.\n" + + "First line can be {header} for default header, or any string (we recommend &m for smooth lines ;p)\n" + + "The line with 'permanent' in it only appears if the faction is permanent.") + private List format = new ArrayList() { + { + this.add("{header}"); + this.add("Description: {description}"); + this.add("Joining: {joining} {peaceful}"); + this.add("Land / Power / Maxpower: {chunks}/{power}/{maxPower}"); + this.add("Raidable: {raidable}"); + this.add("Founded: {create-date}"); + this.add("This faction is permanent, remaining even with no members.'"); + this.add("Land value: {land-value} {land-refund}"); + this.add("Balance: {faction-balance}"); + this.add("Bans: {faction-bancount}"); + this.add("Allies({allies}/{max-allies}): {allies-list} "); + this.add("Online: ({online}/{members}): {online-list}"); + this.add("Offline: ({offline}/{members}): {offline-list}"); + this.add("Alts: ({alts}): {alt-list}"); + } + }; + @Comment("Set true to not display empty fancy messages") + private boolean minimal = false; + @Comment("Factions that should be exempt from /f show, case sensitive, useful for a\n" + + "serverteam faction, since the command shows vanished players otherwise") + private List exempt = new ArrayList() { + { + this.add("put_faction_tag_here"); + } + }; + + public List getFormat() { + return format != null ? Collections.unmodifiableList(format) : Collections.emptyList(); + } + + public boolean isMinimal() { + return minimal; + } + + public List getExempt() { + return exempt != null ? Collections.unmodifiableList(exempt) : Collections.emptyList(); + } + } + + public class Stuck { + @Comment("Warmup seconds before command executes. Set to 0 for no warmup.") + private int delay = 30; + @Comment("This radius defines how far from where they ran the command the player\n" + + "may travel while waiting to be unstuck. If they leave this radius, the\n" + + "command will be cancelled.") + private int radius = 10; + + public int getDelay() { + return delay; + } + + public int getRadius() { + return radius; + } + } + + public class TNT { + private boolean enable = true; + @Comment("Maximum storage. Set to -1 (or lower) to disable") + private int maxStorage = -1; + private int maxRadius = 5; + + public int getMaxRadius() { + return maxRadius; + } + + public int getMaxStorage() { + return maxStorage; + } + + public boolean isAboveMaxStorage(int amount) { + if (maxStorage < 0) { + return false; + } + return amount > maxStorage; + } + + public boolean isEnable() { + return enable; + } + } + + public class Warp { + @Comment("Warmup seconds before command executes. Set to 0 for no warmup.") + private int delay = 0; + @Comment("What should be the maximum amount of warps that a Faction can set?") + private int maxWarps = 5; + + public int getDelay() { + return delay; + } + + public int getMaxWarps() { + return maxWarps; + } + } + + public class ToolTips { + @Comment("Faction on-hover tooltip information") + private List faction = new ArrayList() { + { + this.add("&7Leader: &a{leader}"); + this.add("&7Claimed: &a{chunks}"); + this.add("&7Raidable: &a{raidable}"); + this.add("&7Warps: &a{warps}"); + this.add("&7Power: &a{power}/{maxPower}"); + this.add("&7Members: &a{online}/{members}"); + } + }; + @Comment("Player on-hover tooltip information") + private List player = new ArrayList() { + { + this.add("&7Last Seen: &a{lastSeen}"); + this.add("&7Power: &a{player-power}"); + this.add("&7Rank: &a{group}"); + this.add("&7Balance: &a${balance}"); + } + }; + + public List getFaction() { + return faction != null ? Collections.unmodifiableList(faction) : Collections.emptyList(); + } + + public List getPlayer() { + return player != null ? Collections.unmodifiableList(player) : Collections.emptyList(); + } + } + + public class Roster { + @Comment("This is including faction space, so 5 faction size + 5 extra players on roster, 10 combined") + private int rosterCap = 10; + + public int rosterCap(){ + return rosterCap; + } + } + + private RaidClaim raidClaim = new RaidClaim(); + private Fly fly = new Fly(); + private Help help = new Help(); + private Home home = new Home(); + private ListCmd list = new ListCmd(); + private MapCmd map = new MapCmd(); + private Near near = new Near(); + private Perms perms = new Perms(); + private SeeChunk seeChunk = new SeeChunk(); + private Show show = new Show(); + private Stuck stuck = new Stuck(); + @Comment("TNT bank!") + private TNT tnt = new TNT(); + private ToolTips toolTips = new ToolTips(); + private Warp warp = new Warp(); + + private Roster roster = new Roster(); + + public RaidClaim raidClaim() { + return raidClaim; + } + + public Fly fly() { + return fly; + } + + public Roster roster(){ + return roster; + } + + public Help help() { + return help; + } + + public Home home() { + return home; + } + + public ListCmd list() { + return list; + } + + public MapCmd map() { + return map; + } + + public Near near() { + return near; + } + + public Perms perms() { + return perms; + } + + public SeeChunk seeChunk() { + return seeChunk; + } + + public Show show() { + return show; + } + + public Stuck stuck() { + return stuck; + } + + public TNT tnt() { + return tnt; + } + + public ToolTips toolTips() { + return toolTips; + } + + public Warp warp() { + return warp; + } + } + + public class Factions { + public class LandRaidControl { + public class DTR { + private double startingDTR = 2.0; + private double maxDTR = 10.0; + private double minDTR = -3.0; + private double perPlayer = 1; + private double regainPerMinutePerPlayer = 0.05; + private double regainPerMinuteMaxRate = 0.1; + private double lossPerDeath = 1; + @Comment("Time, in seconds, to freeze DTR regeneration after a faction member dies") + private int freezeTime = 0; + private boolean freezePreventsJoin = true; + private boolean freezePreventsLeave = true; + private boolean freezePreventsDisband = true; + private double freezeKickPenalty = 0.5; + private String freezeTimeFormat = "H:mm:ss"; + @Comment("Additional claims allowed for each player in the faction") + private int landPerPlayer = 3; + @Comment("Claims the faction starts with.\n" + + "Note: A faction of one player has this many PLUS the perPlayer amount.") + private int landStarting = 6; + private int decimalDigits = 2; + private Map worldDeathModifiers = new HashMap() { + { + this.put("world_nether", 0.5D); + this.put("world_the_end", 0.25D); + } + }; + + public int getDecimalDigits() { + return decimalDigits; + } + + public int getLandPerPlayer() { + return landPerPlayer; + } + + public int getLandStarting() { + return landStarting; + } + + public int getFreezeTime() { + return freezeTime; + } + + public String getFreezeTimeFormat() { + return freezeTimeFormat; + } + + public boolean isFreezePreventsJoin() { + return freezePreventsJoin; + } + + public boolean isFreezePreventsLeave() { + return freezePreventsLeave; + } + + public boolean isFreezePreventsDisband() { + return freezePreventsDisband; + } + + public double getFreezeKickPenalty() { + return freezeKickPenalty; + } + + public double getMinDTR() { + return minDTR; + } + + public double getPerPlayer() { + return perPlayer; + } + + public double getRegainPerMinutePerPlayer() { + return regainPerMinutePerPlayer; + } + + public double getRegainPerMinuteMaxRate() { + return regainPerMinuteMaxRate; + } + + public double getMaxDTR() { + return maxDTR; + } + + public double getStartingDTR() { + return startingDTR; + } + + /** + * Not used directly by the plugin, as it uses the helper method. + * + * @return loss per death + * @see #getLossPerDeath(World) + */ + public double getLossPerDeathBase() { + return this.lossPerDeath; + } + + public double getLossPerDeath(World world) { + if (this.worldDeathModifiers == null) { + this.worldDeathModifiers = new HashMap<>(); + } + return this.lossPerDeath * this.worldDeathModifiers.getOrDefault(world.getName(), 1D).doubleValue(); + } + } + + public class Power { + private double playerMin = -10.0D; + private double playerMax = 10.0D; + private double playerStarting = 0.0D; + @Comment("Default health rate of 0.2 takes 5 minutes to recover one power") + private double powerPerMinute = 0.2; + @Comment("How much is lost on death") + private double lossPerDeath = 4.0; + @Comment("Does a player regenerate power while offline?") + private boolean regenOffline = false; + @Comment("A player loses this much per day offline") + private double offlineLossPerDay = 0.0; + @Comment("A player stops losing power from being offline once they reach this amount") + private double offlineLossLimit = 0.0; + @Comment("If greater than 0, used as a cap for how much power a faction can have\nAdditional power from players beyond this acts as a \"buffer\" of sorts") + private double factionMax = 0.0; + private boolean respawnHomeFromNoPowerLossWorlds = true; + private Set worldsNoPowerLoss = new HashSet() { + { + this.add("exampleWorld"); + } + }; + private boolean peacefulMembersDisablePowerLoss = true; + private boolean warZonePowerLoss = true; + private boolean wildernessPowerLoss = true; + @Comment("Disallow joining/leaving/kicking while power is negative") + private boolean canLeaveWithNegativePower = true; + @Comment("Allow a faction to be raided if they have more land than power.\n" + + "This will make claimed territory lose all protections\n" + + " allowing factions to open chests, break blocks, etc. if they\n" + + " have claimed chunks >= power.") + private boolean raidability = false; + @Comment("After a player dies, how long should the faction not be able to regen power?\n" + + "This resets on each death but does not accumulate.\n" + + "Set to 0 for no freeze. Time is in seconds.") + private int powerFreeze = 0; + + public boolean isRaidability() { + return raidability; + } + + public int getPowerFreeze() { + return powerFreeze; + } + + public boolean canLeaveWithNegativePower() { + return canLeaveWithNegativePower; + } + + public boolean isWarZonePowerLoss() { + return warZonePowerLoss; + } + + public boolean isWildernessPowerLoss() { + return wildernessPowerLoss; + } + + public double getPlayerMin() { + return playerMin; + } + + public double getPlayerMax() { + return playerMax; + } + + public double getPlayerStarting() { + return playerStarting; + } + + public double getPowerPerMinute() { + return powerPerMinute; + } + + public double getLossPerDeath() { + return lossPerDeath; + } + + public boolean isRegenOffline() { + return regenOffline; + } + + public double getOfflineLossPerDay() { + return offlineLossPerDay; + } + + public double getOfflineLossLimit() { + return offlineLossLimit; + } + + public double getFactionMax() { + return factionMax; + } + + public boolean isRespawnHomeFromNoPowerLossWorlds() { + return respawnHomeFromNoPowerLossWorlds; + } + + public Set getWorldsNoPowerLoss() { + return worldsNoPowerLoss == null ? Collections.emptySet() : Collections.unmodifiableSet(worldsNoPowerLoss); + } + + public boolean isPeacefulMembersDisablePowerLoss() { + return peacefulMembersDisablePowerLoss; + } + } + + @Comment("Sets the mode of land/raid control") + private String system = "power"; + private DTR dtr = new DTR(); + @Comment("Controls the power system of land/raid control\nSet the 'system' value to 'power' to use this system") + private Power power = new Power(); + + public String getSystem() { + return system; + } + + public DTR dtr() { + return this.dtr; + } + + public Power power() { + return power; + } + } + + public class Prefix { + private String admin = "***"; + private String coleader = "**"; + private String mod = "*"; + private String normal = "+"; + private String recruit = "-"; + private String alt = "~"; + + public String getAdmin() { + return admin; + } + + public String getColeader() { + return coleader; + } + + public String getMod() { + return mod; + } + + public String getNormal() { + return normal; + } + + public String getRecruit() { + return recruit; + } + + public String getAlt() { + return alt; + } + } + + public class Chat { + @Comment("Allow for players to chat only within their faction, with allies, etc.\n" + + "Set to false to only allow public chats through this plugin.") + private boolean factionOnlyChat = true; + // Configuration on the Faction tag in chat messages. + @Comment("If true, disables adding of faction tag so another plugin can manage this") + private boolean tagHandledByAnotherPlugin = false; + private boolean tagRelationColored = true; + private String tagReplaceString = "[FACTION]"; + private String tagInsertAfterString = ""; + private String tagInsertBeforeString = ""; + private int tagInsertIndex = 0; + private boolean tagPadBefore = false; + private boolean tagPadAfter = true; + private String tagFormat = "%s\u00A7f"; + private boolean alwaysShowChatTag = true; + private String factionChatFormat = "%s:\u00A7f %s"; + private String allianceChatFormat = "\u00A7d%s:\u00A7f %s"; + private String truceChatFormat = "\u00A75%s:\u00A7f %s"; + private String modChatFormat = "\u00A7c%s:\u00A7f %s"; + private boolean broadcastDescriptionChanges = false; + private boolean broadcastTagChanges = false; + + public boolean isFactionOnlyChat() { + return factionOnlyChat; + } + + public boolean isTagHandledByAnotherPlugin() { + return tagHandledByAnotherPlugin; + } + + public boolean isTagRelationColored() { + return tagRelationColored; + } + + public String getTagReplaceString() { + return tagReplaceString; + } + + public String getTagInsertAfterString() { + return tagInsertAfterString; + } + + public String getTagInsertBeforeString() { + return tagInsertBeforeString; + } + + public int getTagInsertIndex() { + return tagInsertIndex; + } + + public boolean isTagPadBefore() { + return tagPadBefore; + } + + public boolean isTagPadAfter() { + return tagPadAfter; + } + + public String getTagFormat() { + return tagFormat; + } + + public boolean isAlwaysShowChatTag() { + return alwaysShowChatTag; + } + + public String getFactionChatFormat() { + return factionChatFormat; + } + + public String getAllianceChatFormat() { + return allianceChatFormat; + } + + public String getTruceChatFormat() { + return truceChatFormat; + } + + public String getModChatFormat() { + return modChatFormat; + } + + public boolean isBroadcastDescriptionChanges() { + return broadcastDescriptionChanges; + } + + public boolean isBroadcastTagChanges() { + return broadcastTagChanges; + } + } + + public class Homes { + private boolean enabled = true; + private boolean mustBeInClaimedTerritory = true; + private boolean teleportToOnDeath = true; + private boolean teleportCommandEnabled = true; + private boolean teleportCommandEssentialsIntegration = true; + private boolean teleportCommandSmokeEffectEnabled = true; + private float teleportCommandSmokeEffectThickness = 3f; + private boolean teleportAllowedFromEnemyTerritory = true; + private boolean teleportAllowedFromDifferentWorld = true; + private double teleportAllowedEnemyDistance = 32.0; + private boolean teleportIgnoreEnemiesIfInOwnTerritory = true; + + public boolean isEnabled() { + return enabled; + } + + public boolean isMustBeInClaimedTerritory() { + return mustBeInClaimedTerritory; + } + + public boolean isTeleportToOnDeath() { + return teleportToOnDeath; + } + + public boolean isTeleportCommandEnabled() { + return teleportCommandEnabled; + } + + public boolean isTeleportCommandEssentialsIntegration() { + return teleportCommandEssentialsIntegration; + } + + public boolean isTeleportCommandSmokeEffectEnabled() { + return teleportCommandSmokeEffectEnabled; + } + + public float getTeleportCommandSmokeEffectThickness() { + return teleportCommandSmokeEffectThickness; + } + + public boolean isTeleportAllowedFromEnemyTerritory() { + return teleportAllowedFromEnemyTerritory; + } + + public boolean isTeleportAllowedFromDifferentWorld() { + return teleportAllowedFromDifferentWorld; + } + + public double getTeleportAllowedEnemyDistance() { + return teleportAllowedEnemyDistance; + } + + public boolean isTeleportIgnoreEnemiesIfInOwnTerritory() { + return teleportIgnoreEnemiesIfInOwnTerritory; + } + } + + public class MaxRelations { + private boolean enabled = false; + private int ally = 10; + private int truce = 10; + private int neutral = -1; + private int enemy = 10; + + public boolean isEnabled() { + return enabled; + } + + public int getAlly() { + return ally; + } + + public int getTruce() { + return truce; + } + + public int getNeutral() { + return neutral; + } + + public int getEnemy() { + return enemy; + } + } + + public class PVP { + private boolean disablePVPBetweenNeutralFactions = false; + private boolean disablePVPForFactionlessPlayers = false; + private boolean enablePVPAgainstFactionlessInAttackersLand = false; + private boolean disablePeacefulPVPInWarzone = true; + private int noPVPDamageToOthersForXSecondsAfterLogin = 3; + private Set worldsIgnorePvP = new HashSet() { + { + this.add("exampleWorldName"); + } + }; + + public boolean isDisablePVPBetweenNeutralFactions() { + return disablePVPBetweenNeutralFactions; + } + + public boolean isDisablePVPForFactionlessPlayers() { + return disablePVPForFactionlessPlayers; + } + + public boolean isDisablePeacefulPVPInWarzone() { + return disablePeacefulPVPInWarzone; + } + + public boolean isEnablePVPAgainstFactionlessInAttackersLand() { + return enablePVPAgainstFactionlessInAttackersLand; + } + + public int getNoPVPDamageToOthersForXSecondsAfterLogin() { + return noPVPDamageToOthersForXSecondsAfterLogin; + } + + public Set getWorldsIgnorePvP() { + return worldsIgnorePvP == null ? Collections.emptySet() : Collections.unmodifiableSet(worldsIgnorePvP); + } + } + + public class SpecialCase { + private boolean peacefulTerritoryDisablePVP = true; + private boolean peacefulTerritoryDisableMonsters = false; + private boolean peacefulTerritoryDisableBoom = false; + private boolean permanentFactionsDisableLeaderPromotion = false; + @Comment("Material names of things whose placement is ignored in faction territory") + private Set ignoreBuildMaterials = new HashSet() { + { + this.add("exampleMaterial"); + } + }; + @WipeOnReload + private transient Set ignoreBuildMaterialsMat; + + public Set getIgnoreBuildMaterials() { + if (ignoreBuildMaterialsMat == null) { + ignoreBuildMaterialsMat = new HashSet<>(); + ignoreBuildMaterials.forEach(m -> ignoreBuildMaterialsMat.add(MaterialDb.get(m))); + ignoreBuildMaterialsMat.remove(Material.AIR); + ignoreBuildMaterials = Collections.unmodifiableSet(ignoreBuildMaterials); + } + return ignoreBuildMaterialsMat; + } + + public boolean isPeacefulTerritoryDisablePVP() { + return peacefulTerritoryDisablePVP; + } + + public boolean isPeacefulTerritoryDisableMonsters() { + return peacefulTerritoryDisableMonsters; + } + + public boolean isPeacefulTerritoryDisableBoom() { + return peacefulTerritoryDisableBoom; + } + + public boolean isPermanentFactionsDisableLeaderPromotion() { + return permanentFactionsDisableLeaderPromotion; + } + } + + public class Portals { + @Comment("If true, portals will be limited to the minimum relation below") + private boolean limit = false; + @Comment("What should the minimum relation be to create a portal in territory?\n" + + "Goes in the order of: ENEMY, NEUTRAL, ALLY, MEMBER.\n" + + "Minimum relation allows that and all listed to the right to create portals.\n" + + "Example: put ALLY to allow ALLY and MEMBER to be able to create portals.\n" + + "If typed incorrectly, defaults to NEUTRAL.") + private String minimumRelation = "MEMBER"; + + public boolean isLimit() { + return limit; + } + + public String getMinimumRelation() { + return minimumRelation; + } + } + + public class Claims { + private boolean mustBeConnected = false; + private boolean canBeUnconnectedIfOwnedByOtherFaction = true; + private int requireMinFactionMembers = 1; + private int landsMax = 0; + private int lineClaimLimit = 5; + private int fillClaimMaxClaims = 25; + private int fillClaimMaxDistance = 5; + @Comment("The max radius a player can claim, this is overrided for admins but must be confirmed if a higher value is used") + private int maxRadiusClaim = 20; + @Comment("If someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit") + private int radiusClaimFailureLimit = 9; + private Set worldsNoClaiming = new HashSet() { + { + this.add("exampleWorldName"); + } + }; + @Comment("Buffer Zone is an chunk area required between claims of different Factions.\n" + + "This is default to 0 and has always been that way. Meaning Factions can have\n" + + " claims that border each other.\n" + + "If this is set to 3, then Factions need to have 3 chunks between their claim\n" + + " and another Faction's claim.\n" + + "It's recommended to keep this pretty low as the radius check could be a\n" + + " heavy operation if set to a large number.\n" + + "If this is set to 0, we won't even bother checking which is how Factions has\n" + + " always been.") + private int bufferZone = 0; + @Comment("Should we allow Factions to over claim if they are raidable?\n" + + "This has always been true, allowing factions to over claim others.") + private boolean allowOverClaim = true; + @Comment("If true (and allowOverClaim is true, claiming over another faction's land will ignore buffer zone settings.") + private boolean allowOverClaimIgnoringBuffer = false; + + public boolean isAllowOverClaim() { + return allowOverClaim; + } + + public boolean isAllowOverClaimAndIgnoringBuffer() { + return allowOverClaim && allowOverClaimIgnoringBuffer; + } + + public int getBufferZone() { + return bufferZone; + } + + public int getMaxRadiusClaim() { + return maxRadiusClaim; + } + + public boolean isMustBeConnected() { + return mustBeConnected; + } + + public boolean isCanBeUnconnectedIfOwnedByOtherFaction() { + return canBeUnconnectedIfOwnedByOtherFaction; + } + + public int getRequireMinFactionMembers() { + return requireMinFactionMembers; + } + + public int getLandsMax() { + return landsMax; + } + + public int getFillClaimMaxClaims() { + return fillClaimMaxClaims; + } + + public int getFillClaimMaxDistance() { + return fillClaimMaxDistance; + } + + public int getLineClaimLimit() { + return lineClaimLimit; + } + + public int getRadiusClaimFailureLimit() { + return radiusClaimFailureLimit; + } + + public Set getWorldsNoClaiming() { + return worldsNoClaiming == null ? Collections.emptySet() : Collections.unmodifiableSet(worldsNoClaiming); + } + } + + public class Protection { + @Comment("Commands which will be prevented if the player is a member of a permanent faction") + private Set permanentFactionMemberDenyCommands = new HashSet() { + { + this.add("exampleCommand"); + } + }; + + @Comment("Commands which will be prevented when in claimed territory of a neutral faction") + private Set territoryNeutralDenyCommands = new HashSet() { + { + this.add("exampleCommand"); + } + }; + @Comment("Commands which will be prevented when in claimed territory of an enemy faction") + private Set territoryEnemyDenyCommands = new HashSet() { + { + this.add("home"); + this.add("sethome"); + this.add("spawn"); + this.add("tpahere"); + this.add("tpaccept"); + this.add("tpa"); + } + }; + @Comment("Commands which will be prevented when in claimed territory of an ally faction") + private Set territoryAllyDenyCommands = new HashSet() { + { + this.add("exampleCommand"); + } + }; + @Comment("Commands which will be prevented when in warzone") + private Set warzoneDenyCommands = new HashSet() { + { + this.add("exampleCommand"); + } + }; + @Comment("Commands which will be prevented when in wilderness") + private Set wildernessDenyCommands = new HashSet() { + { + this.add("exampleCommand"); + } + }; + + private boolean territoryBlockCreepers = false; + private boolean territoryBlockCreepersWhenOffline = false; + private boolean territoryBlockFireballs = false; + private boolean territoryBlockFireballsWhenOffline = false; + private boolean territoryBlockTNT = false; + private boolean territoryBlockTNTWhenOffline = false; + private boolean territoryBlockOtherExplosions = false; + private boolean territoryBlockOtherExplosionsWhenOffline = false; + private boolean territoryDenyEndermanBlocks = true; + private boolean territoryDenyEndermanBlocksWhenOffline = true; + + private boolean safeZoneDenyBuild = true; + private boolean safeZoneDenyUsage = true; + private boolean safeZoneBlockTNT = true; + private boolean safeZoneBlockOtherExplosions = true; + private boolean safeZonePreventAllDamageToPlayers = false; + private boolean safeZoneDenyEndermanBlocks = true; + + private boolean warZoneDenyBuild = true; + private boolean warZoneDenyUsage = true; + private boolean warZoneBlockCreepers = true; + private boolean warZoneBlockFireballs = true; + private boolean warZoneBlockTNT = true; + private boolean warZoneBlockOtherExplosions = true; + private boolean warZoneFriendlyFire = false; + private boolean warZoneDenyEndermanBlocks = true; + + private boolean wildernessDenyBuild = false; + private boolean wildernessDenyUsage = false; + private boolean wildernessBlockCreepers = false; + private boolean wildernessBlockFireballs = false; + private boolean wildernessBlockTNT = false; + private boolean wildernessBlockOtherExplosions = false; + private boolean wildernessDenyEndermanBlocks = false; + + private boolean pistonProtectionThroughDenyBuild = true; + + private Set territoryDenyUsageMaterials = new HashSet<>(); + private Set territoryDenyUsageMaterialsWhenOffline = new HashSet<>(); + @WipeOnReload + private transient Set territoryDenyUsageMaterialsMat; + @WipeOnReload + private transient Set territoryDenyUsageMaterialsWhenOfflineMat; + + @Comment("Exceptions to consideration for container perms.\n" + + "For example, putting \"TRAPPED_CHEST\" into here would allow anyone to open trapped chests anywhere.") + private Set containerExceptions = new HashSet<>(); + @WipeOnReload + private transient Set containerExceptionsMat; + + @Comment("Exceptions to consideration for breaking perms. Can always be broken.") + private Set breakExceptions = new HashSet<>(); + @WipeOnReload + private transient Set breakExceptionsMat; + + @Comment("Exceptions for protections of interacting with entities, such as mounting horses") + private Set entityInteractExceptions = new HashSet<>(); + + @Comment("Mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections.") + private Set playersWhoBypassAllProtection = new HashSet() { + { + this.add("example-player-name"); + } + }; + private Set worldsNoWildernessProtection = new HashSet() { + { + this.add("exampleWorld"); + } + }; + + private Protection() { + protectUsage("FIRE_CHARGE"); + protectUsage("FLINT_AND_STEEL"); + protectUsage("BUCKET"); + protectUsage("WATER_BUCKET"); + protectUsage("LAVA_BUCKET"); + } + + private void protectUsage(String material) { + territoryDenyUsageMaterials.add(material); + territoryDenyUsageMaterialsWhenOffline.add(material); + } + + public Set getPermanentFactionMemberDenyCommands() { + return permanentFactionMemberDenyCommands == null ? Collections.emptySet() : Collections.unmodifiableSet(permanentFactionMemberDenyCommands); + } + + public Set getTerritoryNeutralDenyCommands() { + return territoryNeutralDenyCommands == null ? Collections.emptySet() : Collections.unmodifiableSet(territoryNeutralDenyCommands); + } + + public Set getTerritoryEnemyDenyCommands() { + return territoryEnemyDenyCommands == null ? Collections.emptySet() : Collections.unmodifiableSet(territoryEnemyDenyCommands); + } + + public Set getTerritoryAllyDenyCommands() { + return territoryAllyDenyCommands == null ? Collections.emptySet() : Collections.unmodifiableSet(territoryAllyDenyCommands); + } + + public Set getWarzoneDenyCommands() { + return warzoneDenyCommands == null ? Collections.emptySet() : Collections.unmodifiableSet(warzoneDenyCommands); + } + + public Set getWildernessDenyCommands() { + return wildernessDenyCommands == null ? Collections.emptySet() : Collections.unmodifiableSet(wildernessDenyCommands); + } + + public boolean isTerritoryBlockCreepers() { + return territoryBlockCreepers; + } + + public boolean isTerritoryBlockCreepersWhenOffline() { + return territoryBlockCreepersWhenOffline; + } + + public boolean isTerritoryBlockFireballs() { + return territoryBlockFireballs; + } + + public boolean isTerritoryBlockFireballsWhenOffline() { + return territoryBlockFireballsWhenOffline; + } + + public boolean isTerritoryBlockTNT() { + return territoryBlockTNT; + } + + public boolean isTerritoryBlockTNTWhenOffline() { + return territoryBlockTNTWhenOffline; + } + + public boolean isTerritoryDenyEndermanBlocks() { + return territoryDenyEndermanBlocks; + } + + public boolean isTerritoryDenyEndermanBlocksWhenOffline() { + return territoryDenyEndermanBlocksWhenOffline; + } + + public boolean isSafeZoneDenyBuild() { + return safeZoneDenyBuild; + } + + public boolean isSafeZoneDenyUsage() { + return safeZoneDenyUsage; + } + + public boolean isSafeZoneBlockTNT() { + return safeZoneBlockTNT; + } + + public boolean isSafeZonePreventAllDamageToPlayers() { + return safeZonePreventAllDamageToPlayers; + } + + public boolean isSafeZoneDenyEndermanBlocks() { + return safeZoneDenyEndermanBlocks; + } + + public boolean isWarZoneDenyBuild() { + return warZoneDenyBuild; + } + + public boolean isWarZoneDenyUsage() { + return warZoneDenyUsage; + } + + public boolean isWarZoneBlockCreepers() { + return warZoneBlockCreepers; + } + + public boolean isWarZoneBlockFireballs() { + return warZoneBlockFireballs; + } + + public boolean isWarZoneBlockTNT() { + return warZoneBlockTNT; + } + + public boolean isWarZoneFriendlyFire() { + return warZoneFriendlyFire; + } + + public boolean isWarZoneDenyEndermanBlocks() { + return warZoneDenyEndermanBlocks; + } + + public boolean isWildernessDenyBuild() { + return wildernessDenyBuild; + } + + public boolean isWildernessDenyUsage() { + return wildernessDenyUsage; + } + + public boolean isWildernessBlockCreepers() { + return wildernessBlockCreepers; + } + + public boolean isWildernessBlockFireballs() { + return wildernessBlockFireballs; + } + + public boolean isWildernessBlockTNT() { + return wildernessBlockTNT; + } + + public boolean isWildernessDenyEndermanBlocks() { + return wildernessDenyEndermanBlocks; + } + + public boolean isPistonProtectionThroughDenyBuild() { + return pistonProtectionThroughDenyBuild; + } + + public boolean isTerritoryBlockOtherExplosions() { + return territoryBlockOtherExplosions; + } + + public boolean isTerritoryBlockOtherExplosionsWhenOffline() { + return territoryBlockOtherExplosionsWhenOffline; + } + + public boolean isSafeZoneBlockOtherExplosions() { + return safeZoneBlockOtherExplosions; + } + + public boolean isWarZoneBlockOtherExplosions() { + return warZoneBlockOtherExplosions; + } + + public boolean isWildernessBlockOtherExplosions() { + return wildernessBlockOtherExplosions; + } + + public Set getTerritoryDenyUsageMaterials() { + if (territoryDenyUsageMaterialsMat == null) { + territoryDenyUsageMaterialsMat = new HashSet<>(); + territoryDenyUsageMaterials.forEach(m -> territoryDenyUsageMaterialsMat.add(MaterialDb.get(m))); + territoryDenyUsageMaterialsMat.remove(Material.AIR); + territoryDenyUsageMaterialsMat = Collections.unmodifiableSet(territoryDenyUsageMaterialsMat); + } + return territoryDenyUsageMaterialsMat; + } + + public Set getTerritoryDenyUsageMaterialsWhenOffline() { + if (territoryDenyUsageMaterialsWhenOfflineMat == null) { + territoryDenyUsageMaterialsWhenOfflineMat = new HashSet<>(); + territoryDenyUsageMaterialsWhenOffline.forEach(m -> territoryDenyUsageMaterialsWhenOfflineMat.add(MaterialDb.get(m))); + territoryDenyUsageMaterialsWhenOfflineMat.remove(Material.AIR); + territoryDenyUsageMaterialsWhenOfflineMat = Collections.unmodifiableSet(territoryDenyUsageMaterialsWhenOfflineMat); + } + return territoryDenyUsageMaterialsWhenOfflineMat; + } + + public Set getContainerExceptions() { + if (containerExceptionsMat == null) { + containerExceptionsMat = new HashSet<>(); + containerExceptions.forEach(m -> containerExceptionsMat.add(MaterialDb.get(m))); + containerExceptionsMat.remove(Material.AIR); + containerExceptionsMat = Collections.unmodifiableSet(containerExceptionsMat); + } + return containerExceptionsMat; + } + + public Set getBreakExceptions() { + if (breakExceptionsMat == null) { + breakExceptionsMat = new HashSet<>(); + breakExceptions.forEach(m -> breakExceptionsMat.add(MaterialDb.get(m))); + breakExceptionsMat.remove(Material.AIR); + breakExceptionsMat = Collections.unmodifiableSet(breakExceptionsMat); + } + return breakExceptionsMat; + } + + public Set getEntityInteractExceptions() { + return Collections.unmodifiableSet(entityInteractExceptions); + } + + public Set getPlayersWhoBypassAllProtection() { + return playersWhoBypassAllProtection == null ? Collections.emptySet() : Collections.unmodifiableSet(playersWhoBypassAllProtection); + } + + public Set getWorldsNoWildernessProtection() { + return worldsNoWildernessProtection == null ? Collections.emptySet() : Collections.unmodifiableSet(worldsNoWildernessProtection); + } + } + + public class Spawning { + private Set preventSpawningInSafezone = new HashSet() { + { + this.add("BREEDING"); + this.add("BUILD_IRONGOLEM"); + this.add("BUILD_SNOWMAN"); + this.add("BUILD_WITHER"); + this.add("CURED"); + this.add("DEFAULT"); + this.add("DISPENSE_EGG"); + this.add("DROWNED"); + this.add("EGG"); + this.add("ENDER_PEARL"); + this.add("EXPLOSION"); + this.add("INFECTION"); + this.add("LIGHTNING"); + this.add("MOUNT"); + this.add("NATURAL"); + this.add("NETHER_PORTAL"); + this.add("OCELOT_BABY"); + this.add("PATROL"); + this.add("RAID"); + this.add("REINFORCEMENTS"); + this.add("SILVERFISH_BLOCK"); + this.add("SLIME_SPLIT"); + this.add("SPAWNER"); + this.add("SPAWNER_EGG"); + this.add("TRAP"); + this.add("VILLAGE_DEFENSE"); + this.add("VILLAGE_INVASION"); + } + }; + @WipeOnReload + private transient Set preventSpawningInSafezoneReason; + private Set preventSpawningInSafezoneExceptions = new HashSet() { + { + this.add("BAT"); + this.add("CAT"); + this.add("CHICKEN"); + this.add("COD"); + this.add("COW"); + this.add("DOLPHIN"); + this.add("DONKEY"); + this.add("FOX"); + this.add("HORSE"); + this.add("IRON_GOLEM"); + this.add("LLAMA"); + this.add("MULE"); + this.add("MUSHROOM_COW"); + this.add("OCELOT"); + this.add("PANDA"); + this.add("PARROT"); + this.add("PIG"); + this.add("POLAR_BEAR"); + this.add("PUFFERFISH"); + this.add("RABBIT"); + this.add("SALMON"); + this.add("SHEEP"); + this.add("STRIDER"); + this.add("SQUID"); + this.add("TRADER_LLAMA"); + this.add("TROPICAL_FISH"); + this.add("TURTLE"); + this.add("VILLAGER"); + this.add("WANDERING_TRADER"); + this.add("WOLF"); + } + }; + @WipeOnReload + private transient Set preventSpawningInSafezoneExceptionsType; + private Set preventSpawningInWarzone = new HashSet<>(); + @WipeOnReload + private transient Set preventSpawningInWarzoneReason; + private Set preventSpawningInWarzoneExceptions = new HashSet<>(); + @WipeOnReload + private transient Set preventSpawningInWarzoneExceptionsType; + private Set preventSpawningInWilderness = new HashSet<>(); + @WipeOnReload + private transient Set preventSpawningInWildernessReason; + private Set preventSpawningInWildernessExceptions = new HashSet<>(); + @WipeOnReload + private transient Set preventSpawningInWildernessExceptionsType; + private Set preventSpawningInTerritory = new HashSet<>(); + @WipeOnReload + private transient Set preventSpawningInTerritoryReason; + private Set preventSpawningInTerritoryExceptions = new HashSet<>(); + @WipeOnReload + private transient Set preventSpawningInTerritoryExceptionsType; + @Comment("If true, FactionsUUID will automatically add in its new defaults such as\n" + + "adding new friendly mobs to the safe zone exception list") + private boolean updateAutomatically = true; + + public boolean isUpdateAutomatically() { + return updateAutomatically; + } + + public Set getPreventInSafezone() { + if (preventSpawningInSafezoneReason == null) { + preventSpawningInSafezoneReason = MiscUtil.typeSetFromStringSet(preventSpawningInSafezone, MiscUtil.SPAWN_REASON_FUNCTION); + } + return preventSpawningInSafezoneReason; + } + + public Set getPreventInSafezoneExceptions() { + if (preventSpawningInSafezoneExceptionsType == null) { + preventSpawningInSafezoneExceptionsType = MiscUtil.typeSetFromStringSet(preventSpawningInSafezoneExceptions, MiscUtil.ENTITY_TYPE_FUNCTION); + } + return preventSpawningInSafezoneExceptionsType; + } + + public Set getPreventInTerritory() { + if (preventSpawningInTerritoryReason == null) { + preventSpawningInTerritoryReason = MiscUtil.typeSetFromStringSet(preventSpawningInTerritory, MiscUtil.SPAWN_REASON_FUNCTION); + } + return preventSpawningInTerritoryReason; + } + + public Set getPreventInTerritoryExceptions() { + if (preventSpawningInTerritoryExceptionsType == null) { + preventSpawningInTerritoryExceptionsType = MiscUtil.typeSetFromStringSet(preventSpawningInTerritoryExceptions, MiscUtil.ENTITY_TYPE_FUNCTION); + } + return preventSpawningInTerritoryExceptionsType; + } + + public Set getPreventInWarzone() { + if (preventSpawningInWarzoneReason == null) { + preventSpawningInWarzoneReason = MiscUtil.typeSetFromStringSet(preventSpawningInWarzone, MiscUtil.SPAWN_REASON_FUNCTION); + } + return preventSpawningInWarzoneReason; + } + + public Set getPreventInWarzoneExceptions() { + if (preventSpawningInWarzoneExceptionsType == null) { + preventSpawningInWarzoneExceptionsType = MiscUtil.typeSetFromStringSet(preventSpawningInWarzoneExceptions, MiscUtil.ENTITY_TYPE_FUNCTION); + } + return preventSpawningInWarzoneExceptionsType; + } + + public Set getPreventInWilderness() { + if (preventSpawningInWildernessReason == null) { + preventSpawningInWildernessReason = MiscUtil.typeSetFromStringSet(preventSpawningInWilderness, MiscUtil.SPAWN_REASON_FUNCTION); + } + return preventSpawningInWildernessReason; + } + + public Set getPreventInWildernessExceptions() { + if (preventSpawningInWildernessExceptionsType == null) { + preventSpawningInWildernessExceptionsType = MiscUtil.typeSetFromStringSet(preventSpawningInWildernessExceptions, MiscUtil.ENTITY_TYPE_FUNCTION); + } + return preventSpawningInWildernessExceptionsType; + } + } + + public class OwnedArea { + private boolean enabled = true; + private int limitPerFaction = 0; + private boolean moderatorsBypass = true; + private boolean denyBuild = true; + private boolean painBuild = false; + private boolean protectMaterials = true; + private boolean denyUsage = true; + + private boolean messageOnBorder = true; + private boolean messageInsideTerritory = true; + private boolean messageByChunk = false; + + public boolean isEnabled() { + return enabled; + } + + public int getLimitPerFaction() { + return limitPerFaction; + } + + public boolean isModeratorsBypass() { + return moderatorsBypass; + } + + public boolean isDenyBuild() { + return denyBuild; + } + + public boolean isPainBuild() { + return painBuild; + } + + public boolean isProtectMaterials() { + return protectMaterials; + } + + public boolean isDenyUsage() { + return denyUsage; + } + + public boolean isMessageOnBorder() { + return messageOnBorder; + } + + public boolean isMessageInsideTerritory() { + return messageInsideTerritory; + } + + public boolean isMessageByChunk() { + return messageByChunk; + } + } + + public class Other { + private boolean allowMultipleColeaders = false; + + @Comment("Minimum faction tag length") + private int tagLengthMin = 3; + @Comment("Maximum faction tag length") + private int tagLengthMax = 10; + private boolean tagForceUpperCase = false; + + private boolean newFactionsDefaultOpen = false; + private boolean newFactionsDefaultPeaceful = false; + + @Comment("When faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit") + private int factionMemberLimit = 0; + + private int maxAlts = 15; + + public int maxAlts(){ + return this.maxAlts; + } + + @Comment("What faction ID to start new players in when they first join the server; default is 0, \"no faction\"") + private String newPlayerStartingFactionID = "0"; + + private double saveToFileEveryXMinutes = 30.0; + + private double autoLeaveAfterDaysOfInactivity = 10.0; + private double autoLeaveRoutineRunsEveryXMinutes = 5.0; + private int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick + private boolean removePlayerDataWhenBanned = true; + private boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. + private double considerFactionsReallyOfflineAfterXMinutes = 0.0; + private int actionDeniedPainAmount = 1; + + @Comment("If enabled, perms can be managed separately for when the faction is offline") + private boolean separateOfflinePerms = false; + + @Comment("Should we delete player homes that they set via Essentials when they leave a Faction\n" + + "if they have homes set in that Faction's territory?") + private boolean deleteEssentialsHomes = true; + + @Comment("Default Relation allows you to change the default relation for Factions.\n" + + "Example usage would be so people can't leave then make a new Faction while Raiding\n" + + " in order to be able to execute commands if the default relation is neutral.") + private String defaultRelation = "neutral"; + + @Comment("Default role of a player when joining a faction. Can be customized by faction leader\n" + + "with /f defaultrole\n" + + "Options: coleader, moderator, member, recruit\n" + + "Defaults to member if set incorrectly") + private String defaultRole = "member"; + @WipeOnReload + private transient Role defaultRoleRole; + + @Comment("If true, disables pistons entirely within faction territory.\n" + + "Prevents flying piston machines in faction territory.") + private boolean disablePistonsInTerritory = false; + + @Comment("Any faction names CONTAINING any of these items will be disallowed") + private List nameBlacklist = new ArrayList() { + { + this.add("blockedwordhere"); + this.add("anotherblockedthinghere"); + } + }; + + public List getNameBlacklist() { + return nameBlacklist == null ? Collections.emptyList() : Collections.unmodifiableList(this.nameBlacklist); + } + + public boolean isDisablePistonsInTerritory() { + return disablePistonsInTerritory; + } + + public boolean isDeleteEssentialsHomes() { + return deleteEssentialsHomes; + } + + public String getDefaultRelation() { + return defaultRelation; + } + + public transient Relation actualDefaultRelation = null; + + public Relation getDefaultRelationActual() { + if(actualDefaultRelation == null){ + actualDefaultRelation = Relation.fromString(defaultRelation); + } + return actualDefaultRelation; + } + + public Role getDefaultRole() { + if (defaultRoleRole == null) { + if (defaultRole == null || (defaultRoleRole = Role.fromString(defaultRole)) == null) { + defaultRoleRole = Role.NORMAL; + } + } + return defaultRoleRole; + } + + public boolean isSeparateOfflinePerms() { + return separateOfflinePerms; + } + + public boolean isAllowMultipleColeaders() { + return allowMultipleColeaders; + } + + public int getTagLengthMin() { + return tagLengthMin; + } + + public int getTagLengthMax() { + return tagLengthMax; + } + + public boolean isTagForceUpperCase() { + return tagForceUpperCase; + } + + public int getFactionMemberLimit() { + return factionMemberLimit; + } + public boolean isNewFactionsDefaultOpen() { + return newFactionsDefaultOpen; + } + + public boolean isNewFactionsDefaultPeaceful() { + return newFactionsDefaultPeaceful; + } + + public String getNewPlayerStartingFactionID() { + return newPlayerStartingFactionID; + } + + public double getSaveToFileEveryXMinutes() { + return saveToFileEveryXMinutes; + } + + public double getAutoLeaveAfterDaysOfInactivity() { + return autoLeaveAfterDaysOfInactivity; + } + + public double getAutoLeaveRoutineRunsEveryXMinutes() { + return autoLeaveRoutineRunsEveryXMinutes; + } + + public int getAutoLeaveRoutineMaxMillisecondsPerTick() { + return autoLeaveRoutineMaxMillisecondsPerTick; + } + + public boolean isRemovePlayerDataWhenBanned() { + return removePlayerDataWhenBanned; + } + + public boolean isAutoLeaveDeleteFPlayerData() { + return autoLeaveDeleteFPlayerData; + } + + public double getConsiderFactionsReallyOfflineAfterXMinutes() { + return considerFactionsReallyOfflineAfterXMinutes; + } + + public int getActionDeniedPainAmount() { + return actionDeniedPainAmount; + } + } + + public class EnterTitles { + private boolean enabled = true; + private int fadeIn = 10; + private int stay = 70; + private int fadeOut = 20; + private boolean alsoShowChat = false; + private String title = "{faction-relation-color}{faction}"; + private String subtitle = "&7{description}"; + + public boolean isEnabled() { + return enabled; + } + + public int getFadeIn() { + return fadeIn; + } + + public int getStay() { + return stay; + } + + public int getFadeOut() { + return fadeOut; + } + + public boolean isAlsoShowChat() { + return alsoShowChat; + } + + public String getTitle() { + return title; + } + + public String getSubtitle() { + return subtitle; + } + } + + private Chat chat = new Chat(); + private Homes homes = new Homes(); + @Comment("Limits factions to having a max number of each relation.\n" + + "Setting to 0 means none allowed. -1 for disabled.\n" + + "This will have no effect on default or existing relations, only when relations are changed.\n" + + "It is advised that you set the default relation to -1 so they can always go back to that.\n" + + "Otherwise Factions could be stuck with not being able to unenemy other Factions.") + private MaxRelations maxRelations = new MaxRelations(); + private PVP pvp = new PVP(); + private SpecialCase specialCase = new SpecialCase(); + private Claims claims = new Claims(); + @Comment("Do you want to limit portal creation?") + private Portals portals = new Portals(); + private Protection protection = new Protection(); + @Comment("For claimed areas where further faction-member ownership can be defined") + private OwnedArea ownedArea = new OwnedArea(); + @Comment("Displayed prefixes for different roles within a faction") + private Prefix prefixes = new Prefix(); + private LandRaidControl landRaidControl = new LandRaidControl(); + @Comment("Remaining settings not categorized") + private Other other = new Other(); + @Comment("Should we send titles when players enter Factions? Durations are in ticks (20 ticks every second)") + private EnterTitles enterTitles = new EnterTitles(); + @Comment("Spawn control.\n" + + "Exception names are entity type names as seen at the below URL.\n" + + "Note that any name with an underscore MUST have quotes around it.\n" + + "https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/entity/EntityType.html\n" + + "Spawn types are those at the below URL:\n" + + "https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/event/entity/CreatureSpawnEvent.SpawnReason.html") + private Spawning spawning = new Spawning(); + + public EnterTitles enterTitles() { + return enterTitles; + } + + public Chat chat() { + return chat; + } + + public Homes homes() { + return homes; + } + + public MaxRelations maxRelations() { + return maxRelations; + } + + public PVP pvp() { + return pvp; + } + + public SpecialCase specialCase() { + return specialCase; + } + + public Claims claims() { + return claims; + } + + public Portals portals() { + return portals; + } + + public Protection protection() { + return protection; + } + + public Other other() { + return other; + } + + public OwnedArea ownedArea() { + return ownedArea; + } + + public Prefix prefixes() { + return prefixes; + } + + public LandRaidControl landRaidControl() { + return landRaidControl; + } + + public Spawning spawning() { + return spawning; + } + } + + public class Logging { + private boolean factionCreate = true; + private boolean factionDisband = true; + private boolean factionJoin = true; + private boolean factionKick = true; + private boolean factionLeave = true; + private boolean landClaims = true; + private boolean landUnclaims = true; + private boolean moneyTransactions = true; + private boolean playerCommands = true; + + public boolean isFactionCreate() { + return factionCreate; + } + + public boolean isFactionDisband() { + return factionDisband; + } + + public boolean isFactionJoin() { + return factionJoin; + } + + public boolean isFactionKick() { + return factionKick; + } + + public boolean isFactionLeave() { + return factionLeave; + } + + public boolean isLandClaims() { + return landClaims; + } + + public boolean isLandUnclaims() { + return landUnclaims; + } + + public boolean isMoneyTransactions() { + return moneyTransactions; + } + + public boolean isPlayerCommands() { + return playerCommands; + } + } + + public class Exploits { + private boolean obsidianGenerators = true; + private boolean enderPearlClipping = true; + private boolean interactionSpam = true; + private boolean tntWaterlog = false; + private boolean liquidFlow = false; + private boolean preventDuping = true; + + public boolean isObsidianGenerators() { + return obsidianGenerators; + } + + public boolean isEnderPearlClipping() { + return enderPearlClipping; + } + + public boolean isInteractionSpam() { + return interactionSpam; + } + + public boolean isTntWaterlog() { + return tntWaterlog; + } + + public boolean isLiquidFlow() { + return liquidFlow; + } + + public boolean doPreventDuping() { + return preventDuping; + } + } + + public class Economy { + @Comment("\n******************\n\n" + + "The value \"enabled\" must be true for any economy features\n" + + "Make sure that you confirm the \"defaultWorld\" setting is a valid world name\n"+ + "\n******************\n") + private boolean enabled = false; + private String universeAccount = ""; + @Comment("This setting matters in particular if you have per-world economy.\n" + + "This setting is the world to use for:\n" + + " faction banks,\n" + + " the universe account (if used),\n" + + " transferring money to a player who is presently offline,\n" + + " or any other situation where the player's world is unknown.\n\n" + + "Note that you should set up your per-world plugin to treat all your Factions worlds as one group/world.") + private String defaultWorld = "world"; + private double costClaimWilderness = 30.0; + private double costClaimFromFactionBonus = 30.0; + private double overclaimRewardMultiplier = 0.0; + private double claimAdditionalMultiplier = 0.5; + private double claimRefundMultiplier = 0.7; + private double claimUnconnectedFee = 0.0; + private double costCreate = 100.0; + private double costOwner = 15.0; + private double costSethome = 30.0; + private double costDelhome = 30.0; + private double costJoin = 0.0; + private double costLeave = 0.0; + private double costKick = 0.0; + private double costInvite = 0.0; + private double costHome = 0.0; + private double costTag = 0.0; + private double costDesc = 0.0; + private double costTitle = 0.0; + private double costList = 0.0; + private double costMap = 0.0; + private double costPower = 0.0; + private double costShow = 0.0; + private double costStuck = 0.0; + private double costDTR = 0.0; + private double costOpen = 0.0; + private double costAlly = 0.0; + private double costTruce = 0.0; + private double costEnemy = 0.0; + private double costNeutral = 0.0; + private double costNoBoom = 0.0; + // Calculate if enabled + private double costWarp = 0.0; + private double costSetWarp = 0.0; + private double costDelWarp = 0.0; + + @Comment("Faction banks, to pay for land claiming and other costs instead of individuals paying for them\n" + + "This IS NOT the setting for enabling economy features overall. That setting is just named \"enabled\"") + private boolean bankEnabled = true; + @Comment("Have to be at least moderator to withdraw or pay money to another faction") + private boolean bankMembersCanWithdraw = false; + @Comment("The faction pays for faction command costs, such as sethome") + private boolean bankFactionPaysCosts = true; + @Comment("The faction pays for land claiming costs.") + private boolean bankFactionPaysLandCosts = true; + + public boolean isEnabled() { + return enabled; + } + + public String getDefaultWorld() { + return defaultWorld; + } + + public double getCostDTR() { + return costDTR; + } + + public String getUniverseAccount() { + return universeAccount; + } + + public double getCostClaimWilderness() { + return costClaimWilderness; + } + + public double getCostClaimFromFactionBonus() { + return costClaimFromFactionBonus; + } + + public double getOverclaimRewardMultiplier() { + return overclaimRewardMultiplier; + } + + public double getClaimAdditionalMultiplier() { + return claimAdditionalMultiplier; + } + + public double getClaimRefundMultiplier() { + return claimRefundMultiplier; + } + + public double getClaimUnconnectedFee() { + return claimUnconnectedFee; + } + + public double getCostCreate() { + return costCreate; + } + + public double getCostOwner() { + return costOwner; + } + + public double getCostSethome() { + return costSethome; + } + + public double getCostDelhome() { + return costDelhome; + } + + public double getCostJoin() { + return costJoin; + } + + public double getCostLeave() { + return costLeave; + } + + public double getCostKick() { + return costKick; + } + + public double getCostInvite() { + return costInvite; + } + + public double getCostHome() { + return costHome; + } + + public double getCostTag() { + return costTag; + } + + public double getCostDesc() { + return costDesc; + } + + public double getCostTitle() { + return costTitle; + } + + public double getCostList() { + return costList; + } + + public double getCostMap() { + return costMap; + } + + public double getCostPower() { + return costPower; + } + + public double getCostShow() { + return costShow; + } + + public double getCostStuck() { + return costStuck; + } + + public double getCostOpen() { + return costOpen; + } + + public double getCostAlly() { + return costAlly; + } + + public double getCostTruce() { + return costTruce; + } + + public double getCostEnemy() { + return costEnemy; + } + + public double getCostNeutral() { + return costNeutral; + } + + public double getCostNoBoom() { + return costNoBoom; + } + + public double getCostWarp() { + return costWarp; + } + + public double getCostSetWarp() { + return costSetWarp; + } + + public double getCostDelWarp() { + return costDelWarp; + } + + public boolean isBankEnabled() { + return bankEnabled; + } + + public boolean isBankMembersCanWithdraw() { + return bankMembersCanWithdraw; + } + + public boolean isBankFactionPaysCosts() { + return bankFactionPaysCosts; + } + + public boolean isBankFactionPaysLandCosts() { + return bankFactionPaysLandCosts; + } + } + + public class MapSettings { + private int height = 17; + private int width = 49; + private boolean showFactionKey = true; + private boolean showNeutralFactionsOnMap = true; + private boolean showEnemyFactions = true; + private boolean showTruceFactions = true; + + public int getHeight() { + return height; + } + + public int getWidth() { + return width; + } + + public boolean isShowFactionKey() { + return showFactionKey; + } + + public boolean isShowNeutralFactionsOnMap() { + return showNeutralFactionsOnMap; + } + + public boolean isShowEnemyFactions() { + return showEnemyFactions; + } + + public boolean isShowTruceFactions() { + return showTruceFactions; + } + } + + public class Data { + public class Json { + @Comment("If true, data files will be stored without extra whitespace and linebreaks.\n" + + "This becomes less readable, but can cut storage use in half.") + private boolean efficientStorage = false; + + public boolean useEfficientStorage() { + return efficientStorage; + } + } + + @Comment("Presently, the only option is JSON.") + private String storage = "JSON"; + private Json json = new Json(); + + public Json json() { + return json; + } + } + + public class RestrictWorlds { + @Comment("If true, Factions will only function on certain worlds") + private boolean restrictWorlds = false; + @Comment("If restrictWorlds is true, this setting determines if the world list below is a whitelist or blacklist.\n" + + "True for whitelist, false for blacklist.") + private boolean whitelist = true; + private Set worldList = new HashSet() { + { + this.add("exampleWorld"); + } + }; + + public boolean isRestrictWorlds() { + return restrictWorlds; + } + + public boolean isWhitelist() { + return whitelist; + } + + public Set getWorldList() { + return worldList == null ? Collections.emptySet() : Collections.unmodifiableSet(worldList); + } + } + + public class Scoreboard { + public class Constant { + private boolean enabled = false; + @Comment("Can use any placeholders, but does not update once set") + private String title = "Faction Status"; + @Comment("If true, show faction prefixes on nametags and in tab list if scoreboard is enabled") + private boolean prefixes = true; + @Comment("Set the length limit for prefixes.\n" + + "If 0, will use a sane default for your Minecraft version (16 for pre-1.13, 32 for 1.13+).") + private int prefixLength = 0; + @Comment("Takes {relationcolor}, {faction}, player-specific tags, &-prefixed color codes") + private String prefixTemplate = "{relationcolor}[{faction}] &r"; + + @Comment("If true, show suffixes on nametags and in tab list if scoreboard is enabled") + private boolean suffixes = false; + @Comment("Set the length limit for suffixes.\n" + + "If 0, will use a sane default for your Minecraft version (16 for pre-1.13, 32 for 1.13+).") + private int suffixLength = 0; + @Comment("Takes {relationcolor}, {faction}, player-specific tags, &-prefixed color codes") + private String suffixTemplate = " {relationcolor}[{faction}]"; + + private List content = new ArrayList() { + { + this.add("&6Your Faction"); + this.add("{faction}"); + this.add("&3Your Power"); + this.add("{power}"); + this.add("&aBalance"); + this.add("${balance}"); + } + }; + private boolean factionlessEnabled = false; + private List factionlessContent = new ArrayList() { + { + this.add("Make a new Faction"); + this.add("Use /f create"); + } + }; + private String factionlessTitle = "Status"; + + public boolean isEnabled() { + return enabled; + } + + public String getTitle() { + return title; + } + + public boolean isPrefixes() { + return prefixes; + } + + public int getPrefixLength() { + return prefixLength < 1 ? (FactionsPlugin.getMCVersion() < 1300 ? 16 : 32) : prefixLength; + } + + public String getPrefixTemplate() { + return prefixTemplate; + } + + public boolean isSuffixes() { + return suffixes; + } + + public int getSuffixLength() { + return suffixLength < 1 ? (FactionsPlugin.getMCVersion() < 1300 ? 16 : 32) : suffixLength; + } + + public String getSuffixTemplate() { + return suffixTemplate; + } + + public List getContent() { + return content != null ? Collections.unmodifiableList(content) : Collections.emptyList(); + } + + public boolean isFactionlessEnabled() { + return factionlessEnabled; + } + + public List getFactionlessContent() { + return factionlessContent != null ? Collections.unmodifiableList(factionlessContent) : Collections.emptyList(); + } + + public String getFactionlessTitle() { + return factionlessTitle; + } + } + + public class Info { + @Comment("send faction change message as well when scoreboard is up?") + private boolean alsoSendChat = true; + @Comment("How long do we want scoreboards to stay") + private int expiration = 7; + private boolean enabled = false; + @Comment("Supports placeholders") + private List content = new ArrayList() { + { + this.add("&6Power"); + this.add("{power}"); + this.add("&3Members"); + this.add("{online}/{members}"); + this.add("&4Leader"); + this.add("{leader}"); + this.add("&bTerritory"); + this.add("{chunks}"); + } + }; + private String title = "{faction-relation-color}{faction}"; + + public boolean isAlsoSendChat() { + return alsoSendChat; + } + + public int getExpiration() { + return expiration; + } + + public boolean isEnabled() { + return enabled; + } + + public List getContent() { + return content != null ? Collections.unmodifiableList(content) : Collections.emptyList(); + } + + public String getTitle() { + return title; + } + } + + @Comment("Constant scoreboard stays around all the time, displaying status info.\n" + + "Also, if prefixes are enabled while it is enabled, will show prefixes on nametags and tab") + private Constant constant = new Constant(); + @Comment("Info scoreboard is displayed when a player walks into a new Faction's territory.\n" + + "Scoreboard disappears after seconds.") + private Info info = new Info(); + + public Constant constant() { + return constant; + } + + public Info info() { + return info; + } + } + + public class Upgrades { + private boolean enabled = true; + + public boolean isEnabled() { + return enabled; + } + + public class TnT { + private boolean enabled = true; + + private int defaultTnT = 100000; + + @Comment("This list follows the format of (PRICE):(TNT). The order of the list is crucial as it dictates the level.") + private List levels = new ArrayList(){ + { + this.add("50000:500000"); + this.add("100000:1000000"); + this.add("1000000:10000000"); + } + }; + + public int getCost(int level){ + if(level <= 0 || levels.size() == 0 || levels.size() < level)return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[0]); + } + + public int getNumber(int level){ + if(level <= 0)return getDefaultTnT(); + + if(levels.size() == 0 || levels.size() < level)return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[1]); + } + + public List getLevels() { + return levels; + } + + private Item item = new Item(); + + public boolean isEnabled(){ + return this.enabled; + } + + public int getDefaultTnT() { + return defaultTnT; + } + + public Item item(){ + return item; + } + + public class Item { + private String type = "TNT"; + + private String name = "&c&lTnT Bank Upgrade"; + + private int slot = 6; + + private int damage = 0; + + public int getSlot() { + return slot; + } + + private List lore = new ArrayList(){ + { + this.add("&7"); + this.add("&d* &eLevel 1"); + this.add("&ePrice: &a${PRICE_1}"); + this.add("&eAmount: &c{AMOUNT_1}"); + this.add("&7"); + this.add("&d* &eLevel 2"); + this.add("&ePrice: &a${PRICE_2}"); + this.add("&eAmount: &c{AMOUNT_2}"); + this.add("&7"); + this.add("&d* &eLevel 3"); + this.add("&ePrice: &a${PRICE_3}"); + this.add("&eAmount: &c{AMOUNT_3}"); + this.add("&7"); + this.add("&7Current Level: &d&n{LEVEL}"); + } + }; + + public SimpleItem getItem(){ + return SimpleItem.builder().setMaterial(Material.valueOf(type)) + .setData((short) damage) + .setLore(lore) + .setName(TextUtil.parseColor(name)) + .build(); + } + } + } + + public class Chest { + private boolean enabled = true; + + private int defaultRows = 1; + + private boolean preventSpawnersInChest = true; + + private String chestName = "&eFaction Chest"; + + @Comment("This list follows the format of (PRICE):(ROWS). The order of the list is crucial as it dictates the level.") + private List levels = new ArrayList(){ + { + this.add("50000:4"); + this.add("100000:5"); + this.add("1000000:6"); + } + }; + + public int getCost(int level){ + if(level <= 0 || levels.size() == 0 || levels.size() < level)return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[0]); + } + + public boolean preventSpawnersInChest(){ + return preventSpawnersInChest; + } + + public int getNumber(int level){ + if(level <= 0)return getDefaultRows(); + + if(levels.size() == 0 || levels.size() < level)return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[1]); + } + + public List getLevels() { + return levels; + } + + private Item item = new Item(); + + public boolean isEnabled(){ + return this.enabled; + } + + public String getChestName() { + return chestName; + } + + public int getDefaultRows() { + return defaultRows; + } + + public Item item(){ + return item; + } + + public class Item { + private String type = "CHEST"; + + private String name = "&e&lChest Upgrade"; + + private int slot = 5; + + private int damage = 0; + + public int getSlot() { + return slot; + } + + private List lore = new ArrayList(){ + { + this.add("&7"); + this.add("&d* &eLevel 1"); + this.add("&ePrice: &a${PRICE_1}"); + this.add("&eAmount: &c{AMOUNT_1}"); + this.add("&7"); + this.add("&d* &eLevel 2"); + this.add("&ePrice: &a${PRICE_2}"); + this.add("&eAmount: &c{AMOUNT_2}"); + this.add("&7"); + this.add("&d* &eLevel 3"); + this.add("&ePrice: &a${PRICE_3}"); + this.add("&eAmount: &c{AMOUNT_3}"); + this.add("&7"); + this.add("&7Current Level: &d&n{LEVEL}"); + } + }; + + public SimpleItem getItem(){ + return SimpleItem.builder().setMaterial(Material.valueOf(type)) + .setData((short) damage) + .setLore(lore) + .setName(TextUtil.parseColor(name)) + .build(); + } + } + } +/* + + public class SpawnerBoost { + private boolean enabled = true; + + private double defaultBoost = 1; + + @Comment("This list follows the format of (PRICE):(Boost in decimal). The order of the list is crucial as it dictates the level.") + private List levels = new ArrayList(){ + { + this.add("250000:1.1"); + this.add("500000:1.2"); + this.add("1000000:1.3"); + } + }; + + public int getCost(int level){ + if(level <= 0 || levels.size() == 0 || levels.size() < level)return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[0]); + } + + public double getNumber(int level){ + if(level <= 0)return getDefaultBoost(); + + if(levels.size() == 0 || levels.size() < level)return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Double.parseDouble(costs[1]); + } + + public List getLevels() { + return levels; + } + + private Item item = new Item(); + + public boolean isEnabled(){ + return this.enabled; + } + + public double getDefaultBoost() { + return defaultBoost; + } + + public Item item(){ + return item; + } + + public class Item { + private String type = "MOB_SPAWNER"; + + private String name = "&1&lSpawner Boost"; + + private int slot = 2; + + private int damage = 0; + + public int getSlot() { + return slot; + } + + private List lore = new ArrayList(){ + { + this.add("&7"); + this.add("&d* &eLevel 1"); + this.add("&ePrice: &a${PRICE_1}"); + this.add("&eAmount: &c{AMOUNT_1}"); + this.add("&7"); + this.add("&d* &eLevel 2"); + this.add("&ePrice: &a${PRICE_2}"); + this.add("&eAmount: &c{AMOUNT_2}"); + this.add("&7"); + this.add("&d* &eLevel 3"); + this.add("&ePrice: &a${PRICE_3}"); + this.add("&eAmount: &c{AMOUNT_3}"); + this.add("&7"); + this.add("&7Current Level: &d&n{LEVEL}"); + } + }; + + public SimpleItem getItem(){ + return SimpleItem.builder().setMaterial(Material.valueOf(type)) + .setData((short) damage) + .setLore(lore) + .setName(TextUtil.parseColor(name)) + .build(); + } + } + } +*/ + + public class WarpAmount { + private boolean enabled = true; + + private int defaultWarpAmount = 0; + + @Comment("This list follows the format of (PRICE):(gain access to more faction warps). The order of the list is crucial as it dictates the level.") + private List levels = new ArrayList(){ + { + this.add("250000:5"); + this.add("500000:8"); + this.add("1000000:10"); + } + }; + + public int getCost(int level){ + if (level <= 0 || levels.size() == 0 || levels.size() < level) return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[0]); + } + + public int getNumber(int level){ + if(level <= 0) return getDefaultWarpAmount(); + + if(levels.size() == 0 || levels.size() < level) return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[1]); + } + + public List getLevels() { + return levels; + } + + private Item item = new Item(); + + public boolean isEnabled(){ + return this.enabled; + } + + public int getDefaultWarpAmount() { + return defaultWarpAmount; + } + + public Item item(){ + return item; + } + + public class Item { + private String type = "ENDER_PEARL"; + + private String name = "&aWarp Amount"; + + private int slot = 2; + + private int damage = 0; + + public int getSlot() { + return slot; + } + + private List lore = new ArrayList(){ + { + this.add("&7"); + this.add("&d* &eLevel 1"); + this.add("&ePrice: &a${PRICE_1}"); + this.add("&eAmount: &c{AMOUNT_1}"); + this.add("&7"); + this.add("&d* &eLevel 2"); + this.add("&ePrice: &a${PRICE_2}"); + this.add("&eAmount: &c{AMOUNT_2}"); + this.add("&7"); + this.add("&d* &eLevel 3"); + this.add("&ePrice: &a${PRICE_3}"); + this.add("&eAmount: &c{AMOUNT_3}"); + this.add("&7"); + this.add("&7Current Level: &d&n{LEVEL}"); + } + }; + + public SimpleItem getItem(){ + return SimpleItem.builder().setMaterial(Material.valueOf(type)) + .setData((short) damage) + .setLore(lore) + .setName(TextUtil.parseColor(name)) + .build(); + } + } + } + + private WarpAmount warpAmount = new WarpAmount(); + + public WarpAmount warpAmount(){ + return this.warpAmount; + } + + public class FactionSize { + private boolean enabled = true; + + private int defaultFactionSize = 15; + + @Comment("This list follows the format of (PRICE):(gain access to more faction warps). The order of the list is crucial as it dictates the level.") + private List levels = new ArrayList<>(Arrays.asList( + "250000:" + defaultFactionSize + 1, + "250000:" + defaultFactionSize + 2, + "250000:" + defaultFactionSize + 3, + "250000:" + defaultFactionSize + 4, + "250000:" + defaultFactionSize + 5 + )); + + public int getCost(int level){ + if (level <= 0 || levels.size() == 0 || levels.size() < level) return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[0]); + } + + public int getNumber(int level){ + if(level <= 0) return getDefaultFactionSize(); + + if(levels.size() == 0 || levels.size() < level) return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[1]); + } + + public List getLevels() { + return levels; + } + + private Item item = new Item(); + + public boolean isEnabled(){ + return this.enabled; + } + + public int getDefaultFactionSize() { + return defaultFactionSize; + } + + public Item item(){ + return item; + } + + public class Item { + private String type = "ARMOR_STAND"; + + private String name = "&aFaction Size"; + + private int slot = 0; + + private int damage = 0; + + public int getSlot() { + return slot; + } + + private List lore = new ArrayList(){ + { + this.add("&7"); + this.add("&d* &eLevel 1"); + this.add("&ePrice: &a${PRICE_1}"); + this.add("&eAmount: &c{AMOUNT_1}"); + this.add("&7"); + this.add("&d* &eLevel 2"); + this.add("&ePrice: &a${PRICE_2}"); + this.add("&eAmount: &c{AMOUNT_2}"); + this.add("&7"); + this.add("&d* &eLevel 3"); + this.add("&ePrice: &a${PRICE_3}"); + this.add("&eAmount: &c{AMOUNT_3}"); + this.add("&7"); + this.add("&7"); + this.add("&d* &eLevel 4"); + this.add("&ePrice: &a${PRICE_4}"); + this.add("&eAmount: &c{AMOUNT_4}"); + this.add("&7"); + this.add("&d* &eLevel 5"); + this.add("&ePrice: &a${PRICE_5}"); + this.add("&eAmount: &c{AMOUNT_5}"); + this.add("&7Current Level: &d&n{LEVEL}"); + } + }; + + public SimpleItem getItem(){ + return SimpleItem.builder().setMaterial(Material.valueOf(type)) + .setData((short) damage) + .setLore(lore) + .setName(TextUtil.parseColor(name)) + .build(); + } + } + } + + private FactionSize factionSize = new FactionSize(); + + public FactionSize factionSize(){ + return this.factionSize; + } + +/* + public class CropBoost { + private boolean enabled = true; + + private double defaultBoost = 0; + + @Comment("This list follows the format of (PRICE):(Chance to double grow). The order of the list is crucial as it dictates the level.") + private List levels = new ArrayList(){ + { + this.add("250000:0.5"); + this.add("500000:0.6"); + this.add("1000000:0.7"); + } + }; + + public int getCost(int level){ + if(level <= 0 || levels.size() == 0 || levels.size() < level)return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Integer.parseInt(costs[0]); + } + + public double getNumber(int level){ + if(level <= 0)return getDefaultBoost(); + + if(levels.size() == 0 || levels.size() < level)return -1; + + String[] costs = levels.get(level - 1).split(":"); + + return Double.parseDouble(costs[1]); + } + + public List getLevels() { + return levels; + } + + private Item item = new Item(); + + public boolean isEnabled(){ + return this.enabled; + } + + public double getDefaultBoost() { + return defaultBoost; + } + + public Item item(){ + return item; + } + + public class Item { + private String type = "SUGAR_CANE"; + + private String name = "&2&lCrop Boost"; + + private int slot = 3; + + private int damage = 0; + + public int getSlot() { + return slot; + } + + private List lore = new ArrayList(){ + { + this.add("&7"); + this.add("&d* &eLevel 1"); + this.add("&ePrice: &a${PRICE_1}"); + this.add("&eAmount: &c{AMOUNT_1}"); + this.add("&7"); + this.add("&d* &eLevel 2"); + this.add("&ePrice: &a${PRICE_2}"); + this.add("&eAmount: &c{AMOUNT_2}"); + this.add("&7"); + this.add("&d* &eLevel 3"); + this.add("&ePrice: &a${PRICE_3}"); + this.add("&eAmount: &c{AMOUNT_3}"); + this.add("&7"); + this.add("&7Current Level: &d&n{LEVEL}"); + } + }; + + public SimpleItem getItem(){ + return SimpleItem.builder().setMaterial(Material.valueOf(type)) + .setData((short) damage) + .setLore(lore) + .setName(TextUtil.parseColor(name)) + .build(); + } + } + } + + private CropBoost cropBoost = new CropBoost(); + + public CropBoost cropBoost(){ + return this.cropBoost; + } +*/ + + private TnT tnt = new TnT(); + + public TnT tnt(){ + return tnt; + } + + private Chest chest = new Chest(); + + public Chest chest(){ + return chest; + } + + /*private SpawnerBoost spawnerBoost = new SpawnerBoost(); + + public SpawnerBoost spawnerBoost(){ + return this.spawnerBoost; + }*/ + + public class GUI { + private int rows = 1; + + public int getRows() { + return rows; + } + + public Filler filler(){ + return filler; + } + + public class Filler { + private String type = "STAINED_GLASS_PANE"; + + private String name = "&7"; + + private int slot = 0; + + private int damage = 7; + + private List lore = new ArrayList<>(); + + public ItemStack getItem(){ + ItemStack itemStack = new ItemStack(Material.valueOf(type), 1, (short) damage); + + ItemMeta itemMeta = itemStack.getItemMeta(); + + itemMeta.setDisplayName(TextUtil.parseColor(name)); + + itemMeta.setLore(lore); + + itemStack.setItemMeta(itemMeta); + return itemStack; + } + } + + private Filler filler = new Filler(); + } + + private GUI gui = new GUI(); + + public GUI gui(){ + return this.gui; + } + } + + public class LWC { + private boolean enabled = true; + private boolean resetLocksOnUnclaim = false; + private boolean resetLocksOnCapture = false; + + public boolean isEnabled() { + return enabled; + } + + public boolean isResetLocksOnUnclaim() { + return resetLocksOnUnclaim; + } + + public boolean isResetLocksOnCapture() { + return resetLocksOnCapture; + } + } + + public class Paper { + @Comment("Utilize Paper's async teleportation if available (Paper 1.9+).") + private boolean asyncTeleport = true; + + public boolean isAsyncTeleport() { + return asyncTeleport; + } + } + + public class PlayerVaults { + @Comment("The %s is for the faction id") + private String vaultPrefix = "faction-%s"; + private int defaultMaxVaults = 0; + + public String getVaultPrefix() { + return vaultPrefix; + } + + public int getDefaultMaxVaults() { + return defaultMaxVaults; + } + } + + public class WorldGuard { + private boolean checking = false; + private boolean buildPriority = false; + + public boolean isChecking() { + return checking; + } + + public boolean isBuildPriority() { + return buildPriority; + } + } + + public class WorldBorder { + @Comment("WorldBorder support\n" + + "This is for Minecraft's built-in command. To get your current border: /minecraft:worldborder get\n" + + "A buffer of 0 means faction claims can go right up to the border of the world.\n" + + "The buffer is in chunks, so 1 as a buffer means an entire chunk of buffer between\n" + + "the border of the world and what can be claimed to factions") + private int buffer = 0; + + public int getBuffer() { + return buffer; + } + } + + @Comment("The command base (by default f, making the command /f)") + private List commandBase = new ArrayList() { + { + this.add("f"); + } + }; + + @Comment("The time zone to use when dealing with timely matters") + private String timeZone = "America/New_York"; + + @Comment("FactionsUUID by drtshock\n" + + "Support and documentation https://factions.support\n" + + "Updates https://www.spigotmc.org/resources/factionsuuid.1035/\n" + + "\n" + + "Made with love <3") + private AVeryFriendlyFactionsConfig aVeryFriendlyFactionsConfig = new AVeryFriendlyFactionsConfig(); + + @Comment("Colors for relationships and default factions") + private Colors colors = new Colors(); + private Corner corner = new Corner(); + private Commands commands = new Commands(); + private Factions factions = new Factions(); + private Upgrades upgrades = new Upgrades(); + @Comment("What should be logged?") + private Logging logging = new Logging(); + @Comment("Controls certain exploit preventions") + private Exploits exploits = new Exploits(); + @Comment("Economy support requires Vault and a compatible economy plugin\n" + + "If you wish to use economy features, be sure to set 'enabled' in this section to true!") + private Economy economy = new Economy(); + @Comment("Control for the default settings of /f map") + private MapSettings map = new MapSettings(); + @Comment("Data storage settings") + private Data data = new Data(); + private RestrictWorlds restrictWorlds = new RestrictWorlds(); + private Scoreboard scoreboard = new Scoreboard(); + @Comment("LWC integration\n" + + "This support targets the modern fork of LWC, called LWC Extended.\n" + + "You can find it here: https://www.spigotmc.org/resources/lwc-extended.69551/\n" + + "Note: Modern LWC is no longer supported, and its former maintainer now runs LWC Extended") + private LWC lwc = new LWC(); + @Comment("Paper features, when accessible.") + private Paper paper = new Paper(); + @Comment("PlayerVaults faction vault settings.\n" + + "Enable faction-owned vaults!\n" + + "https://www.spigotmc.org/resources/playervaultsx.51204/") + private PlayerVaults playerVaults = new PlayerVaults(); + @Comment("WorldGuard settings") + private WorldGuard worldGuard = new WorldGuard(); + private WorldBorder worldBorder = new WorldBorder(); + + private OnlineChecks onlineChecks = new OnlineChecks(); + + public class OnlineChecks { + @Comment("Dictates whether we will use the hasOnlinePlayers method in block breaks.\n" + + "This will improve performance a small amount if set to false") + private boolean doOnlineChecks = false; + + public boolean doOnlineChecks(){ + return doOnlineChecks; + } + } + + public Corner corner(){return corner;} + + public List getCommandBase() { + return commandBase == null ? (commandBase = Collections.singletonList("f")) : commandBase; + } + + public String getTimeZone() { + return timeZone; + } + + public AVeryFriendlyFactionsConfig getaVeryFriendlyFactionsConfig() { + return aVeryFriendlyFactionsConfig; + } + + public Colors colors() { + return colors; + } + + public Commands commands() { + return commands; + } + + public Factions factions() { + return factions; + } + + public Logging logging() { + return logging; + } + + public Upgrades upgrades(){ + return upgrades; + } + + public Exploits exploits() { + return exploits; + } + + public Economy economy() { + return economy; + } + + public MapSettings map() { + return map; + } + + public OnlineChecks onlineChecks(){return onlineChecks;} + + public RestrictWorlds restrictWorlds() { + return restrictWorlds; + } + + public Scoreboard scoreboard() { + return scoreboard; + } + + public Paper paper() { + return paper; + } + + public PlayerVaults playerVaults() { + return playerVaults; + } + + public WorldGuard worldGuard() { + return worldGuard; + } + + public LWC lwc() { + return lwc; + } + + public WorldBorder worldBorder() { + return worldBorder; + } + + public Data data() { + return data; + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/Transitioner.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/Transitioner.java new file mode 100644 index 0000000..e6768d0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/Transitioner.java @@ -0,0 +1,200 @@ +package com.massivecraft.factions.config.transition; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.Loader; +import com.massivecraft.factions.config.transition.oldclass.v0.MaterialAdapter; +import com.massivecraft.factions.config.transition.oldclass.v0.NewMemoryFaction; +import com.massivecraft.factions.config.transition.oldclass.v0.OldAccessV0; +import com.massivecraft.factions.config.transition.oldclass.v0.OldConfV0; +import com.massivecraft.factions.config.transition.oldclass.v0.OldMemoryFactionV0; +import com.massivecraft.factions.config.transition.oldclass.v0.OldPermissableActionV0; +import com.massivecraft.factions.config.transition.oldclass.v0.OldPermissableV0; +import com.massivecraft.factions.config.transition.oldclass.v0.OldPermissionsMapTypeAdapterV0; +import com.massivecraft.factions.config.transition.oldclass.v0.TransitionConfigV0; +import com.massivecraft.factions.config.transition.oldclass.v1.OldMainConfigV1; +import com.massivecraft.factions.config.transition.oldclass.v1.TransitionConfigV1; +import com.massivecraft.factions.util.EnumTypeAdapter; +import com.massivecraft.factions.util.LazyLocation; +import com.massivecraft.factions.util.MapFLocToStringSetTypeAdapter; +import com.massivecraft.factions.util.MyLocationTypeAdapter; +import com.massivecraft.factions.util.TL; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.hocon.HoconConfigurationLoader; +import org.bukkit.Material; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; + +public class Transitioner { + private FactionsPlugin plugin; + private Gson gsonV0; + + public static void transition(FactionsPlugin plugin) { + Transitioner transitioner = new Transitioner(plugin); + transitioner.migrateV0(); + + Path confPath = plugin.getDataFolder().toPath().resolve("config").resolve("main.conf"); + if (!confPath.toFile().exists()) { + return; + } + + HoconConfigurationLoader loader = Loader.getLoader("main"); + try { + CommentedConfigurationNode rootNode = loader.load(); + CommentedConfigurationNode versionNode = rootNode.getNode("aVeryFriendlyFactionsConfig").getNode("version"); + + if (versionNode.isVirtual()) { + transitioner.migrateV1(loader); + rootNode = loader.load(); + versionNode = rootNode.getNode("aVeryFriendlyFactionsConfig").getNode("version"); + if (versionNode.isVirtual()) { + return; // Failure! + } + } + + int version = rootNode.getNode("aVeryFriendlyFactionsConfig").getNode("version").getInt(); + if (version < 3) { + transitioner.migrateV2(rootNode); + } + if (version < 4) { + transitioner.migrateV3(rootNode); + } + + loader.save(rootNode); + } catch (IOException e) { + plugin.getLogger().log(Level.SEVERE, "Failed to save configuration migration! Data may be lost, requiring restoration from backups.", e); + } + } + + private Transitioner(FactionsPlugin plugin) { + this.plugin = plugin; + } + + private void migrateV0() { + Path pluginFolder = this.plugin.getDataFolder().toPath(); + Path configFolder = pluginFolder.resolve("config"); + if (configFolder.toFile().exists()) { + // Found existing config, so nothing to do here. + return; + } + Path oldConf = pluginFolder.resolve("conf.json"); + if (!oldConf.toFile().exists()) { + // No config, no conversion! + return; + } + Path oldConfigFolder = pluginFolder.resolve("oldConfig"); + File oldConfigFolderFile = oldConfigFolder.toFile(); + if (oldConfigFolderFile.exists()) { + // Found existing oldConfig, implying it was already upgraded once + this.plugin.getLogger().warning("Found no 'config' folder, but an 'oldConfig' exists. Not attempting conversion."); + return; + } + this.plugin.getLogger().info("Found no 'config' folder. Starting configuration transition..."); + this.buildV0Gson(); + try { + OldConfV0 conf = this.gsonV0.fromJson(new String(Files.readAllBytes(oldConf), StandardCharsets.UTF_8), OldConfV0.class); + TransitionConfigV0 newConfig = new TransitionConfigV0(conf); + Loader.loadAndSave("main", newConfig); + oldConfigFolderFile.mkdir(); + Path dataFolder = pluginFolder.resolve("data"); + dataFolder.toFile().mkdir(); + Files.move(pluginFolder.resolve("board.json"), dataFolder.resolve("board.json")); + Files.move(pluginFolder.resolve("players.json"), dataFolder.resolve("players.json")); + + Path oldFactions = pluginFolder.resolve("factions.json"); + Map data = this.gsonV0.fromJson(new String(Files.readAllBytes(oldFactions), StandardCharsets.UTF_8), new TypeToken>() { + }.getType()); + Map newData = new HashMap<>(); + data.forEach((id, fac) -> newData.put(id, new NewMemoryFaction(fac))); + Files.write(dataFolder.resolve("factions.json"), this.plugin.getGson().toJson(newData).getBytes(StandardCharsets.UTF_8)); + + Files.move(oldFactions, oldConfigFolder.resolve("factions.json")); + Files.move(oldConf, oldConfigFolder.resolve("conf.json")); + this.plugin.getLogger().info("Transition complete!"); + } catch (Exception e) { + this.plugin.getLogger().log(Level.SEVERE, "Could not convert old conf.json", e); + } + } + + private void buildV0Gson() { + Type mapFLocToStringSetType = new TypeToken>>() { + }.getType(); + + Type accessTypeAdatper = new TypeToken>>() { + }.getType(); + + Type materialType = new TypeToken() { + }.getType(); + + this.gsonV0 = new GsonBuilder() + .setPrettyPrinting() + .disableHtmlEscaping() + .enableComplexMapKeySerialization() + .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE) + .registerTypeAdapter(materialType, new MaterialAdapter()) + .registerTypeAdapter(accessTypeAdatper, new OldPermissionsMapTypeAdapterV0()) + .registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()) + .registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()) + .registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY).create(); + } + + private void migrateV1(HoconConfigurationLoader loader) { + Path pluginFolder = this.plugin.getDataFolder().toPath(); + Path configPath = pluginFolder.resolve("config.yml"); + Path oldConfigFolder = pluginFolder.resolve("oldConfig"); + if (!configPath.toFile().exists()) { + this.plugin.getLogger().warning("Found a main.conf from before 0.5.4 but no config.yml was found! Might lose some config information!"); + return; + } + try { + OldMainConfigV1 oldConf = new OldMainConfigV1(); + Loader.load(loader, oldConf); + TransitionConfigV1 newConf = new TransitionConfigV1(); + Loader.load(loader, newConf); + newConf.update(oldConf, this.plugin.getConfig()); + Loader.loadAndSave(loader, newConf); + if (!oldConfigFolder.toFile().exists()) { + oldConfigFolder.toFile().mkdir(); + } + Files.move(configPath, oldConfigFolder.resolve("config.yml")); + } catch (Exception e) { + this.plugin.getLogger().log(Level.SEVERE, "Could not migrate configuration", e); + } + } + + private void migrateV2(CommentedConfigurationNode node) { + node.getNode("factions").getNode("enterTitles").getNode("title").setValue(""); + node.getNode("factions").getNode("enterTitles").getNode("subtitle").setValue("{faction-relation-color}{faction}"); + node.getNode("aVeryFriendlyFactionsConfig").getNode("version").setValue(3); + node.getNode("scoreboard").getNode("constant").getNode("factionlessTitle").setValue(node.getNode("scoreboard").getNode("constant").getNode("title").getString()); + + this.plugin.getLogger().info("Detected a config from before 0.5.7"); + this.plugin.getLogger().info(" Setting default enterTitles settings based on old style. Visit main.conf to edit."); + this.plugin.getLogger().info(" Setting default constant scoreboard factionlessTitle settings based on normal title. Visit main.conf to edit."); + } + + private void migrateV3(CommentedConfigurationNode node) { + node.getNode("scoreboard").getNode("constant").getNode("prefixTemplate").setValue(TL.DEFAULT_PREFIX.toString()); + node.getNode("aVeryFriendlyFactionsConfig").getNode("version").setValue(4); + + this.plugin.getLogger().info("Detected a config from before 0.5.14"); + this.plugin.getLogger().info(" 1. Setting default scoreboard prefixTemplate based on lang.yml default-prefix setting."); + this.plugin.getLogger().info(" 2. Be aware that \"warZonePreventMonsterSpawns\" has been removed entirely, and there is"); + this.plugin.getLogger().info(" now a new spawning control system added."); + this.plugin.getLogger().info(" 3. The perms gui hover text can now be customized in config, and the allow/deny/locked text"); + this.plugin.getLogger().info(" can now be customized in lang.yml under GUI->PERMS->ACTION"); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/MaterialAdapter.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/MaterialAdapter.java new file mode 100644 index 0000000..905a4fe --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/MaterialAdapter.java @@ -0,0 +1,23 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.Material; + +import java.io.IOException; + +public class MaterialAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, Material value) throws IOException { + out.value(value.name()); + } + + @Override + public Material read(JsonReader in) throws IOException { + return MaterialDb.get(in.nextString()); + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/NewMemoryFaction.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/NewMemoryFaction.java new file mode 100644 index 0000000..f1077b9 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/NewMemoryFaction.java @@ -0,0 +1,77 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.BanInfo; +import com.massivecraft.factions.util.LazyLocation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public class NewMemoryFaction { + private String id; + private boolean peacefulExplosionsEnabled; + private boolean permanent; + private String tag; + private String description; + private boolean open; + private boolean peaceful; + private Integer permanentPower; + private LazyLocation home; + private long foundedDate; + private double powerBoost; + private Map relationWish; + private Map> claimOwnership; + private Set invites; + private HashMap> announcements; + private ConcurrentHashMap warps; + private ConcurrentHashMap warpPasswords; + private long lastDeath; + private int maxVaults; + private Role defaultRole; + private Map> permissions; + private Map> permissionsOffline; + private Set bans; + + public NewMemoryFaction(OldMemoryFactionV0 old) { + this.id = old.id; + this.peacefulExplosionsEnabled = old.peacefulExplosionsEnabled; + this.permanent = old.permanent; + this.tag = old.tag; + this.description = old.description; + this.open = old.open; + this.peaceful = old.peaceful; + this.permanentPower = old.permanentPower; + this.home = old.home; + this.foundedDate = old.foundedDate; + this.powerBoost = old.powerBoost; + this.relationWish = old.relationWish; + this.claimOwnership = old.claimOwnership; + this.invites = old.invites; + this.announcements = old.announcements; + this.warps = old.warps; + this.warpPasswords = old.warpPasswords; + this.lastDeath = old.lastDeath; + this.maxVaults = old.maxVaults; + this.defaultRole = old.defaultRole; + this.permissions = new HashMap<>(); + this.permissionsOffline = new HashMap<>(); + old.permissions.forEach((permiss, map) -> { + Map newMap = new HashMap<>(); + map.forEach((permact, access) -> { + if (access == OldAccessV0.ALLOW || access == OldAccessV0.DENY) { + newMap.put(permact.getNew(), access == OldAccessV0.ALLOW); + } + }); + this.permissions.put(permiss.newPermissible(), newMap); + this.permissionsOffline.put(permiss.newPermissible(), newMap); + }); + this.bans = old.bans; + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldAccessV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldAccessV0.java new file mode 100644 index 0000000..aa8f715 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldAccessV0.java @@ -0,0 +1,46 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import org.bukkit.ChatColor; + +public enum OldAccessV0 { + ALLOW("Allow", ChatColor.GREEN), + DENY("Deny", ChatColor.DARK_RED), + UNDEFINED("Undefined", ChatColor.GRAY); + + private String name; + private ChatColor color; + + OldAccessV0(String name, ChatColor color) { + this.name = name; + this.color = color; + } + + /** + * Case insensitive check for access. + * + * @param check check + * @return access + */ + public static OldAccessV0 fromString(String check) { + for (OldAccessV0 access : values()) { + if (access.name().equalsIgnoreCase(check)) { + return access; + } + } + + return null; + } + + public String getName() { + return this.name; + } + + public ChatColor getColor() { + return color; + } + + @Override + public String toString() { + return name(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldConfV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldConfV0.java new file mode 100644 index 0000000..3bab46e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldConfV0.java @@ -0,0 +1,299 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import org.bukkit.ChatColor; +import org.bukkit.Material; + +import java.util.*; + +public class OldConfV0 { + public List baseCommandAliases = new ArrayList<>(); + + // Colors + public ChatColor colorMember = ChatColor.GREEN; + public ChatColor colorAlly = ChatColor.LIGHT_PURPLE; + public ChatColor colorTruce = ChatColor.DARK_PURPLE; + public ChatColor colorNeutral = ChatColor.WHITE; + public ChatColor colorEnemy = ChatColor.RED; + + public ChatColor colorPeaceful = ChatColor.GOLD; + public ChatColor colorWilderness = ChatColor.GRAY; + public ChatColor colorSafezone = ChatColor.GOLD; + public ChatColor colorWar = ChatColor.DARK_RED; + + // Power + public double powerPlayerMax = 10.0; + public double powerPlayerMin = -10.0; + public double powerPlayerStarting = 0.0; + public double powerPerMinute = 0.2; // Default health rate... it takes 5 min to heal one power + public double powerPerDeath = 4.0; // A death makes you lose 4 power + public boolean powerRegenOffline = false; // does player power regenerate even while they're offline? + public double powerOfflineLossPerDay = 0.0; // players will lose this much power per day offline + public double powerOfflineLossLimit = 0.0; // players will no longer lose power from being offline once their power drops to this amount or less + public double powerFactionMax = 0.0; // if greater than 0, the cap on how much power a faction can have (additional power from players beyond that will act as a "buffer" of sorts) + + public String prefixAdmin = "***"; + public String prefixColeader = "**"; + public String prefixMod = "*"; + public String prefixNormal = "+"; + public String prefixRecruit = "-"; + + public boolean allowMultipleColeaders = false; + + public int factionTagLengthMin = 3; + public int factionTagLengthMax = 10; + public boolean factionTagForceUpperCase = false; + + public boolean newFactionsDefaultOpen = false; + + // when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit + public int factionMemberLimit = 0; + + // what faction ID to start new players in when they first join the server; default is 0, "no faction" + public String newPlayerStartingFactionID = "0"; + + public boolean showMapFactionKey = true; + public boolean showNeutralFactionsOnMap = true; + public boolean showEnemyFactionsOnMap = true; + public boolean showTruceFactionsOnMap = true; + + // Disallow joining/leaving/kicking while power is negative + public boolean canLeaveWithNegativePower = true; + + // Configuration for faction-only chat + public boolean factionOnlyChat = true; + // Configuration on the Faction tag in chat messages. + public boolean chatTagEnabled = true; + public transient boolean chatTagHandledByAnotherPlugin = false; + public boolean chatTagRelationColored = true; + public String chatTagReplaceString = "[FACTION]"; + public String chatTagInsertAfterString = ""; + public String chatTagInsertBeforeString = ""; + public int chatTagInsertIndex = 0; + public boolean chatTagPadBefore = false; + public boolean chatTagPadAfter = true; + public String chatTagFormat = "%s" + ChatColor.WHITE; + public boolean alwaysShowChatTag = true; + public String factionChatFormat = "%s:" + ChatColor.WHITE + " %s"; + public String allianceChatFormat = ChatColor.LIGHT_PURPLE + "%s:" + ChatColor.WHITE + " %s"; + public String truceChatFormat = ChatColor.DARK_PURPLE + "%s:" + ChatColor.WHITE + " %s"; + public String modChatFormat = ChatColor.RED + "%s:" + ChatColor.WHITE + " %s"; + + public boolean broadcastDescriptionChanges = false; + public boolean broadcastTagChanges = false; + + public double saveToFileEveryXMinutes = 30.0; + + public double autoLeaveAfterDaysOfInactivity = 10.0; + public double autoLeaveRoutineRunsEveryXMinutes = 5.0; + public int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick + public boolean removePlayerDataWhenBanned = true; + public boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. + + public boolean worldGuardChecking = false; + public boolean worldGuardBuildPriority = false; + + // server logging options + public boolean logFactionCreate = true; + public boolean logFactionDisband = true; + public boolean logFactionJoin = true; + public boolean logFactionKick = true; + public boolean logFactionLeave = true; + public boolean logLandClaims = true; + public boolean logLandUnclaims = true; + public boolean logMoneyTransactions = true; + public boolean logPlayerCommands = true; + + // prevent some potential exploits + public boolean handleExploitObsidianGenerators = true; + public boolean handleExploitEnderPearlClipping = true; + public boolean handleExploitInteractionSpam = true; + public boolean handleExploitTNTWaterlog = false; + public boolean handleExploitLiquidFlow = false; + + public boolean homesEnabled = true; + public boolean homesMustBeInClaimedTerritory = true; + public boolean homesTeleportToOnDeath = true; + public boolean homesRespawnFromNoPowerLossWorlds = true; + public boolean homesTeleportCommandEnabled = true; + public boolean homesTeleportCommandEssentialsIntegration = true; + public boolean homesTeleportCommandSmokeEffectEnabled = true; + public float homesTeleportCommandSmokeEffectThickness = 3f; + public boolean homesTeleportAllowedFromEnemyTerritory = true; + public boolean homesTeleportAllowedFromDifferentWorld = true; + public double homesTeleportAllowedEnemyDistance = 32.0; + public boolean homesTeleportIgnoreEnemiesIfInOwnTerritory = true; + + public boolean disablePVPBetweenNeutralFactions = false; + public boolean disablePVPForFactionlessPlayers = false; + public boolean enablePVPAgainstFactionlessInAttackersLand = false; + + public int noPVPDamageToOthersForXSecondsAfterLogin = 3; + + public boolean peacefulTerritoryDisablePVP = true; + public boolean peacefulTerritoryDisableMonsters = false; + public boolean peacefulTerritoryDisableBoom = false; + public boolean peacefulMembersDisablePowerLoss = true; + + public boolean permanentFactionsDisableLeaderPromotion = false; + + public boolean claimsMustBeConnected = false; + public boolean claimsCanBeUnconnectedIfOwnedByOtherFaction = true; + public int claimsRequireMinFactionMembers = 1; + public int claimedLandsMax = 0; + public int lineClaimLimit = 5; + + // if someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit + public int radiusClaimFailureLimit = 9; + + public double considerFactionsReallyOfflineAfterXMinutes = 0.0; + + public int actionDeniedPainAmount = 1; + + // commands which will be prevented if the player is a member of a permanent faction + public Set permanentFactionMemberDenyCommands = new LinkedHashSet<>(); + + // commands which will be prevented when in claimed territory of another faction + public Set territoryNeutralDenyCommands = new LinkedHashSet<>(); + public Set territoryEnemyDenyCommands = new LinkedHashSet<>(); + public Set territoryAllyDenyCommands = new LinkedHashSet<>(); + public Set warzoneDenyCommands = new LinkedHashSet<>(); + public Set wildernessDenyCommands = new LinkedHashSet<>(); + + // IGNORED STARTS HERE LOL + public boolean defaultFlyPermEnemy = false; + public boolean defaultFlyPermNeutral = false; + public boolean defaultFlyPermTruce = false; + public boolean defaultFlyPermAlly = true; + public boolean defaultFlyPermMember = true; + + public boolean territoryDenyBuild = true; + public boolean territoryDenyBuildWhenOffline = true; + public boolean territoryPainBuild = false; + public boolean territoryPainBuildWhenOffline = false; + public boolean territoryDenyUseage = true; + public boolean territoryEnemyDenyBuild = true; + public boolean territoryEnemyDenyBuildWhenOffline = true; + public boolean territoryEnemyPainBuild = false; + public boolean territoryEnemyPainBuildWhenOffline = false; + public boolean territoryEnemyDenyUseage = true; + public boolean territoryEnemyProtectMaterials = true; + public boolean territoryAllyDenyBuild = true; + public boolean territoryAllyDenyBuildWhenOffline = true; + public boolean territoryAllyPainBuild = false; + public boolean territoryAllyPainBuildWhenOffline = false; + public boolean territoryAllyDenyUseage = true; + public boolean territoryAllyProtectMaterials = true; + public boolean territoryTruceDenyBuild = true; + public boolean territoryTruceDenyBuildWhenOffline = true; + public boolean territoryTrucePainBuild = false; + public boolean territoryTrucePainBuildWhenOffline = false; + public boolean territoryTruceDenyUseage = true; + public boolean territoryTruceProtectMaterials = true; + // IGNORED ENDS HERE LOL + public boolean territoryBlockCreepers = false; + public boolean territoryBlockCreepersWhenOffline = false; + public boolean territoryBlockFireballs = false; + public boolean territoryBlockFireballsWhenOffline = false; + public boolean territoryBlockTNT = false; + public boolean territoryBlockTNTWhenOffline = false; + public boolean territoryDenyEndermanBlocks = true; + public boolean territoryDenyEndermanBlocksWhenOffline = true; + + public boolean safeZoneDenyBuild = true; + public boolean safeZoneDenyUseage = true; + public boolean safeZoneBlockTNT = true; + public boolean safeZonePreventAllDamageToPlayers = false; + public boolean safeZoneDenyEndermanBlocks = true; + + public boolean warZoneDenyBuild = true; + public boolean warZoneDenyUseage = true; + public boolean warZoneBlockCreepers = false; + public boolean warZoneBlockFireballs = false; + public boolean warZoneBlockTNT = true; + public boolean warZonePowerLoss = true; + public boolean warZoneFriendlyFire = false; + public boolean warZoneDenyEndermanBlocks = true; + + public boolean wildernessDenyBuild = false; + public boolean wildernessDenyUseage = false; + public boolean wildernessBlockCreepers = false; + public boolean wildernessBlockFireballs = false; + public boolean wildernessBlockTNT = false; + public boolean wildernessPowerLoss = true; + public boolean wildernessDenyEndermanBlocks = false; + + // for claimed areas where further faction-member ownership can be defined + public boolean ownedAreasEnabled = true; + public int ownedAreasLimitPerFaction = 0; + public boolean ownedAreasModeratorsCanSet = false; + public boolean ownedAreaModeratorsBypass = true; + public boolean ownedAreaDenyBuild = true; + public boolean ownedAreaPainBuild = false; + public boolean ownedAreaProtectMaterials = true; + public boolean ownedAreaDenyUseage = true; + + public boolean ownedMessageOnBorder = true; + public boolean ownedMessageInsideTerritory = true; + public boolean ownedMessageByChunk = false; + + public boolean pistonProtectionThroughDenyBuild = true; + + public Set territoryProtectedMaterials = Collections.emptySet(); + public Set territoryDenyUseageMaterials = EnumSet.noneOf(Material.class); + public Set territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class); + public Set territoryDenyUseageMaterialsWhenOffline = EnumSet.noneOf(Material.class); + + // Economy settings + public boolean econEnabled = false; + public String econUniverseAccount = ""; + public double econCostClaimWilderness = 30.0; + public double econCostClaimFromFactionBonus = 30.0; + public double econOverclaimRewardMultiplier = 0.0; + public double econClaimAdditionalMultiplier = 0.5; + public double econClaimRefundMultiplier = 0.7; + public double econClaimUnconnectedFee = 0.0; + public double econCostCreate = 100.0; + public double econCostOwner = 15.0; + public double econCostSethome = 30.0; + public double econCostJoin = 0.0; + public double econCostLeave = 0.0; + public double econCostKick = 0.0; + public double econCostInvite = 0.0; + public double econCostHome = 0.0; + public double econCostTag = 0.0; + public double econCostDesc = 0.0; + public double econCostTitle = 0.0; + public double econCostList = 0.0; + public double econCostMap = 0.0; + public double econCostPower = 0.0; + public double econCostShow = 0.0; + public double econCostStuck = 0.0; + public double econCostOpen = 0.0; + public double econCostAlly = 0.0; + public double econCostTruce = 0.0; + public double econCostEnemy = 0.0; + public double econCostNeutral = 0.0; + public double econCostNoBoom = 0.0; + + //Faction banks, to pay for land claiming and other costs instead of individuals paying for them + public boolean bankEnabled = true; + public boolean bankMembersCanWithdraw = false; //Have to be at least moderator to withdraw or pay money to another faction + public boolean bankFactionPaysCosts = true; //The faction pays for faction command costs, such as sethome + public boolean bankFactionPaysLandCosts = true; //The faction pays for land claiming costs. + + // mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections + public Set playersWhoBypassAllProtection = new LinkedHashSet<>(); + + public Set worldsNoClaiming = new LinkedHashSet<>(); + public Set worldsNoPowerLoss = new LinkedHashSet<>(); + public Set worldsIgnorePvP = new LinkedHashSet<>(); + public Set worldsNoWildernessProtection = new LinkedHashSet<>(); + + // faction- + public String vaultPrefix = "faction-%s"; + public int defaultMaxVaults = 0; + + // Taller and wider for "bigger f map" + public int mapHeight = 17; + public int mapWidth = 49; +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldMemoryFactionV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldMemoryFactionV0.java new file mode 100644 index 0000000..f58ab7c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldMemoryFactionV0.java @@ -0,0 +1,43 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.BanInfo; +import com.massivecraft.factions.util.LazyLocation; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public class OldMemoryFactionV0 { + protected String id = null; + protected boolean peacefulExplosionsEnabled; + protected boolean permanent; + protected String tag; + protected String description; + protected boolean open; + protected boolean peaceful; + protected Integer permanentPower; + protected LazyLocation home; + protected long foundedDate; + protected double money; + protected double powerBoost; + protected Map relationWish = new HashMap<>(); + protected Map> claimOwnership = new ConcurrentHashMap<>(); + protected Set invites = new HashSet<>(); + protected HashMap> announcements = new HashMap<>(); + protected ConcurrentHashMap warps = new ConcurrentHashMap<>(); + protected ConcurrentHashMap warpPasswords = new ConcurrentHashMap<>(); + protected long lastDeath; + protected int maxVaults; + protected Role defaultRole; + protected Map> permissions = new HashMap<>(); + protected Set bans = new HashSet<>(); + + private OldMemoryFactionV0() { + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissableActionV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissableActionV0.java new file mode 100644 index 0000000..c68c84c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissableActionV0.java @@ -0,0 +1,71 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.massivecraft.factions.perms.PermissibleAction; + +public enum OldPermissableActionV0 { + BAN("ban", PermissibleAction.BAN), + BUILD("build", PermissibleAction.BUILD), + DESTROY("destroy", PermissibleAction.DESTROY), + FROST_WALK("frostwalk", PermissibleAction.FROSTWALK), + PAIN_BUILD("painbuild", PermissibleAction.PAINBUILD), + DOOR("door", PermissibleAction.DOOR), + BUTTON("button", PermissibleAction.BUTTON), + LEVER("lever", PermissibleAction.LEVER), + CONTAINER("container", PermissibleAction.CONTAINER), + INVITE("invite", PermissibleAction.INVITE), + KICK("kick", PermissibleAction.KICK), + ITEM("items", PermissibleAction.ITEM), // generic for most items + SETHOME("sethome", PermissibleAction.SETHOME), + WITHDRAW("withdraw", PermissibleAction.ECONOMY), + TERRITORY("territory", PermissibleAction.TERRITORY), + ACCESS("access", PermissibleAction.PLATE), + DISBAND("disband", PermissibleAction.DISBAND), + PROMOTE("promote", PermissibleAction.PROMOTE), + SETWARP("setwarp", PermissibleAction.SETWARP), + WARP("warp", PermissibleAction.WARP), + FLY("fly", PermissibleAction.FLY), + ; + + private String name; + + private PermissibleAction action; + + OldPermissableActionV0(String name, PermissibleAction newPermissibleAction) { + this.name = name; + this.action = newPermissibleAction; + } + + public PermissibleAction getNew() { + return this.action; + } + + /** + * Get the friendly name of this action. Used for editing in commands. + * + * @return friendly name of the action as a String. + */ + public String getName() { + return this.name; + } + + /** + * Case insensitive check for action. + * + * @param check check + * @return permissible + */ + public static OldPermissableActionV0 fromString(String check) { + for (OldPermissableActionV0 permissableAction : values()) { + if (permissableAction.name().equalsIgnoreCase(check)) { + return permissableAction; + } + } + + return null; + } + + @Override + public String toString() { + return name; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissableV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissableV0.java new file mode 100644 index 0000000..c0d3cd3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissableV0.java @@ -0,0 +1,9 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.massivecraft.factions.perms.Permissible; + +public interface OldPermissableV0 { + String name(); + + Permissible newPermissible(); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissionsMapTypeAdapterV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissionsMapTypeAdapterV0.java new file mode 100644 index 0000000..06cc8dc --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldPermissionsMapTypeAdapterV0.java @@ -0,0 +1,96 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.util.TL; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + +public class OldPermissionsMapTypeAdapterV0 implements JsonDeserializer>> { + + @Override + public Map> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { + + try { + JsonObject obj = json.getAsJsonObject(); + if (obj == null) { + return null; + } + + Map> permissionsMap = new ConcurrentHashMap<>(); + + // Top level is Relation + for (Map.Entry entry : obj.entrySet()) { + OldPermissableV0 permissable = getPermissable(entry.getKey()); + + if (permissable == null) { + continue; + } + + // Second level is the map between action -> access + Map accessMap = new HashMap<>(); + for (Map.Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) { + OldPermissableActionV0 permissableAction = OldPermissableActionV0.fromString(entry2.getKey()); + if (permissableAction == null) { + switch (entry2.getKey()) { + case "frostwalk": + permissableAction = OldPermissableActionV0.FROST_WALK; + break; + case "painbuild": + permissableAction = OldPermissableActionV0.PAIN_BUILD; + break; + case "items": + permissableAction = OldPermissableActionV0.ITEM; + break; + } + } + OldAccessV0 access = OldAccessV0.fromString(entry2.getValue().getAsString()); + accessMap.put(permissableAction, access); + } + permissionsMap.put(permissable, accessMap); + } + + return permissionsMap; + + } catch (Exception ex) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Error encountered while deserializing a PermissionsMap.", ex); + return null; + } + } + + private OldPermissableV0 getPermissable(String name) { + // If name is uppercase then it is (probably, no way to completely know) valid if not begin conversion + if (name.equals(name.toUpperCase())) { + if (OldRoleV0.fromString(name.toUpperCase()) != null) { + return OldRoleV0.fromString(name.toUpperCase()); + } else if (OldRelationV0.fromString(name.toUpperCase()) != null) { + return OldRelationV0.fromString(name.toUpperCase()); + } else { + return null; + } + } else { + if (name.equals(TL.ROLE_RECRUIT.toString())) { + return OldRoleV0.RECRUIT; + } else if (name.equals(TL.ROLE_NORMAL.toString())) { + return OldRoleV0.NORMAL; + } else if (name.equals(TL.ROLE_MODERATOR.toString())) { + return OldRoleV0.MODERATOR; + } else { + // If it is explicitly member and its old data then it refers to relation member not role, skip it + if (name.equals("member")) { + return null; + } + return OldRelationV0.fromString(name); + } + } + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldRelationV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldRelationV0.java new file mode 100644 index 0000000..744ca0b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldRelationV0.java @@ -0,0 +1,48 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.util.TL; + + +public enum OldRelationV0 implements OldPermissableV0 { + MEMBER(4, TL.RELATION_MEMBER_SINGULAR.toString(), Relation.MEMBER), + ALLY(3, TL.RELATION_ALLY_SINGULAR.toString(), Relation.ALLY), + TRUCE(2, TL.RELATION_TRUCE_SINGULAR.toString(), Relation.TRUCE), + NEUTRAL(1, TL.RELATION_NEUTRAL_SINGULAR.toString(), Relation.NEUTRAL), + ENEMY(0, TL.RELATION_ENEMY_SINGULAR.toString(), Relation.ENEMY); + + public final int value; + public final String nicename; + public final Relation replacement; + + OldRelationV0(final int value, final String nicename, final Relation replacement) { + this.value = value; + this.nicename = nicename; + this.replacement = replacement; + } + + public Permissible newPermissible() { + return this.replacement; + } + + public static OldRelationV0 fromString(String s) { + // Because Java 6 doesn't allow String switches :( + if (s.equalsIgnoreCase(MEMBER.nicename)) { + return MEMBER; + } else if (s.equalsIgnoreCase(ALLY.nicename)) { + return ALLY; + } else if (s.equalsIgnoreCase(TRUCE.nicename)) { + return TRUCE; + } else if (s.equalsIgnoreCase(ENEMY.nicename)) { + return ENEMY; + } else { + return NEUTRAL; // If they somehow mess things up, go back to default behavior. + } + } + + @Override + public String toString() { + return this.nicename; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldRoleV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldRoleV0.java new file mode 100644 index 0000000..db25425 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/OldRoleV0.java @@ -0,0 +1,50 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.util.TL; + +public enum OldRoleV0 implements OldPermissableV0 { + ADMIN(4, TL.ROLE_ADMIN, Role.ADMIN), + COLEADER(3, TL.ROLE_COLEADER, Role.COLEADER), + MODERATOR(2, TL.ROLE_MODERATOR, Role.MODERATOR), + NORMAL(1, TL.ROLE_NORMAL, Role.NORMAL), + RECRUIT(0, TL.ROLE_RECRUIT, Role.RECRUIT); + + public final int value; + public final String nicename; + public final TL translation; + public final Role replacement; + + OldRoleV0(final int value, final TL translation, final Role replacement) { + this.value = value; + this.nicename = translation.toString(); + this.translation = translation; + this.replacement = replacement; + } + + public Permissible newPermissible() { + return this.replacement; + } + + public static OldRoleV0 fromString(String check) { + switch (check.toLowerCase()) { + case "admin": + return ADMIN; + case "coleader": + case "coowner": + return COLEADER; + case "mod": + case "moderator": + return MODERATOR; + case "normal": + case "member": + return NORMAL; + case "recruit": + case "rec": + return RECRUIT; + } + + return null; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/TransitionConfigV0.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/TransitionConfigV0.java new file mode 100644 index 0000000..32e7b24 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v0/TransitionConfigV0.java @@ -0,0 +1,653 @@ +package com.massivecraft.factions.config.transition.oldclass.v0; + +import com.massivecraft.factions.config.annotation.Comment; +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +public class TransitionConfigV0 { + public class Colors { + public class Relations { + private String member = "GREEN"; + private String ally = "LIGHT_PURPLE"; + private String truce = "DARK_PURPLE"; + private String neutral = "WHITE"; + private String enemy = "RED"; + private String peaceful = "GOLD"; + } + + public class Factions { + private String wilderness = "GRAY"; + private String safezone = "GOLD"; + private String warzone = "DARK_RED"; + } + + private Factions factions = new Factions(); + private Relations relations = new Relations(); + } + + public class Factions { + public class LandRaidControl { + public class Power { + private double playerMin = -10.0D; + private double playerMax = 10.0D; + private double playerStarting = 0.0D; + @Comment("Default health rate of 0.2 takes 5 minutes to recover one power") + private double powerPerMinute = 0.2; + @Comment("How much is lost on death") + private double lossPerDeath = 4.0; + @Comment("Does a player regenerate power while offline?") + private boolean regenOffline = false; + @Comment("A player loses this much per day offline") + private double offlineLossPerDay = 0.0; + @Comment("A player stops losing power from being offline once they reach this amount") + private double offlineLossLimit = 0.0; + @Comment("If greater than 0, used as a cap for how much power a faction can have\nAdditional power from players beyond this acts as a \"buffer\" of sorts") + private double factionMax = 0.0; + private boolean respawnHomeFromNoPowerLossWorlds = true; + private Set worldsNoPowerLoss = new HashSet<>(); + private boolean peacefulMembersDisablePowerLoss = true; + private boolean warZonePowerLoss = true; + private boolean wildernessPowerLoss = true; + @Comment("Disallow joining/leaving/kicking while power is negative") + private boolean canLeaveWithNegativePower = true; + } + + @Comment("Sets the mode of land/raid control") + private String system = "power"; + @Comment("Controls the power system of land/raid control\nSet the 'system' value to 'power' to use this system") + private Power power = new Power(); + } + + public class Prefix { + private String admin = "***"; + private String coleader = "**"; + private String mod = "*"; + private String normal = "+"; + private String recruit = "-"; + } + + public class Chat { + @Comment("Allow for players to chat only within their faction, with allies, etc.\n" + + "Set to false to only allow public chats through this plugin.") + private boolean factionOnlyChat = true; + // Configuration on the Faction tag in chat messages. + @Comment("If true, disables adding of faction tag so another plugin can manage this") + private transient boolean tagHandledByAnotherPlugin = false; + private boolean tagRelationColored = true; + private String tagReplaceString = "[FACTION]"; + private String tagInsertAfterString = ""; + private String tagInsertBeforeString = ""; + private int tagInsertIndex = 0; + private boolean tagPadBefore = false; + private boolean tagPadAfter = true; + private String tagFormat = "%s\u00A7f"; + private boolean alwaysShowChatTag = true; + private String factionChatFormat = "%s:\u00A7f %s"; + private String allianceChatFormat = "\u00A7d%s:\u00A7f %s"; + private String truceChatFormat = "\u00A75%s:\u00A7f %s"; + private String modChatFormat = "\u00A7c%s:\u00A7f %s"; + private boolean broadcastDescriptionChanges = false; + private boolean broadcastTagChanges = false; + } + + public class Homes { + private boolean enabled = true; + private boolean mustBeInClaimedTerritory = true; + private boolean teleportToOnDeath = true; + private boolean teleportCommandEnabled = true; + private boolean teleportCommandEssentialsIntegration = true; + private boolean teleportCommandSmokeEffectEnabled = true; + private float teleportCommandSmokeEffectThickness = 3f; + private boolean teleportAllowedFromEnemyTerritory = true; + private boolean teleportAllowedFromDifferentWorld = true; + private double teleportAllowedEnemyDistance = 32.0; + private boolean teleportIgnoreEnemiesIfInOwnTerritory = true; + } + + public class PVP { + private boolean disablePVPBetweenNeutralFactions = false; + private boolean disablePVPForFactionlessPlayers = false; + private boolean enablePVPAgainstFactionlessInAttackersLand = false; + private int noPVPDamageToOthersForXSecondsAfterLogin = 3; + private Set worldsIgnorePvP = new HashSet<>(); + } + + public class SpecialCase { + private boolean peacefulTerritoryDisablePVP = true; + private boolean peacefulTerritoryDisableMonsters = false; + private boolean peacefulTerritoryDisableBoom = false; + private boolean permanentFactionsDisableLeaderPromotion = false; + } + + public class Claims { + private boolean mustBeConnected = false; + private boolean canBeUnconnectedIfOwnedByOtherFaction = true; + private int requireMinFactionMembers = 1; + private int landsMax = 0; + private int lineClaimLimit = 5; + @Comment("If someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit") + private int radiusClaimFailureLimit = 9; + private Set worldsNoClaiming = new HashSet<>(); + } + + public class Protection { + @Comment("Commands which will be prevented if the player is a member of a permanent faction") + private Set permanentFactionMemberDenyCommands = new HashSet<>(); + + @Comment("Commands which will be prevented when in claimed territory of a neutral faction") + private Set territoryNeutralDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in claimed territory of an enemy faction") + private Set territoryEnemyDenyCommands = new HashSet() { + { + this.add("home"); + this.add("sethome"); + this.add("spawn"); + this.add("tpahere"); + this.add("tpaccept"); + this.add("tpa"); + } + }; + @Comment("Commands which will be prevented when in claimed territory of an ally faction") + private Set territoryAllyDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in warzone") + private Set warzoneDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in wilderness") + private Set wildernessDenyCommands = new HashSet<>(); + + private boolean territoryBlockCreepers = false; + private boolean territoryBlockCreepersWhenOffline = false; + private boolean territoryBlockFireballs = false; + private boolean territoryBlockFireballsWhenOffline = false; + private boolean territoryBlockTNT = false; + private boolean territoryBlockTNTWhenOffline = false; + private boolean territoryDenyEndermanBlocks = true; + private boolean territoryDenyEndermanBlocksWhenOffline = true; + + private boolean safeZoneDenyBuild = true; + private boolean safeZoneDenyUsage = true; + private boolean safeZoneBlockTNT = true; + private boolean safeZonePreventAllDamageToPlayers = false; + private boolean safeZoneDenyEndermanBlocks = true; + + private boolean warZoneDenyBuild = true; + private boolean warZoneDenyUsage = true; + private boolean warZoneBlockCreepers = false; + private boolean warZoneBlockFireballs = false; + private boolean warZoneBlockTNT = true; + private boolean warZoneFriendlyFire = false; + private boolean warZoneDenyEndermanBlocks = true; + + private boolean wildernessDenyBuild = false; + private boolean wildernessDenyUsage = false; + private boolean wildernessBlockCreepers = false; + private boolean wildernessBlockFireballs = false; + private boolean wildernessBlockTNT = false; + private boolean wildernessDenyEndermanBlocks = false; + + private boolean pistonProtectionThroughDenyBuild = true; + + private Set territoryProtectedMaterials = new HashSet<>(); + private Set territoryDenyUsageMaterials = new HashSet<>(); + private Set territoryProtectedMaterialsWhenOffline = new HashSet<>(); + private Set territoryDenyUsageMaterialsWhenOffline = new HashSet<>(); + + @Comment("Mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections") + private Set playersWhoBypassAllProtection = new HashSet<>(); + private Set worldsNoWildernessProtection = new HashSet<>(); + + private Protection() { + protectMaterial("DARK_OAK_DOOR"); + protectMaterial("BIRCH_DOOR"); + protectMaterial("ACACIA_DOOR"); + protectMaterial("IRON_DOOR"); + protectMaterial("JUNGLE_DOOR"); + protectMaterial("OAK_DOOR"); + protectMaterial("SPRUCE_DOOR"); + + protectMaterial("ACACIA_TRAPDOOR"); + protectMaterial("BIRCH_TRAPDOOR"); + protectMaterial("DARK_OAK_TRAPDOOR"); + protectMaterial("IRON_TRAPDOOR"); + protectMaterial("JUNGLE_TRAPDOOR"); + protectMaterial("OAK_TRAPDOOR"); + protectMaterial("SPRUCE_TRAPDOOR"); + + protectMaterial("ACACIA_FENCE"); + protectMaterial("BIRCH_FENCE"); + protectMaterial("DARK_OAK_FENCE"); + protectMaterial("OAK_FENCE"); + protectMaterial("NETHER_BRICK_FENCE"); + protectMaterial("SPRUCE_FENCE"); + + protectMaterial("OAK_FENCE_GATE"); + protectMaterial("SPRUCE_FENCE_GATE"); + protectMaterial("BIRCH_FENCE_GATE"); + protectMaterial("JUNGLE_FENCE_GATE"); + protectMaterial("ACACIA_FENCE_GATE"); + protectMaterial("DARK_OAK_FENCE_GATE"); + + protectMaterial("DISPENSER"); + protectMaterial("CHEST"); + protectMaterial("FURNACE"); + protectMaterial("REPEATER"); + protectMaterial("JUKEBOX"); + protectMaterial("BREWING_STAND"); + protectMaterial("ENCHANTING_TABLE"); + protectMaterial("CAULDRON"); + protectMaterial("FARMLAND"); + protectMaterial("BEACON"); + protectMaterial("ANVIL"); + protectMaterial("TRAPPED_CHEST"); + protectMaterial("DROPPER"); + protectMaterial("HOPPER"); + + protectUsage("FIRE_CHARGE"); + protectUsage("FLINT_AND_STEEL"); + protectUsage("BUCKET"); + protectUsage("WATER_BUCKET"); + protectUsage("LAVA_BUCKET"); + } + + private void protectMaterial(String material) { + this.territoryProtectedMaterials.add(material); + territoryProtectedMaterialsWhenOffline.add(material); + } + + private void protectUsage(String material) { + territoryDenyUsageMaterials.add(material); + territoryDenyUsageMaterialsWhenOffline.add(material); + } + } + + public class OwnedArea { + private boolean enabled = true; + private int limitPerFaction = 0; + private boolean moderatorsCanSet = false; + private boolean moderatorsBypass = true; + private boolean denyBuild = true; + private boolean painBuild = false; + private boolean protectMaterials = true; + private boolean denyUsage = true; + + private boolean messageOnBorder = true; + private boolean messageInsideTerritory = true; + private boolean messageByChunk = false; + } + + private Chat chat = new Chat(); + private Homes homes = new Homes(); + private PVP pvp = new PVP(); + private SpecialCase specialCase = new SpecialCase(); + private Claims claims = new Claims(); + private Protection protection = new Protection(); + @Comment("For claimed areas where further faction-member ownership can be defined") + private OwnedArea ownedArea = new OwnedArea(); + @Comment("Displayed prefixes for different roles within a faction") + private Prefix prefixes = new Prefix(); + private LandRaidControl landRaidControl = new LandRaidControl(); + + private boolean allowMultipleColeaders = false; + + @Comment("Minimum faction tag length") + private int tagLengthMin = 3; + @Comment("Maximum faction tag length") + private int tagLengthMax = 10; + private boolean tagForceUpperCase = false; + + private boolean newFactionsDefaultOpen = false; + + @Comment("When faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit") + private int factionMemberLimit = 0; + + @Comment("What faction ID to start new players in when they first join the server; default is 0, \"no faction\"") + private String newPlayerStartingFactionID = "0"; + + private double saveToFileEveryXMinutes = 30.0; + + private double autoLeaveAfterDaysOfInactivity = 10.0; + private double autoLeaveRoutineRunsEveryXMinutes = 5.0; + private int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick + private boolean removePlayerDataWhenBanned = true; + private boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. + private double considerFactionsReallyOfflineAfterXMinutes = 0.0; + private int actionDeniedPainAmount = 1; + + @Comment("If enabled, perms can be managed separately for when the faction is offline") + private boolean separateOfflinePerms = false; + } + + public class Logging { + private boolean factionCreate = true; + private boolean factionDisband = true; + private boolean factionJoin = true; + private boolean factionKick = true; + private boolean factionLeave = true; + private boolean landClaims = true; + private boolean landUnclaims = true; + private boolean moneyTransactions = true; + private boolean playerCommands = true; + } + + public class Exploits { + private boolean obsidianGenerators = true; + private boolean enderPearlClipping = true; + private boolean interactionSpam = true; + private boolean tntWaterlog = false; + private boolean liquidFlow = false; + } + + public class Economy { + private boolean enabled = false; + private String universeAccount = ""; + private double costClaimWilderness = 30.0; + private double costClaimFromFactionBonus = 30.0; + private double overclaimRewardMultiplier = 0.0; + private double claimAdditionalMultiplier = 0.5; + private double claimRefundMultiplier = 0.7; + private double claimUnconnectedFee = 0.0; + private double costCreate = 100.0; + private double costOwner = 15.0; + private double costSethome = 30.0; + private double costJoin = 0.0; + private double costLeave = 0.0; + private double costKick = 0.0; + private double costInvite = 0.0; + private double costHome = 0.0; + private double costTag = 0.0; + private double costDesc = 0.0; + private double costTitle = 0.0; + private double costList = 0.0; + private double costMap = 0.0; + private double costPower = 0.0; + private double costShow = 0.0; + private double costStuck = 0.0; + private double costOpen = 0.0; + private double costAlly = 0.0; + private double costTruce = 0.0; + private double costEnemy = 0.0; + private double costNeutral = 0.0; + private double costNoBoom = 0.0; + + @Comment("Faction banks, to pay for land claiming and other costs instead of individuals paying for them") + private boolean bankEnabled = true; + @Comment("Have to be at least moderator to withdraw or pay money to another faction") + private boolean bankMembersCanWithdraw = false; + @Comment("The faction pays for faction command costs, such as sethome") + private boolean bankFactionPaysCosts = true; + @Comment("The faction pays for land claiming costs.") + private boolean bankFactionPaysLandCosts = true; + } + + public class Map { + private int height = 17; + private int width = 49; + private boolean showFactionKey = true; + private boolean showNeutralFactionsOnMap = true; + private boolean showEnemyFactions = true; + private boolean showTruceFactions = true; + } + + public class PlayerVaults { + @Comment("The %s is for the faction id") + private String vaultPrefix = "faction-%s"; + private int defaultMaxVaults = 0; + } + + public class WorldGuard { + private boolean checking; + private boolean buildPriority; + } + + @Comment("The command base (by default f, making the command /f)") + private List commandBase; + + @Comment("Colors for relationships and default factions") + private Colors colors = new Colors(); + + private Factions factions = new Factions(); + @Comment("What should be logged?") + private Logging logging = new Logging(); + @Comment("Controls certain exploit preventions") + private Exploits exploits = new Exploits(); + @Comment("Economy support requires Vault and a compatible economy plugin") + private Economy economy = new Economy(); + @Comment("Control for the default settings of /f map") + private Map map = new Map(); + @Comment("PlayerVaults faction vault settings") + private PlayerVaults playerVaults = new PlayerVaults(); + @Comment("WorldGuard settings") + private WorldGuard worldGuard = new WorldGuard(); + + public TransitionConfigV0(OldConfV0 c) { + this.commandBase = new ArrayList<>(c.baseCommandAliases); + + this.worldGuard.buildPriority = c.worldGuardBuildPriority; + this.worldGuard.checking = c.worldGuardChecking; + + this.playerVaults.defaultMaxVaults = c.defaultMaxVaults; + this.playerVaults.vaultPrefix = c.vaultPrefix; + + this.colors.relations.member = c.colorMember.name(); + this.colors.relations.ally = c.colorAlly.name(); + this.colors.relations.truce = c.colorTruce.name(); + this.colors.relations.neutral = c.colorNeutral.name(); + this.colors.relations.enemy = c.colorEnemy.name(); + this.colors.relations.peaceful = c.colorPeaceful.name(); + this.colors.factions.wilderness = c.colorWilderness.name(); + this.colors.factions.safezone = c.colorSafezone.name(); + this.colors.factions.warzone = c.colorWar.name(); + + this.factions.landRaidControl.power.playerMin = c.powerPlayerMin; + this.factions.landRaidControl.power.playerMax = c.powerPlayerMax; + this.factions.landRaidControl.power.playerStarting = c.powerPlayerStarting; + this.factions.landRaidControl.power.powerPerMinute = c.powerPerMinute; + this.factions.landRaidControl.power.lossPerDeath = c.powerPerDeath; + this.factions.landRaidControl.power.regenOffline = c.powerRegenOffline; + this.factions.landRaidControl.power.offlineLossPerDay = c.powerOfflineLossPerDay; + this.factions.landRaidControl.power.offlineLossLimit = c.powerOfflineLossLimit; + this.factions.landRaidControl.power.factionMax = c.powerFactionMax; + this.factions.landRaidControl.power.respawnHomeFromNoPowerLossWorlds = c.homesRespawnFromNoPowerLossWorlds; + this.factions.landRaidControl.power.worldsNoPowerLoss = c.worldsNoPowerLoss; + this.factions.landRaidControl.power.peacefulMembersDisablePowerLoss = c.peacefulMembersDisablePowerLoss; + this.factions.landRaidControl.power.warZonePowerLoss = c.warZonePowerLoss; + this.factions.landRaidControl.power.wildernessPowerLoss = c.wildernessPowerLoss; + this.factions.landRaidControl.power.canLeaveWithNegativePower = c.canLeaveWithNegativePower; + + this.factions.prefixes.admin = c.prefixAdmin; + this.factions.prefixes.coleader = c.prefixColeader; + this.factions.prefixes.mod = c.prefixMod; + this.factions.prefixes.normal = c.prefixNormal; + this.factions.prefixes.recruit = c.prefixRecruit; + + this.factions.chat.factionOnlyChat = c.factionOnlyChat; + this.factions.chat.tagHandledByAnotherPlugin = c.chatTagHandledByAnotherPlugin || c.chatTagEnabled; + this.factions.chat.tagRelationColored = c.chatTagRelationColored; + this.factions.chat.tagReplaceString = c.chatTagReplaceString; + this.factions.chat.tagInsertAfterString = c.chatTagInsertAfterString; + this.factions.chat.tagInsertBeforeString = c.chatTagInsertBeforeString; + this.factions.chat.tagInsertIndex = c.chatTagInsertIndex; + this.factions.chat.tagPadBefore = c.chatTagPadBefore; + this.factions.chat.tagPadAfter = c.chatTagPadAfter; + this.factions.chat.tagFormat = c.chatTagFormat; + this.factions.chat.alwaysShowChatTag = c.alwaysShowChatTag; + this.factions.chat.factionChatFormat = c.factionChatFormat; + this.factions.chat.allianceChatFormat = c.allianceChatFormat; + this.factions.chat.truceChatFormat = c.truceChatFormat; + this.factions.chat.modChatFormat = c.modChatFormat; + this.factions.chat.broadcastDescriptionChanges = c.broadcastDescriptionChanges; + this.factions.chat.broadcastTagChanges = c.broadcastTagChanges; + + this.factions.homes.enabled = c.homesEnabled; + this.factions.homes.mustBeInClaimedTerritory = c.homesMustBeInClaimedTerritory; + this.factions.homes.teleportToOnDeath = c.homesTeleportToOnDeath; + this.factions.homes.teleportCommandEnabled = c.homesTeleportCommandEnabled; + this.factions.homes.teleportCommandEssentialsIntegration = c.homesTeleportCommandEssentialsIntegration; + this.factions.homes.teleportCommandSmokeEffectEnabled = c.homesTeleportCommandSmokeEffectEnabled; + this.factions.homes.teleportCommandSmokeEffectThickness = c.homesTeleportCommandSmokeEffectThickness; + this.factions.homes.teleportAllowedFromEnemyTerritory = c.homesTeleportAllowedFromEnemyTerritory; + this.factions.homes.teleportAllowedFromDifferentWorld = c.homesTeleportAllowedFromDifferentWorld; + this.factions.homes.teleportAllowedEnemyDistance = c.homesTeleportAllowedEnemyDistance; + this.factions.homes.teleportIgnoreEnemiesIfInOwnTerritory = c.homesTeleportIgnoreEnemiesIfInOwnTerritory; + + this.factions.pvp.disablePVPBetweenNeutralFactions = c.disablePVPBetweenNeutralFactions; + this.factions.pvp.disablePVPForFactionlessPlayers = c.disablePVPForFactionlessPlayers; + this.factions.pvp.enablePVPAgainstFactionlessInAttackersLand = c.enablePVPAgainstFactionlessInAttackersLand; + this.factions.pvp.noPVPDamageToOthersForXSecondsAfterLogin = c.noPVPDamageToOthersForXSecondsAfterLogin; + this.factions.pvp.worldsIgnorePvP = c.worldsIgnorePvP; + + this.factions.specialCase.peacefulTerritoryDisablePVP = c.peacefulTerritoryDisablePVP; + this.factions.specialCase.peacefulTerritoryDisableMonsters = c.peacefulTerritoryDisableMonsters; + this.factions.specialCase.peacefulTerritoryDisableBoom = c.peacefulTerritoryDisableBoom; + this.factions.specialCase.permanentFactionsDisableLeaderPromotion = c.permanentFactionsDisableLeaderPromotion; + + this.factions.claims.mustBeConnected = c.claimsMustBeConnected; + this.factions.claims.canBeUnconnectedIfOwnedByOtherFaction = c.claimsCanBeUnconnectedIfOwnedByOtherFaction; + this.factions.claims.requireMinFactionMembers = c.claimsRequireMinFactionMembers; + this.factions.claims.landsMax = c.claimedLandsMax; + this.factions.claims.lineClaimLimit = c.lineClaimLimit; + this.factions.claims.radiusClaimFailureLimit = c.radiusClaimFailureLimit; + this.factions.claims.worldsNoClaiming = c.worldsNoClaiming; + + this.factions.protection.permanentFactionMemberDenyCommands = c.permanentFactionMemberDenyCommands; + this.factions.protection.territoryNeutralDenyCommands = c.territoryNeutralDenyCommands; + this.factions.protection.territoryEnemyDenyCommands = c.territoryEnemyDenyCommands; + this.factions.protection.territoryAllyDenyCommands = c.territoryAllyDenyCommands; + this.factions.protection.warzoneDenyCommands = c.warzoneDenyCommands; + this.factions.protection.wildernessDenyCommands = c.wildernessDenyCommands; + this.factions.protection.territoryBlockCreepers = c.territoryBlockCreepers; + this.factions.protection.territoryBlockCreepersWhenOffline = c.territoryBlockCreepersWhenOffline; + this.factions.protection.territoryBlockFireballs = c.territoryBlockFireballs; + this.factions.protection.territoryBlockFireballsWhenOffline = c.territoryBlockFireballsWhenOffline; + this.factions.protection.territoryBlockTNT = c.territoryBlockTNT; + this.factions.protection.territoryBlockTNTWhenOffline = c.territoryBlockTNTWhenOffline; + this.factions.protection.territoryDenyEndermanBlocks = c.territoryDenyEndermanBlocks; + this.factions.protection.territoryDenyEndermanBlocksWhenOffline = c.territoryDenyEndermanBlocksWhenOffline; + this.factions.protection.safeZoneDenyBuild = c.safeZoneDenyBuild; + this.factions.protection.safeZoneDenyUsage = c.safeZoneDenyUseage; + this.factions.protection.safeZoneBlockTNT = c.safeZoneBlockTNT; + this.factions.protection.safeZonePreventAllDamageToPlayers = c.safeZonePreventAllDamageToPlayers; + this.factions.protection.safeZoneDenyEndermanBlocks = c.safeZoneDenyEndermanBlocks; + this.factions.protection.warZoneDenyBuild = c.warZoneDenyBuild; + this.factions.protection.warZoneDenyUsage = c.warZoneDenyUseage; + this.factions.protection.warZoneBlockCreepers = c.warZoneBlockCreepers; + this.factions.protection.warZoneBlockFireballs = c.warZoneBlockFireballs; + this.factions.protection.warZoneBlockTNT = c.warZoneBlockTNT; + this.factions.protection.warZoneFriendlyFire = c.warZoneFriendlyFire; + this.factions.protection.warZoneDenyEndermanBlocks = c.warZoneDenyEndermanBlocks; + this.factions.protection.wildernessDenyBuild = c.wildernessDenyBuild; + this.factions.protection.wildernessDenyUsage = c.wildernessDenyUseage; + this.factions.protection.wildernessBlockCreepers = c.wildernessBlockCreepers; + this.factions.protection.wildernessBlockFireballs = c.wildernessBlockFireballs; + this.factions.protection.wildernessBlockTNT = c.wildernessBlockTNT; + this.factions.protection.wildernessDenyEndermanBlocks = c.wildernessDenyEndermanBlocks; + this.factions.protection.pistonProtectionThroughDenyBuild = c.pistonProtectionThroughDenyBuild; + this.factions.protection.territoryProtectedMaterials = c.territoryProtectedMaterials.stream().filter(Objects::nonNull).map(Material::name).collect(Collectors.toSet()); + this.factions.protection.territoryDenyUsageMaterials = c.territoryDenyUseageMaterials.stream().filter(Objects::nonNull).map(Material::name).collect(Collectors.toSet()); + this.factions.protection.territoryProtectedMaterialsWhenOffline = c.territoryProtectedMaterialsWhenOffline.stream().filter(Objects::nonNull).map(Material::name).collect(Collectors.toSet()); + this.factions.protection.territoryDenyUsageMaterialsWhenOffline = c.territoryDenyUseageMaterialsWhenOffline.stream().filter(Objects::nonNull).map(Material::name).collect(Collectors.toSet()); + this.factions.protection.playersWhoBypassAllProtection = c.playersWhoBypassAllProtection; + this.factions.protection.worldsNoWildernessProtection = c.worldsNoWildernessProtection; + + this.factions.ownedArea.enabled = c.ownedAreasEnabled; + this.factions.ownedArea.limitPerFaction = c.ownedAreasLimitPerFaction; + this.factions.ownedArea.moderatorsCanSet = c.ownedAreasModeratorsCanSet; + this.factions.ownedArea.moderatorsBypass = c.ownedAreaModeratorsBypass; + this.factions.ownedArea.denyBuild = c.ownedAreaDenyBuild; + this.factions.ownedArea.painBuild = c.ownedAreaPainBuild; + this.factions.ownedArea.protectMaterials = c.ownedAreaProtectMaterials; + this.factions.ownedArea.denyUsage = c.ownedAreaDenyUseage; + this.factions.ownedArea.messageOnBorder = c.ownedMessageOnBorder; + this.factions.ownedArea.messageInsideTerritory = c.ownedMessageInsideTerritory; + this.factions.ownedArea.messageByChunk = c.ownedMessageByChunk; + + this.factions.allowMultipleColeaders = c.allowMultipleColeaders; + this.factions.tagLengthMin = c.factionTagLengthMin; + this.factions.tagLengthMax = c.factionTagLengthMax; + this.factions.tagForceUpperCase = c.factionTagForceUpperCase; + this.factions.newFactionsDefaultOpen = c.newFactionsDefaultOpen; + this.factions.factionMemberLimit = c.factionMemberLimit; + this.factions.newPlayerStartingFactionID = c.newPlayerStartingFactionID; + this.factions.saveToFileEveryXMinutes = c.saveToFileEveryXMinutes; + this.factions.autoLeaveAfterDaysOfInactivity = c.autoLeaveAfterDaysOfInactivity; + this.factions.autoLeaveRoutineRunsEveryXMinutes = c.autoLeaveRoutineRunsEveryXMinutes; + this.factions.autoLeaveRoutineMaxMillisecondsPerTick = c.autoLeaveRoutineMaxMillisecondsPerTick; + this.factions.removePlayerDataWhenBanned = c.removePlayerDataWhenBanned; + this.factions.autoLeaveDeleteFPlayerData = c.autoLeaveDeleteFPlayerData; + this.factions.considerFactionsReallyOfflineAfterXMinutes = c.considerFactionsReallyOfflineAfterXMinutes; + this.factions.actionDeniedPainAmount = c.actionDeniedPainAmount; + + this.logging.factionCreate = c.logFactionCreate; + this.logging.factionDisband = c.logFactionDisband; + this.logging.factionJoin = c.logFactionJoin; + this.logging.factionKick = c.logFactionKick; + this.logging.factionLeave = c.logFactionLeave; + this.logging.landClaims = c.logLandClaims; + this.logging.landUnclaims = c.logLandUnclaims; + this.logging.moneyTransactions = c.logMoneyTransactions; + this.logging.playerCommands = c.logPlayerCommands; + + this.exploits.obsidianGenerators = c.handleExploitObsidianGenerators; + this.exploits.enderPearlClipping = c.handleExploitEnderPearlClipping; + this.exploits.interactionSpam = c.handleExploitInteractionSpam; + this.exploits.tntWaterlog = c.handleExploitTNTWaterlog; + this.exploits.liquidFlow = c.handleExploitLiquidFlow; + + this.economy.enabled = c.econEnabled; + this.economy.universeAccount = c.econUniverseAccount; + this.economy.costClaimWilderness = c.econCostClaimWilderness; + this.economy.costClaimFromFactionBonus = c.econCostClaimFromFactionBonus; + this.economy.overclaimRewardMultiplier = c.econOverclaimRewardMultiplier; + this.economy.claimAdditionalMultiplier = c.econClaimAdditionalMultiplier; + this.economy.claimRefundMultiplier = c.econClaimRefundMultiplier; + this.economy.claimUnconnectedFee = c.econClaimUnconnectedFee; + this.economy.costCreate = c.econCostCreate; + this.economy.costOwner = c.econCostOwner; + this.economy.costSethome = c.econCostSethome; + this.economy.costJoin = c.econCostJoin; + this.economy.costLeave = c.econCostLeave; + this.economy.costKick = c.econCostKick; + this.economy.costInvite = c.econCostInvite; + this.economy.costHome = c.econCostHome; + this.economy.costTag = c.econCostTag; + this.economy.costDesc = c.econCostDesc; + this.economy.costTitle = c.econCostTitle; + this.economy.costList = c.econCostList; + this.economy.costMap = c.econCostMap; + this.economy.costPower = c.econCostPower; + this.economy.costShow = c.econCostShow; + this.economy.costStuck = c.econCostStuck; + this.economy.costOpen = c.econCostOpen; + this.economy.costAlly = c.econCostAlly; + this.economy.costTruce = c.econCostTruce; + this.economy.costEnemy = c.econCostEnemy; + this.economy.costNeutral = c.econCostNeutral; + this.economy.costNoBoom = c.econCostNoBoom; + this.economy.bankEnabled = c.bankEnabled; + this.economy.bankMembersCanWithdraw = c.bankMembersCanWithdraw; + this.economy.bankFactionPaysCosts = c.bankFactionPaysCosts; + this.economy.bankFactionPaysLandCosts = c.bankFactionPaysLandCosts; + + this.map.height = c.mapHeight; + this.map.width = c.mapWidth; + this.map.showFactionKey = c.showMapFactionKey; + this.map.showNeutralFactionsOnMap = c.showNeutralFactionsOnMap; + this.map.showEnemyFactions = c.showEnemyFactionsOnMap; + this.map.showTruceFactions = c.showTruceFactionsOnMap; + + this.colors.factions.safezone = c.colorSafezone.name(); + this.colors.factions.warzone = c.colorWar.name(); + this.colors.factions.wilderness = c.colorWilderness.name(); + this.colors.relations.ally = c.colorAlly.name(); + this.colors.relations.enemy = c.colorEnemy.name(); + this.colors.relations.member = c.colorMember.name(); + this.colors.relations.neutral = c.colorNeutral.name(); + this.colors.relations.peaceful = c.colorPeaceful.name(); + this.colors.relations.truce = c.colorTruce.name(); + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v1/OldMainConfigV1.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v1/OldMainConfigV1.java new file mode 100644 index 0000000..0409788 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v1/OldMainConfigV1.java @@ -0,0 +1,421 @@ +package com.massivecraft.factions.config.transition.oldclass.v1; + +import com.massivecraft.factions.config.annotation.Comment; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class OldMainConfigV1 { + public class Colors { + public class Relations { + public String member = "GREEN"; + public String ally = "LIGHT_PURPLE"; + public String truce = "DARK_PURPLE"; + public String neutral = "WHITE"; + public String enemy = "RED"; + public String peaceful = "GOLD"; + } + + public class Factions { + public String wilderness = "GRAY"; + public String safezone = "GOLD"; + public String warzone = "DARK_RED"; + } + + public Factions factions = new Factions(); + public Relations relations = new Relations(); + } + + public class Factions { + public class LandRaidControl { + public class Power { + public double playerMin = -10.0D; + public double playerMax = 10.0D; + public double playerStarting = 0.0D; + @Comment("Default health rate of 0.2 takes 5 minutes to recover one power") + public double powerPerMinute = 0.2; + @Comment("How much is lost on death") + public double lossPerDeath = 4.0; + @Comment("Does a player regenerate power while offline?") + public boolean regenOffline = false; + @Comment("A player loses this much per day offline") + public double offlineLossPerDay = 0.0; + @Comment("A player stops losing power from being offline once they reach this amount") + public double offlineLossLimit = 0.0; + @Comment("If greater than 0, used as a cap for how much power a faction can have\nAdditional power from players beyond this acts as a \"buffer\" of sorts") + public double factionMax = 0.0; + public boolean respawnHomeFromNoPowerLossWorlds = true; + public Set worldsNoPowerLoss = new HashSet<>(); + public boolean peacefulMembersDisablePowerLoss = true; + public boolean warZonePowerLoss = true; + public boolean wildernessPowerLoss = true; + @Comment("Disallow joining/leaving/kicking while power is negative") + public boolean canLeaveWithNegativePower = true; + } + + @Comment("Sets the mode of land/raid control") + public String system = "power"; + @Comment("Controls the power system of land/raid control\nSet the 'system' value to 'power' to use this system") + public Power power = new Power(); + } + + public class Prefix { + public String admin = "***"; + public String coleader = "**"; + public String mod = "*"; + public String normal = "+"; + public String recruit = "-"; + + public String getAdmin() { + return admin; + } + + public String getColeader() { + return coleader; + } + + public String getMod() { + return mod; + } + + public String getNormal() { + return normal; + } + + public String getRecruit() { + return recruit; + } + } + + public class Chat { + @Comment("Allow for players to chat only within their faction, with allies, etc.\n" + + "Set to false to only allow public chats through this plugin.") + public boolean factionOnlyChat = true; + // Configuration on the Faction tag in chat messages. + @Comment("If true, disables adding of faction tag so another plugin can manage this") + public boolean tagHandledByAnotherPlugin = false; + public boolean tagRelationColored = true; + public String tagReplaceString = "[FACTION]"; + public String tagInsertAfterString = ""; + public String tagInsertBeforeString = ""; + public int tagInsertIndex = 0; + public boolean tagPadBefore = false; + public boolean tagPadAfter = true; + public String tagFormat = "%s\u00A7f"; + public boolean alwaysShowChatTag = true; + public String factionChatFormat = "%s:\u00A7f %s"; + public String allianceChatFormat = "\u00A7d%s:\u00A7f %s"; + public String truceChatFormat = "\u00A75%s:\u00A7f %s"; + public String modChatFormat = "\u00A7c%s:\u00A7f %s"; + public boolean broadcastDescriptionChanges = false; + public boolean broadcastTagChanges = false; + } + + public class Homes { + public boolean enabled = true; + public boolean mustBeInClaimedTerritory = true; + public boolean teleportToOnDeath = true; + public boolean teleportCommandEnabled = true; + public boolean teleportCommandEssentialsIntegration = true; + public boolean teleportCommandSmokeEffectEnabled = true; + public float teleportCommandSmokeEffectThickness = 3f; + public boolean teleportAllowedFromEnemyTerritory = true; + public boolean teleportAllowedFromDifferentWorld = true; + public double teleportAllowedEnemyDistance = 32.0; + public boolean teleportIgnoreEnemiesIfInOwnTerritory = true; + } + + public class PVP { + public boolean disablePVPBetweenNeutralFactions = false; + public boolean disablePVPForFactionlessPlayers = false; + public boolean enablePVPAgainstFactionlessInAttackersLand = false; + public int noPVPDamageToOthersForXSecondsAfterLogin = 3; + public Set worldsIgnorePvP = new HashSet<>(); + } + + public class SpecialCase { + public boolean peacefulTerritoryDisablePVP = true; + public boolean peacefulTerritoryDisableMonsters = false; + public boolean peacefulTerritoryDisableBoom = false; + public boolean permanentFactionsDisableLeaderPromotion = false; + } + + public class Claims { + public boolean mustBeConnected = false; + public boolean canBeUnconnectedIfOwnedByOtherFaction = true; + public int requireMinFactionMembers = 1; + public int landsMax = 0; + public int lineClaimLimit = 5; + @Comment("If someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit") + public int radiusClaimFailureLimit = 9; + public Set worldsNoClaiming = new HashSet<>(); + } + + public class Protection { + @Comment("Commands which will be prevented if the player is a member of a permanent faction") + public Set permanentFactionMemberDenyCommands = new HashSet<>(); + + @Comment("Commands which will be prevented when in claimed territory of a neutral faction") + public Set territoryNeutralDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in claimed territory of an enemy faction") + public Set territoryEnemyDenyCommands = new HashSet() { + { + this.add("home"); + this.add("sethome"); + this.add("spawn"); + this.add("tpahere"); + this.add("tpaccept"); + this.add("tpa"); + } + }; + @Comment("Commands which will be prevented when in claimed territory of an ally faction") + public Set territoryAllyDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in warzone") + public Set warzoneDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in wilderness") + public Set wildernessDenyCommands = new HashSet<>(); + + public boolean territoryBlockCreepers = false; + public boolean territoryBlockCreepersWhenOffline = false; + public boolean territoryBlockFireballs = false; + public boolean territoryBlockFireballsWhenOffline = false; + public boolean territoryBlockTNT = false; + public boolean territoryBlockTNTWhenOffline = false; + public boolean territoryDenyEndermanBlocks = true; + public boolean territoryDenyEndermanBlocksWhenOffline = true; + + public boolean safeZoneDenyBuild = true; + public boolean safeZoneDenyUsage = true; + public boolean safeZoneBlockTNT = true; + public boolean safeZonePreventAllDamageToPlayers = false; + public boolean safeZoneDenyEndermanBlocks = true; + + public boolean warZoneDenyBuild = true; + public boolean warZoneDenyUsage = true; + public boolean warZoneBlockCreepers = true; + public boolean warZoneBlockFireballs = true; + public boolean warZoneBlockTNT = true; + public boolean warZoneFriendlyFire = false; + public boolean warZoneDenyEndermanBlocks = true; + + public boolean wildernessDenyBuild = false; + public boolean wildernessDenyUsage = false; + public boolean wildernessBlockCreepers = false; + public boolean wildernessBlockFireballs = false; + public boolean wildernessBlockTNT = false; + + public boolean wildernessDenyEndermanBlocks = false; + + public boolean pistonProtectionThroughDenyBuild = true; + + public Set territoryDenyUsageMaterials = new HashSet<>(); + public Set territoryDenyUsageMaterialsWhenOffline = new HashSet<>(); + + @Comment("Mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections") + public Set playersWhoBypassAllProtection = new HashSet<>(); + public Set worldsNoWildernessProtection = new HashSet<>(); + + public Protection() { + protectUsage("FIRE_CHARGE"); + protectUsage("FLINT_AND_STEEL"); + protectUsage("BUCKET"); + protectUsage("WATER_BUCKET"); + protectUsage("LAVA_BUCKET"); + } + + public void protectUsage(String material) { + territoryDenyUsageMaterials.add(material); + territoryDenyUsageMaterialsWhenOffline.add(material); + } + } + + public class OwnedArea { + public boolean enabled = true; + public int limitPerFaction = 0; + public boolean moderatorsBypass = true; + public boolean denyBuild = true; + public boolean painBuild = false; + public boolean protectMaterials = true; + public boolean denyUsage = true; + + public boolean messageOnBorder = true; + public boolean messageInsideTerritory = true; + public boolean messageByChunk = false; + } + + public Chat chat = new Chat(); + public Homes homes = new Homes(); + public PVP pvp = new PVP(); + public SpecialCase specialCase = new SpecialCase(); + public Claims claims = new Claims(); + public Protection protection = new Protection(); + @Comment("For claimed areas where further faction-member ownership can be defined") + public OwnedArea ownedArea = new OwnedArea(); + @Comment("Displayed prefixes for different roles within a faction") + public Prefix prefixes = new Prefix(); + public LandRaidControl landRaidControl = new LandRaidControl(); + + public boolean allowMultipleColeaders = false; + + @Comment("Minimum faction tag length") + public int tagLengthMin = 3; + @Comment("Maximum faction tag length") + public int tagLengthMax = 10; + public boolean tagForceUpperCase = false; + + public boolean newFactionsDefaultOpen = false; + + @Comment("When faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit") + public int factionMemberLimit = 0; + + @Comment("What faction ID to start new players in when they first join the server; default is 0, \"no faction\"") + public String newPlayerStartingFactionID = "0"; + + public double saveToFileEveryXMinutes = 30.0; + + public double autoLeaveAfterDaysOfInactivity = 10.0; + public double autoLeaveRoutineRunsEveryXMinutes = 5.0; + public int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick + public boolean removePlayerDataWhenBanned = true; + public boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. + public double considerFactionsReallyOfflineAfterXMinutes = 0.0; + public int actionDeniedPainAmount = 1; + + @Comment("If enabled, perms can be managed separately for when the faction is offline") + public boolean separateOfflinePerms = false; + } + + public class Logging { + public boolean factionCreate = true; + public boolean factionDisband = true; + public boolean factionJoin = true; + public boolean factionKick = true; + public boolean factionLeave = true; + public boolean landClaims = true; + public boolean landUnclaims = true; + public boolean moneyTransactions = true; + public boolean playerCommands = true; + } + + public class Exploits { + public boolean obsidianGenerators = true; + public boolean enderPearlClipping = true; + public boolean interactionSpam = true; + public boolean tntWaterlog = false; + public boolean liquidFlow = false; + public boolean preventDuping = true; + } + + public class Economy { + public boolean enabled = false; + public String universeAccount = ""; + public double costClaimWilderness = 30.0; + public double costClaimFromFactionBonus = 30.0; + public double overclaimRewardMultiplier = 0.0; + public double claimAdditionalMultiplier = 0.5; + public double claimRefundMultiplier = 0.7; + public double claimUnconnectedFee = 0.0; + public double costCreate = 100.0; + public double costOwner = 15.0; + public double costSethome = 30.0; + public double costDelhome = 30.0; + public double costJoin = 0.0; + public double costLeave = 0.0; + public double costKick = 0.0; + public double costInvite = 0.0; + public double costHome = 0.0; + public double costTag = 0.0; + public double costDesc = 0.0; + public double costTitle = 0.0; + public double costList = 0.0; + public double costMap = 0.0; + public double costPower = 0.0; + public double costShow = 0.0; + public double costStuck = 0.0; + public double costOpen = 0.0; + public double costAlly = 0.0; + public double costTruce = 0.0; + public double costEnemy = 0.0; + public double costNeutral = 0.0; + public double costNoBoom = 0.0; + + @Comment("Faction banks, to pay for land claiming and other costs instead of individuals paying for them") + public boolean bankEnabled = true; + @Comment("Have to be at least moderator to withdraw or pay money to another faction") + public boolean bankMembersCanWithdraw = false; + @Comment("The faction pays for faction command costs, such as sethome") + public boolean bankFactionPaysCosts = true; + @Comment("The faction pays for land claiming costs.") + public boolean bankFactionPaysLandCosts = true; + } + + public class Map { + public int height = 17; + public int width = 49; + public boolean showFactionKey = true; + public boolean showNeutralFactionsOnMap = true; + public boolean showEnemyFactions = true; + public boolean showTruceFactions = true; + } + + public class Data { + public class Json { + @Comment("If true, data files will be stored without extra whitespace and linebreaks.\n" + + "This becomes less readable, but can cut storage use in half.") + public boolean efficientStorage = false; + } + + @Comment("Presently, the only option is JSON.") + public String storage = "JSON"; + public Json json = new Json(); + } + + public class RestrictWorlds { + @Comment("If true, Factions will only function on certain worlds") + public boolean restrictWorlds = false; + @Comment("If restrictWorlds is true, this setting determines if the world list below is a whitelist or blacklist.\n" + + "True for whitelist, false for blacklist.") + public boolean whitelist = true; + public Set worldList = new HashSet<>(); + } + + public class PlayerVaults { + @Comment("The %s is for the faction id") + public String vaultPrefix = "faction-%s"; + public int defaultMaxVaults = 0; + } + + public class WorldGuard { + public boolean checking; + public boolean buildPriority; + } + + @Comment("The command base (by default f, making the command /f)") + public List commandBase = new ArrayList() { + { + this.add("f"); + } + }; + + @Comment("Colors for relationships and default factions") + public Colors colors = new Colors(); + + public Factions factions = new Factions(); + @Comment("What should be logged?") + public Logging logging = new Logging(); + @Comment("Controls certain exploit preventions") + public Exploits exploits = new Exploits(); + @Comment("Economy support requires Vault and a compatible economy plugin") + public Economy economy = new Economy(); + @Comment("Control for the default settings of /f map") + public Map map = new Map(); + @Comment("Data storage settings") + public Data data = new Data(); + public RestrictWorlds restrictWorlds = new RestrictWorlds(); + @Comment("PlayerVaults faction vault settings") + public PlayerVaults playerVaults = new PlayerVaults(); + @Comment("WorldGuard settings") + public WorldGuard worldGuard = new WorldGuard(); +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v1/TransitionConfigV1.java b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v1/TransitionConfigV1.java new file mode 100644 index 0000000..147c970 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/config/transition/oldclass/v1/TransitionConfigV1.java @@ -0,0 +1,2213 @@ +package com.massivecraft.factions.config.transition.oldclass.v1; + +import com.massivecraft.factions.config.annotation.Comment; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@SuppressWarnings("ALL") +public class TransitionConfigV1 { + public static class AVeryFriendlyFactionsConfig { + @Comment("Don't change this value yourself, unless you WANT a broken config!") + private int version = 2; + + @Comment("Debug\n" + + "Turn this on if you are having issues with something and working on resolving them.\n" + + "This will spam your console with information that is useful if you know how to read the source.\n" + + "It's suggested that you only turn this on at the direction of a developer.") + private boolean debug = false; + + public boolean isDebug() { + return debug; + } + } + + public class Colors { + public class Relations { + private String member = "GREEN"; + private transient ChatColor memberColor; + private String ally = "LIGHT_PURPLE"; + private transient ChatColor allyColor; + private String truce = "DARK_PURPLE"; + private transient ChatColor truceColor; + private String neutral = "WHITE"; + private transient ChatColor neutralColor; + private String enemy = "RED"; + private transient ChatColor enemyColor; + private String peaceful = "GOLD"; + private transient ChatColor peacefulColor; + + public ChatColor getMember() { + return memberColor = Colors.this.getColor(this.member, this.memberColor, ChatColor.GREEN); + } + + public ChatColor getAlly() { + return allyColor = Colors.this.getColor(this.ally, this.allyColor, ChatColor.LIGHT_PURPLE); + } + + public ChatColor getTruce() { + return truceColor = Colors.this.getColor(this.truce, this.truceColor, ChatColor.DARK_PURPLE); + } + + public ChatColor getNeutral() { + return neutralColor = Colors.this.getColor(this.neutral, this.neutralColor, ChatColor.WHITE); + } + + public ChatColor getEnemy() { + return enemyColor = Colors.this.getColor(this.enemy, this.enemyColor, ChatColor.RED); + } + + public ChatColor getPeaceful() { + return peacefulColor = Colors.this.getColor(this.peaceful, this.peacefulColor, ChatColor.GOLD); + } + } + + public class Factions { + private String wilderness = "GRAY"; + private transient ChatColor wildernessColor; + private String safezone = "GOLD"; + private transient ChatColor safezoneColor; + private String warzone = "DARK_RED"; + private transient ChatColor warzoneColor; + + public ChatColor getWilderness() { + return wildernessColor = Colors.this.getColor(this.wilderness, this.wildernessColor, ChatColor.GRAY); + } + + public ChatColor getSafezone() { + return safezoneColor = Colors.this.getColor(this.safezone, this.safezoneColor, ChatColor.GOLD); + } + + public ChatColor getWarzone() { + return warzoneColor = Colors.this.getColor(this.warzone, this.warzoneColor, ChatColor.DARK_RED); + } + } + + private Factions factions = new Factions(); + private Relations relations = new Relations(); + + private ChatColor getColor(String name, ChatColor current, ChatColor defaultColor) { + if (current != null) { + return current; + } + ChatColor ret; + try { + ret = ChatColor.valueOf(name); + } catch (IllegalArgumentException e) { + ret = defaultColor; + } + return ret; + } + + public Factions factions() { + return factions; + } + + public Relations relations() { + return relations; + } + } + + public class Commands { + public class Fly { + public class Particles { + @Comment("Speed of the particles, can be decimal value") + private double speed = 0.02; + @Comment("Amount spawned") + private int amount = 20; + @Comment("How often should we spawn these particles?\n" + + "0 disables this completely") + private double spawnRate = 0.2; + + public double getSpeed() { + return speed; + } + + public int getAmount() { + return amount; + } + + public double getSpawnRate() { + return spawnRate; + } + } + + @Comment("Warmup seconds before command executes. Set to 0 for no warmup.") + private int delay = 0; + @Comment("True to enable the fly command, false to disable") + private boolean enable = true; + @Comment("If a player leaves fly (out of territory or took damage)\n" + + "how long (in seconds) should they not take fall damage for?\n" + + "Set to 0 to have them always take fall damage.") + private int fallDamageCooldown = 3; + @Comment("From how far away a player can disable another's flight by being enemy\n" + + "Set to 0 if wanted disable\n" + + "Note: Will produce lag at higher numbers") + private int enemyRadius = 7; + @Comment("How frequently to check enemy radius, in seconds. Set to 0 to disable checking.") + private int radiusCheck = 1; + @Comment("Should we disable flight if the player has suffered generic damage") + private boolean disableOnGenericDamage = false; + + @Comment("Trails show below the players foot when flying, faction.fly.trails\n" + + "Players can enable them with /f trail on/off\n" + + "Players can also set which effect to show /f trail effect only if they have faction.fly.trails.") + private Particles particles = new Particles(); + + public int getDelay() { + return delay; + } + + public boolean isEnable() { + return enable; + } + + public int getFallDamageCooldown() { + return fallDamageCooldown; + } + + public int getEnemyRadius() { + return enemyRadius; + } + + public int getRadiusCheck() { + return radiusCheck; + } + + public boolean isDisableOnGenericDamage() { + return disableOnGenericDamage; + } + + public Particles particles() { + return particles; + } + } + + public class Help { + @Comment("You can change the page name to whatever you like\n" + + "We use '1' to preserve default functionality of /f help 1") + private Map> entries = new HashMap>() { + { + this.put("1", Arrays.asList( + "&e&m----------------------------------------------", + " &c&lFactions Help ", + "&e&m----------------------------------------------", + "&3/f create &e>> &7Create your own faction", + "&3/f who &e>> &7Show factions info", + "&3/f tag &e>> &7Change faction tag", + "&3/f join &e>> &7Join faction", + "&3/f list &e>> &7List all factions", + "&e&m--------------&r &2/f help 2 for more &e&m--------------")); + this.put("2", Arrays.asList( + "&e&m------------------&r&c&l Page 2 &e&m--------------------", + "&3/f home &e>> &7Teleport to faction home", + "&3/f sethome &e>> &7Set your faction home", + "&3/f leave &e>> &7Leave your faction", + "&3/f invite &e>> &7Invite a player to your faction", + "&3/f deinvite &e>> &7Revoke invitation to player", + "&e&m--------------&r &2/f help 3 for more &e&m--------------")); + this.put("3", Arrays.asList( + "&e&m------------------&r&c&l Page 3 &e&m--------------------", + "&3/f claim &e>> &7Claim land", + "&3/f unclaim &e>> &7Unclaim land", + "&3/f kick &e>> &7Kick player from your faction", + "&3/f mod &e>> &7Set player role in faction", + "&3/f chat &e>> &7Switch to faction chat", + "&e&m--------------&r &2/f help 4 for more &e&m--------------")); + this.put("4", Arrays.asList( + "&e&m------------------&r&c&l Page 4 &e&m--------------------", + "&3/f version &e>> &7Display version information", + "&e&m--------------&r&2 End of /f help &e&m-----------------")); + } + }; + @Comment("set to true to use legacy factions help") + private boolean useOldHelp = true; + + public Map> getEntries() { + return entries != null ? entries : Collections.emptyMap(); + } + + public boolean isUseOldHelp() { + return useOldHelp; + } + } + + public class Home { + @Comment("Warmup seconds before command executes. Set to 0 for no warmup.") + private int delay = 0; + + public int getDelay() { + return delay; + } + } + + public class ListCmd { + @Comment("You can only use {pagenumber} and {pagecount} in the header") + private String header = "&e&m----------&r&e[ &2Faction List &9{pagenumber}&e/&9{pagecount} &e]&m----------"; + @Comment("You can use any variables here") + private String factionlessEntry = "Factionless {factionless} online"; + @Comment("You can use any variable here") + private String entry = "{faction-relation-color}{faction} {online} / {members} online, Land / Power / Maxpower: {chunks}/{power}/{maxPower}"; + + public String getHeader() { + return header; + } + + public String getFactionlessEntry() { + return factionlessEntry; + } + + public String getEntry() { + return entry; + } + } + + public class MapCmd { + @Comment("This will help limit how many times a player can be sent a map of factions.\n" + + "Set this to the cooldown you want, in milliseconds, for a map to be shown to a player.\n" + + "This can prevent some teleportation-based exploits for finding factions.\n" + + "The old default was 2000, which blocks any movement faster than running.\n" + + "The new default is 700, which should also allow boats and horses.") + private int cooldown = 700; + + public int getCooldown() { + return cooldown; + } + } + + public class Near { + @Comment("Making this radius larger increases lag, do so at your own risk\n" + + "If on a high radius it is advised to add a cooldown to the command\n" + + "Also using {distance} placeholder in the lang would cause more lag on a bigger radius") + private int radius = 20; + + public int getRadius() { + return radius; + } + } + + public class SeeChunk { + private boolean particles = true; + @Comment("Get a list of particle names here: https://factions.support/particles/") + private String particleName = "REDSTONE"; + @Comment("If the chosen particle is compatible with coloring we will color\n" + + "it based on the current chunk's faction") + private boolean relationalColor = true; + @Comment("How often should we update the particles to the current player's location?") + private double particleUpdateTime = 0.75; + + public boolean isParticles() { + return particles; + } + + public String getParticleName() { + return particleName; + } + + public boolean isRelationalColor() { + return relationalColor; + } + + public double getParticleUpdateTime() { + return particleUpdateTime; + } + } + + public class Show { + @Comment("You can use any variable here, including fancy messages. Color codes and or tags work fine.\n" + + "Lines that aren't defined wont be sent (home not set, faction not peaceful / permanent, dtr freeze)\n" + + "Supports placeholders.\n" + + "First line can be {header} for default header, or any string (we recommend &m for smooth lines ;p)\n" + + "The line with 'permanent' in it only appears if the faction is permanent.") + private List format = new ArrayList() { + { + this.add("{header}"); + this.add("Description: {description}"); + this.add("Joining: {joining} {peaceful}"); + this.add("Land / Power / Maxpower: {chunks}/{power}/{maxPower}"); + this.add("Raidable: {raidable}"); + this.add("Founded: {create-date}"); + this.add("This faction is permanent, remaining even with no members.'"); + this.add("Land value: {land-value} {land-refund}"); + this.add("Balance: {faction-balance}"); + this.add("Bans: {faction-bancount}"); + this.add("Allies({allies}/{max-allies}): {allies-list} "); + this.add("Online: ({online}/{members}): {online-list}"); + this.add("Offline: ({offline}/{members}): {offline-list}"); + } + }; + @Comment("Set true to not display empty fancy messages") + private boolean minimal = false; + @Comment("Factions that should be exempt from /f show, case sensitive, useful for a\n" + + "serverteam faction, since the command shows vanished players otherwise") + private List exempt = new ArrayList() { + { + this.add("put_faction_tag_here"); + } + }; + + public List getFormat() { + return format != null ? format : Collections.emptyList(); + } + + public boolean isMinimal() { + return minimal; + } + + public List getExempt() { + return exempt != null ? exempt : Collections.emptyList(); + } + } + + public class Stuck { + @Comment("Warmup seconds before command executes. Set to 0 for no warmup.") + private int delay = 30; + @Comment("This radius defines how far from where they ran the command the player\n" + + "may travel while waiting to be unstuck. If they leave this radius, the\n" + + "command will be cancelled.") + private int radius = 10; + + public int getDelay() { + return delay; + } + + public int getRadius() { + return radius; + } + } + + public class Warp { + @Comment("Warmup seconds before command executes. Set to 0 for no warmup.") + private int delay = 0; + @Comment("What should be the maximum amount of warps that a Faction can set?") + private int maxWarps = 5; + + public int getDelay() { + return delay; + } + + public int getMaxWarps() { + return maxWarps; + } + } + + public class ToolTips { + @Comment("Faction on-hover tooltip information") + private List faction = new ArrayList() { + { + this.add("&7Leader: &a{leader}"); + this.add("&7Claimed: &a{chunks}"); + this.add("&7Raidable: &a{raidable}"); + this.add("&7Warps: &a{warps}"); + this.add("&7Power: &a{power}&8/&a{maxPower}"); + this.add("&7Members: &a{online}&8/&a{members}"); + } + }; + @Comment("Player on-hover tooltip information") + private List player = new ArrayList() { + { + this.add("&7Last Seen: &a{lastSeen}"); + this.add("&7Power: &a{power}"); + this.add("&7Rank: &a{group}"); + this.add("&7Balance: &a${balance}"); + } + }; + + public List getFaction() { + return faction != null ? faction : Collections.emptyList(); + } + + public List getPlayer() { + return player != null ? player : Collections.emptyList(); + } + } + + private Fly fly = new Fly(); + private Help help = new Help(); + private Home home = new Home(); + private ListCmd list = new ListCmd(); + private MapCmd map = new MapCmd(); + private Near near = new Near(); + private SeeChunk seeChunk = new SeeChunk(); + private Show show = new Show(); + private Stuck stuck = new Stuck(); + private ToolTips toolTips = new ToolTips(); + private Warp warp = new Warp(); + + public Fly fly() { + return fly; + } + + public Help help() { + return help; + } + + public Home home() { + return home; + } + + public ListCmd list() { + return list; + } + + public MapCmd map() { + return map; + } + + public Near near() { + return near; + } + + public SeeChunk seeChunk() { + return seeChunk; + } + + public Show show() { + return show; + } + + public Stuck stuck() { + return stuck; + } + + public ToolTips toolTips() { + return toolTips; + } + + public Warp warp() { + return warp; + } + } + + public class Factions { + public class LandRaidControl { + public class Power { + private double playerMin = -10.0D; + private double playerMax = 10.0D; + private double playerStarting = 0.0D; + @Comment("Default health rate of 0.2 takes 5 minutes to recover one power") + private double powerPerMinute = 0.2; + @Comment("How much is lost on death") + private double lossPerDeath = 4.0; + @Comment("Does a player regenerate power while offline?") + private boolean regenOffline = false; + @Comment("A player loses this much per day offline") + private double offlineLossPerDay = 0.0; + @Comment("A player stops losing power from being offline once they reach this amount") + private double offlineLossLimit = 0.0; + @Comment("If greater than 0, used as a cap for how much power a faction can have\nAdditional power from players beyond this acts as a \"buffer\" of sorts") + private double factionMax = 0.0; + private boolean respawnHomeFromNoPowerLossWorlds = true; + private Set worldsNoPowerLoss = new HashSet<>(); + private boolean peacefulMembersDisablePowerLoss = true; + private boolean warZonePowerLoss = true; + private boolean wildernessPowerLoss = true; + @Comment("Disallow joining/leaving/kicking while power is negative") + private boolean canLeaveWithNegativePower = true; + @Comment("Allow a faction to be raided if they have more land than power.\n" + + "This will make claimed territory lose all protections\n" + + " allowing factions to open chests, break blocks, etc. if they\n" + + " have claimed chunks >= power.") + private boolean raidability = false; + @Comment("After a player dies, how long should the faction not be able to regen power?\n" + + "This resets on each death but does not accumulate.\n" + + "Set to 0 for no freeze. Time is in seconds.") + private int powerFreeze = 0; + + public boolean isRaidability() { + return raidability; + } + + public int getPowerFreeze() { + return powerFreeze; + } + + public boolean canLeaveWithNegativePower() { + return canLeaveWithNegativePower; + } + + public boolean isWarZonePowerLoss() { + return warZonePowerLoss; + } + + public boolean isWildernessPowerLoss() { + return wildernessPowerLoss; + } + + public double getPlayerMin() { + return playerMin; + } + + public double getPlayerMax() { + return playerMax; + } + + public double getPlayerStarting() { + return playerStarting; + } + + public double getPowerPerMinute() { + return powerPerMinute; + } + + public double getLossPerDeath() { + return lossPerDeath; + } + + public boolean isRegenOffline() { + return regenOffline; + } + + public double getOfflineLossPerDay() { + return offlineLossPerDay; + } + + public double getOfflineLossLimit() { + return offlineLossLimit; + } + + public double getFactionMax() { + return factionMax; + } + + public boolean isRespawnHomeFromNoPowerLossWorlds() { + return respawnHomeFromNoPowerLossWorlds; + } + + public Set getWorldsNoPowerLoss() { + return worldsNoPowerLoss == null ? Collections.emptySet() : worldsNoPowerLoss; + } + + public boolean isPeacefulMembersDisablePowerLoss() { + return peacefulMembersDisablePowerLoss; + } + } + + @Comment("Sets the mode of land/raid control") + private String system = "power"; + @Comment("Controls the power system of land/raid control\nSet the 'system' value to 'power' to use this system") + private Power power = new Power(); + + public String getSystem() { + return system; + } + + public Power power() { + return power; + } + } + + public class Prefix { + private String admin = "***"; + private String coleader = "**"; + private String mod = "*"; + private String normal = "+"; + private String recruit = "-"; + + public String getAdmin() { + return admin; + } + + public String getColeader() { + return coleader; + } + + public String getMod() { + return mod; + } + + public String getNormal() { + return normal; + } + + public String getRecruit() { + return recruit; + } + } + + public class Chat { + @Comment("Allow for players to chat only within their faction, with allies, etc.\n" + + "Set to false to only allow public chats through this plugin.") + private boolean factionOnlyChat = true; + // Configuration on the Faction tag in chat messages. + @Comment("If true, disables adding of faction tag so another plugin can manage this") + private boolean tagHandledByAnotherPlugin = false; + private boolean tagRelationColored = true; + private String tagReplaceString = "[FACTION]"; + private String tagInsertAfterString = ""; + private String tagInsertBeforeString = ""; + private int tagInsertIndex = 0; + private boolean tagPadBefore = false; + private boolean tagPadAfter = true; + private String tagFormat = "%s\u00A7f"; + private boolean alwaysShowChatTag = true; + private String factionChatFormat = "%s:\u00A7f %s"; + private String allianceChatFormat = "\u00A7d%s:\u00A7f %s"; + private String truceChatFormat = "\u00A75%s:\u00A7f %s"; + private String modChatFormat = "\u00A7c%s:\u00A7f %s"; + private boolean broadcastDescriptionChanges = false; + private boolean broadcastTagChanges = false; + + public boolean isFactionOnlyChat() { + return factionOnlyChat; + } + + public boolean isTagHandledByAnotherPlugin() { + return tagHandledByAnotherPlugin; + } + + public boolean isTagRelationColored() { + return tagRelationColored; + } + + public String getTagReplaceString() { + return tagReplaceString; + } + + public String getTagInsertAfterString() { + return tagInsertAfterString; + } + + public String getTagInsertBeforeString() { + return tagInsertBeforeString; + } + + public int getTagInsertIndex() { + return tagInsertIndex; + } + + public boolean isTagPadBefore() { + return tagPadBefore; + } + + public boolean isTagPadAfter() { + return tagPadAfter; + } + + public String getTagFormat() { + return tagFormat; + } + + public boolean isAlwaysShowChatTag() { + return alwaysShowChatTag; + } + + public String getFactionChatFormat() { + return factionChatFormat; + } + + public String getAllianceChatFormat() { + return allianceChatFormat; + } + + public String getTruceChatFormat() { + return truceChatFormat; + } + + public String getModChatFormat() { + return modChatFormat; + } + + public boolean isBroadcastDescriptionChanges() { + return broadcastDescriptionChanges; + } + + public boolean isBroadcastTagChanges() { + return broadcastTagChanges; + } + } + + public class Homes { + private boolean enabled = true; + private boolean mustBeInClaimedTerritory = true; + private boolean teleportToOnDeath = true; + private boolean teleportCommandEnabled = true; + private boolean teleportCommandEssentialsIntegration = true; + private boolean teleportCommandSmokeEffectEnabled = true; + private float teleportCommandSmokeEffectThickness = 3f; + private boolean teleportAllowedFromEnemyTerritory = true; + private boolean teleportAllowedFromDifferentWorld = true; + private double teleportAllowedEnemyDistance = 32.0; + private boolean teleportIgnoreEnemiesIfInOwnTerritory = true; + + public boolean isEnabled() { + return enabled; + } + + public boolean isMustBeInClaimedTerritory() { + return mustBeInClaimedTerritory; + } + + public boolean isTeleportToOnDeath() { + return teleportToOnDeath; + } + + public boolean isTeleportCommandEnabled() { + return teleportCommandEnabled; + } + + public boolean isTeleportCommandEssentialsIntegration() { + return teleportCommandEssentialsIntegration; + } + + public boolean isTeleportCommandSmokeEffectEnabled() { + return teleportCommandSmokeEffectEnabled; + } + + public float getTeleportCommandSmokeEffectThickness() { + return teleportCommandSmokeEffectThickness; + } + + public boolean isTeleportAllowedFromEnemyTerritory() { + return teleportAllowedFromEnemyTerritory; + } + + public boolean isTeleportAllowedFromDifferentWorld() { + return teleportAllowedFromDifferentWorld; + } + + public double getTeleportAllowedEnemyDistance() { + return teleportAllowedEnemyDistance; + } + + public boolean isTeleportIgnoreEnemiesIfInOwnTerritory() { + return teleportIgnoreEnemiesIfInOwnTerritory; + } + } + + public class MaxRelations { + private boolean enabled = false; + private int ally = 10; + private int truce = 10; + private int neutral = -1; + private int enemy = 10; + + public boolean isEnabled() { + return enabled; + } + + public int getAlly() { + return ally; + } + + public int getTruce() { + return truce; + } + + public int getNeutral() { + return neutral; + } + + public int getEnemy() { + return enemy; + } + } + + public class PVP { + private boolean disablePVPBetweenNeutralFactions = false; + private boolean disablePVPForFactionlessPlayers = false; + private boolean enablePVPAgainstFactionlessInAttackersLand = false; + private int noPVPDamageToOthersForXSecondsAfterLogin = 3; + private Set worldsIgnorePvP = new HashSet<>(); + + public boolean isDisablePVPBetweenNeutralFactions() { + return disablePVPBetweenNeutralFactions; + } + + public boolean isDisablePVPForFactionlessPlayers() { + return disablePVPForFactionlessPlayers; + } + + public boolean isEnablePVPAgainstFactionlessInAttackersLand() { + return enablePVPAgainstFactionlessInAttackersLand; + } + + public int getNoPVPDamageToOthersForXSecondsAfterLogin() { + return noPVPDamageToOthersForXSecondsAfterLogin; + } + + public Set getWorldsIgnorePvP() { + return worldsIgnorePvP == null ? Collections.emptySet() : worldsIgnorePvP; + } + } + + public class SpecialCase { + private boolean peacefulTerritoryDisablePVP = true; + private boolean peacefulTerritoryDisableMonsters = false; + private boolean peacefulTerritoryDisableBoom = false; + private boolean permanentFactionsDisableLeaderPromotion = false; + + public boolean isPeacefulTerritoryDisablePVP() { + return peacefulTerritoryDisablePVP; + } + + public boolean isPeacefulTerritoryDisableMonsters() { + return peacefulTerritoryDisableMonsters; + } + + public boolean isPeacefulTerritoryDisableBoom() { + return peacefulTerritoryDisableBoom; + } + + public boolean isPermanentFactionsDisableLeaderPromotion() { + return permanentFactionsDisableLeaderPromotion; + } + } + + public class Portals { + @Comment("If true, portals will be limited to the minimum relation below") + private boolean limit = false; + @Comment("What should the minimum relation be to create a portal in territory?\n" + + "Goes in the order of: ENEMY, NEUTRAL, ALLY, MEMBER.\n" + + "Minimum relation allows that and all listed to the right to create portals.\n" + + "Example: put ALLY to allow ALLY and MEMBER to be able to create portals.\n" + + "If typed incorrectly, defaults to NEUTRAL.") + private String minimumRelation = "MEMBER"; + + public boolean isLimit() { + return limit; + } + + public String getMinimumRelation() { + return minimumRelation; + } + } + + public class Claims { + private boolean mustBeConnected = false; + private boolean canBeUnconnectedIfOwnedByOtherFaction = true; + private int requireMinFactionMembers = 1; + private int landsMax = 0; + private int lineClaimLimit = 5; + @Comment("If someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit") + private int radiusClaimFailureLimit = 9; + private Set worldsNoClaiming = new HashSet<>(); + @Comment("Buffer Zone is an chunk area required between claims of different Factions.\n" + + "This is default to 0 and has always been that way. Meaning Factions can have\n" + + " claims that border each other.\n" + + "If this is set to 3, then Factions need to have 3 chunks between their claim\n" + + " and another Faction's claim.\n" + + "It's recommended to keep this pretty low as the radius check could be a\n" + + " heavy operation if set to a large number.\n" + + "If this is set to 0, we won't even bother checking which is how Factions has\n" + + " always been.") + private int bufferZone = 0; + @Comment("Should we allow Factions to over claim if they are raidable?\n" + + "This has always been true, allowing factions to over claim others.") + private boolean allowOverClaim = true; + + public boolean isAllowOverClaim() { + return allowOverClaim; + } + + public int getBufferZone() { + return bufferZone; + } + + public boolean isMustBeConnected() { + return mustBeConnected; + } + + public boolean isCanBeUnconnectedIfOwnedByOtherFaction() { + return canBeUnconnectedIfOwnedByOtherFaction; + } + + public int getRequireMinFactionMembers() { + return requireMinFactionMembers; + } + + public int getLandsMax() { + return landsMax; + } + + public int getLineClaimLimit() { + return lineClaimLimit; + } + + public int getRadiusClaimFailureLimit() { + return radiusClaimFailureLimit; + } + + public Set getWorldsNoClaiming() { + return worldsNoClaiming == null ? Collections.emptySet() : worldsNoClaiming; + } + } + + public class Protection { + @Comment("Commands which will be prevented if the player is a member of a permanent faction") + private Set permanentFactionMemberDenyCommands = new HashSet<>(); + + @Comment("Commands which will be prevented when in claimed territory of a neutral faction") + private Set territoryNeutralDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in claimed territory of an enemy faction") + private Set territoryEnemyDenyCommands = new HashSet() { + { + this.add("home"); + this.add("sethome"); + this.add("spawn"); + this.add("tpahere"); + this.add("tpaccept"); + this.add("tpa"); + } + }; + @Comment("Commands which will be prevented when in claimed territory of an ally faction") + private Set territoryAllyDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in warzone") + private Set warzoneDenyCommands = new HashSet<>(); + @Comment("Commands which will be prevented when in wilderness") + private Set wildernessDenyCommands = new HashSet<>(); + + private boolean territoryBlockCreepers = false; + private boolean territoryBlockCreepersWhenOffline = false; + private boolean territoryBlockFireballs = false; + private boolean territoryBlockFireballsWhenOffline = false; + private boolean territoryBlockTNT = false; + private boolean territoryBlockTNTWhenOffline = false; + private boolean territoryDenyEndermanBlocks = true; + private boolean territoryDenyEndermanBlocksWhenOffline = true; + + private boolean safeZoneDenyBuild = true; + private boolean safeZoneDenyUsage = true; + private boolean safeZoneBlockTNT = true; + private boolean safeZonePreventAllDamageToPlayers = false; + private boolean safeZoneDenyEndermanBlocks = true; + + private boolean warZoneDenyBuild = true; + private boolean warZoneDenyUsage = true; + private boolean warZoneBlockCreepers = true; + private boolean warZoneBlockFireballs = true; + private boolean warZoneBlockTNT = true; + private boolean warZoneFriendlyFire = false; + private boolean warZoneDenyEndermanBlocks = true; + + private boolean wildernessDenyBuild = false; + private boolean wildernessDenyUsage = false; + private boolean wildernessBlockCreepers = false; + private boolean wildernessBlockFireballs = false; + private boolean wildernessBlockTNT = false; + + private boolean wildernessDenyEndermanBlocks = false; + + private boolean pistonProtectionThroughDenyBuild = true; + + private Set territoryDenyUsageMaterials = new HashSet<>(); + private Set territoryDenyUsageMaterialsWhenOffline = new HashSet<>(); + private transient Set territoryDenyUsageMaterialsMat; + private transient Set territoryDenyUsageMaterialsWhenOfflineMat; + + @Comment("Mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections") + private Set playersWhoBypassAllProtection = new HashSet<>(); + private Set worldsNoWildernessProtection = new HashSet<>(); + + private Protection() { + protectUsage("FIRE_CHARGE"); + protectUsage("FLINT_AND_STEEL"); + protectUsage("BUCKET"); + protectUsage("WATER_BUCKET"); + protectUsage("LAVA_BUCKET"); + } + + private void protectUsage(String material) { + territoryDenyUsageMaterials.add(material); + territoryDenyUsageMaterialsWhenOffline.add(material); + } + + public Set getPermanentFactionMemberDenyCommands() { + return permanentFactionMemberDenyCommands == null ? Collections.emptySet() : permanentFactionMemberDenyCommands; + } + + public Set getTerritoryNeutralDenyCommands() { + return territoryNeutralDenyCommands == null ? Collections.emptySet() : territoryNeutralDenyCommands; + } + + public Set getTerritoryEnemyDenyCommands() { + return territoryEnemyDenyCommands == null ? Collections.emptySet() : territoryEnemyDenyCommands; + } + + public Set getTerritoryAllyDenyCommands() { + return territoryAllyDenyCommands == null ? Collections.emptySet() : territoryAllyDenyCommands; + } + + public Set getWarzoneDenyCommands() { + return warzoneDenyCommands == null ? Collections.emptySet() : warzoneDenyCommands; + } + + public Set getWildernessDenyCommands() { + return wildernessDenyCommands == null ? Collections.emptySet() : wildernessDenyCommands; + } + + public boolean isTerritoryBlockCreepers() { + return territoryBlockCreepers; + } + + public boolean isTerritoryBlockCreepersWhenOffline() { + return territoryBlockCreepersWhenOffline; + } + + public boolean isTerritoryBlockFireballs() { + return territoryBlockFireballs; + } + + public boolean isTerritoryBlockFireballsWhenOffline() { + return territoryBlockFireballsWhenOffline; + } + + public boolean isTerritoryBlockTNT() { + return territoryBlockTNT; + } + + public boolean isTerritoryBlockTNTWhenOffline() { + return territoryBlockTNTWhenOffline; + } + + public boolean isTerritoryDenyEndermanBlocks() { + return territoryDenyEndermanBlocks; + } + + public boolean isTerritoryDenyEndermanBlocksWhenOffline() { + return territoryDenyEndermanBlocksWhenOffline; + } + + public boolean isSafeZoneDenyBuild() { + return safeZoneDenyBuild; + } + + public boolean isSafeZoneDenyUsage() { + return safeZoneDenyUsage; + } + + public boolean isSafeZoneBlockTNT() { + return safeZoneBlockTNT; + } + + public boolean isSafeZonePreventAllDamageToPlayers() { + return safeZonePreventAllDamageToPlayers; + } + + public boolean isSafeZoneDenyEndermanBlocks() { + return safeZoneDenyEndermanBlocks; + } + + public boolean isWarZoneDenyBuild() { + return warZoneDenyBuild; + } + + public boolean isWarZoneDenyUsage() { + return warZoneDenyUsage; + } + + public boolean isWarZoneBlockCreepers() { + return warZoneBlockCreepers; + } + + public boolean isWarZoneBlockFireballs() { + return warZoneBlockFireballs; + } + + public boolean isWarZoneBlockTNT() { + return warZoneBlockTNT; + } + + public boolean isWarZoneFriendlyFire() { + return warZoneFriendlyFire; + } + + public boolean isWarZoneDenyEndermanBlocks() { + return warZoneDenyEndermanBlocks; + } + + public boolean isWildernessDenyBuild() { + return wildernessDenyBuild; + } + + public boolean isWildernessDenyUsage() { + return wildernessDenyUsage; + } + + public boolean isWildernessBlockCreepers() { + return wildernessBlockCreepers; + } + + public boolean isWildernessBlockFireballs() { + return wildernessBlockFireballs; + } + + public boolean isWildernessBlockTNT() { + return wildernessBlockTNT; + } + + public boolean isWildernessDenyEndermanBlocks() { + return wildernessDenyEndermanBlocks; + } + + public boolean isPistonProtectionThroughDenyBuild() { + return pistonProtectionThroughDenyBuild; + } + + public Set getTerritoryDenyUsageMaterials() { + if (territoryDenyUsageMaterialsMat == null) { + territoryDenyUsageMaterialsMat = new HashSet<>(); + territoryDenyUsageMaterials.forEach(m -> territoryDenyUsageMaterialsMat.add(MaterialDb.get(m))); + territoryDenyUsageMaterialsMat.remove(Material.AIR); + } + return territoryDenyUsageMaterialsMat; + } + + public Set getTerritoryDenyUsageMaterialsWhenOffline() { + if (territoryDenyUsageMaterialsWhenOfflineMat == null) { + territoryDenyUsageMaterialsWhenOfflineMat = new HashSet<>(); + territoryDenyUsageMaterialsWhenOffline.forEach(m -> territoryDenyUsageMaterialsWhenOfflineMat.add(MaterialDb.get(m))); + territoryDenyUsageMaterialsWhenOfflineMat.remove(Material.AIR); + } + return territoryDenyUsageMaterialsWhenOfflineMat; + } + + public Set getPlayersWhoBypassAllProtection() { + return playersWhoBypassAllProtection == null ? Collections.emptySet() : playersWhoBypassAllProtection; + } + + public Set getWorldsNoWildernessProtection() { + return worldsNoWildernessProtection == null ? Collections.emptySet() : worldsNoWildernessProtection; + } + } + + public class OwnedArea { + private boolean enabled = true; + private int limitPerFaction = 0; + private boolean moderatorsBypass = true; + private boolean denyBuild = true; + private boolean painBuild = false; + private boolean protectMaterials = true; + private boolean denyUsage = true; + + private boolean messageOnBorder = true; + private boolean messageInsideTerritory = true; + private boolean messageByChunk = false; + + public boolean isEnabled() { + return enabled; + } + + public int getLimitPerFaction() { + return limitPerFaction; + } + + public boolean isModeratorsBypass() { + return moderatorsBypass; + } + + public boolean isDenyBuild() { + return denyBuild; + } + + public boolean isPainBuild() { + return painBuild; + } + + public boolean isProtectMaterials() { + return protectMaterials; + } + + public boolean isDenyUsage() { + return denyUsage; + } + + public boolean isMessageOnBorder() { + return messageOnBorder; + } + + public boolean isMessageInsideTerritory() { + return messageInsideTerritory; + } + + public boolean isMessageByChunk() { + return messageByChunk; + } + } + + public class Other { + private boolean allowMultipleColeaders = false; + + @Comment("Minimum faction tag length") + private int tagLengthMin = 3; + @Comment("Maximum faction tag length") + private int tagLengthMax = 10; + private boolean tagForceUpperCase = false; + + private boolean newFactionsDefaultOpen = false; + + @Comment("When faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit") + private int factionMemberLimit = 0; + + @Comment("What faction ID to start new players in when they first join the server; default is 0, \"no faction\"") + private String newPlayerStartingFactionID = "0"; + + private double saveToFileEveryXMinutes = 30.0; + + private double autoLeaveAfterDaysOfInactivity = 10.0; + private double autoLeaveRoutineRunsEveryXMinutes = 5.0; + private int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick + private boolean removePlayerDataWhenBanned = true; + private boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. + private double considerFactionsReallyOfflineAfterXMinutes = 0.0; + private int actionDeniedPainAmount = 1; + + @Comment("If enabled, perms can be managed separately for when the faction is offline") + private boolean separateOfflinePerms = false; + + @Comment("Should we delete player homes that they set via Essentials when they leave a Faction\n" + + "if they have homes set in that Faction's territory?") + private boolean deleteEssentialsHomes = true; + + @Comment("Default Relation allows you to change the default relation for Factions.\n" + + "Example usage would be so people can't leave then make a new Faction while Raiding\n" + + " in order to be able to execute commands if the default relation is neutral.") + private String defaultRelation = "neutral"; + + @Comment("If true, disables pistons entirely within faction territory.\n" + + "Prevents flying piston machines in faction territory.") + private boolean disablePistonsInTerritory = false; + + public boolean isDisablePistonsInTerritory() { + return disablePistonsInTerritory; + } + + public boolean isDeleteEssentialsHomes() { + return deleteEssentialsHomes; + } + + public String getDefaultRelation() { + return defaultRelation; + } + + public boolean isSeparateOfflinePerms() { + return separateOfflinePerms; + } + + public boolean isAllowMultipleColeaders() { + return allowMultipleColeaders; + } + + public int getTagLengthMin() { + return tagLengthMin; + } + + public int getTagLengthMax() { + return tagLengthMax; + } + + public boolean isTagForceUpperCase() { + return tagForceUpperCase; + } + + public boolean isNewFactionsDefaultOpen() { + return newFactionsDefaultOpen; + } + + public int getFactionMemberLimit() { + return factionMemberLimit; + } + + public String getNewPlayerStartingFactionID() { + return newPlayerStartingFactionID; + } + + public double getSaveToFileEveryXMinutes() { + return saveToFileEveryXMinutes; + } + + public double getAutoLeaveAfterDaysOfInactivity() { + return autoLeaveAfterDaysOfInactivity; + } + + public double getAutoLeaveRoutineRunsEveryXMinutes() { + return autoLeaveRoutineRunsEveryXMinutes; + } + + public int getAutoLeaveRoutineMaxMillisecondsPerTick() { + return autoLeaveRoutineMaxMillisecondsPerTick; + } + + public boolean isRemovePlayerDataWhenBanned() { + return removePlayerDataWhenBanned; + } + + public boolean isAutoLeaveDeleteFPlayerData() { + return autoLeaveDeleteFPlayerData; + } + + public double getConsiderFactionsReallyOfflineAfterXMinutes() { + return considerFactionsReallyOfflineAfterXMinutes; + } + + public int getActionDeniedPainAmount() { + return actionDeniedPainAmount; + } + } + + public class EnterTitles { + private boolean enabled = true; + private int fadeIn = 10; + private int stay = 70; + private int fadeOut = 20; + private boolean alsoShowChat = false; + + public boolean isEnabled() { + return enabled; + } + + public int getFadeIn() { + return fadeIn; + } + + public int getStay() { + return stay; + } + + public int getFadeOut() { + return fadeOut; + } + + public boolean isAlsoShowChat() { + return alsoShowChat; + } + } + + private Chat chat = new Chat(); + private Homes homes = new Homes(); + @Comment("Limits factions to having a max number of each relation.\n" + + "Setting to 0 means none allowed. -1 for disabled.\n" + + "This will have no effect on default or existing relations, only when relations are changed.\n" + + "It is advised that you set the default relation to -1 so they can always go back to that.\n" + + "Otherwise Factions could be stuck with not being able to unenemy other Factions.") + private MaxRelations maxRelations = new MaxRelations(); + private PVP pvp = new PVP(); + private SpecialCase specialCase = new SpecialCase(); + private Claims claims = new Claims(); + @Comment("Do you want to limit portal creation?") + private Portals portals = new Portals(); + private Protection protection = new Protection(); + @Comment("For claimed areas where further faction-member ownership can be defined") + private OwnedArea ownedArea = new OwnedArea(); + @Comment("Displayed prefixes for different roles within a faction") + private Prefix prefixes = new Prefix(); + private LandRaidControl landRaidControl = new LandRaidControl(); + @Comment("Remaining settings not categorized") + private Other other = new Other(); + @Comment("Should we send titles when players enter Factions?") + private EnterTitles enterTitles = new EnterTitles(); + + public EnterTitles enterTitles() { + return enterTitles; + } + + public Chat chat() { + return chat; + } + + public Homes homes() { + return homes; + } + + public MaxRelations maxRelations() { + return maxRelations; + } + + public PVP pvp() { + return pvp; + } + + public SpecialCase specialCase() { + return specialCase; + } + + public Claims claims() { + return claims; + } + + public Portals portals() { + return portals; + } + + public Protection protection() { + return protection; + } + + public Other other() { + return other; + } + + public OwnedArea ownedArea() { + return ownedArea; + } + + public Prefix prefixes() { + return prefixes; + } + + public LandRaidControl landRaidControl() { + return landRaidControl; + } + } + + public class Logging { + private boolean factionCreate = true; + private boolean factionDisband = true; + private boolean factionJoin = true; + private boolean factionKick = true; + private boolean factionLeave = true; + private boolean landClaims = true; + private boolean landUnclaims = true; + private boolean moneyTransactions = true; + private boolean playerCommands = true; + + public boolean isFactionCreate() { + return factionCreate; + } + + public boolean isFactionDisband() { + return factionDisband; + } + + public boolean isFactionJoin() { + return factionJoin; + } + + public boolean isFactionKick() { + return factionKick; + } + + public boolean isFactionLeave() { + return factionLeave; + } + + public boolean isLandClaims() { + return landClaims; + } + + public boolean isLandUnclaims() { + return landUnclaims; + } + + public boolean isMoneyTransactions() { + return moneyTransactions; + } + + public boolean isPlayerCommands() { + return playerCommands; + } + } + + public class Exploits { + private boolean obsidianGenerators = true; + private boolean enderPearlClipping = true; + private boolean interactionSpam = true; + private boolean tntWaterlog = false; + private boolean liquidFlow = false; + private boolean preventDuping = true; + + public boolean isObsidianGenerators() { + return obsidianGenerators; + } + + public boolean isEnderPearlClipping() { + return enderPearlClipping; + } + + public boolean isInteractionSpam() { + return interactionSpam; + } + + public boolean isTntWaterlog() { + return tntWaterlog; + } + + public boolean isLiquidFlow() { + return liquidFlow; + } + + public boolean doPreventDuping() { + return preventDuping; + } + } + + public class Economy { + @Comment("Must be true for any economy features") + private boolean enabled = false; + private String universeAccount = ""; + private double costClaimWilderness = 30.0; + private double costClaimFromFactionBonus = 30.0; + private double overclaimRewardMultiplier = 0.0; + private double claimAdditionalMultiplier = 0.5; + private double claimRefundMultiplier = 0.7; + private double claimUnconnectedFee = 0.0; + private double costCreate = 100.0; + private double costOwner = 15.0; + private double costSethome = 30.0; + private double costDelhome = 30.0; + private double costJoin = 0.0; + private double costLeave = 0.0; + private double costKick = 0.0; + private double costInvite = 0.0; + private double costHome = 0.0; + private double costTag = 0.0; + private double costDesc = 0.0; + private double costTitle = 0.0; + private double costList = 0.0; + private double costMap = 0.0; + private double costPower = 0.0; + private double costShow = 0.0; + private double costStuck = 0.0; + private double costOpen = 0.0; + private double costAlly = 0.0; + private double costTruce = 0.0; + private double costEnemy = 0.0; + private double costNeutral = 0.0; + private double costNoBoom = 0.0; + // Calculate if enabled + private double costWarp = 0.0; + private double costSetWarp = 0.0; + private double costDelWarp = 0.0; + + @Comment("Faction banks, to pay for land claiming and other costs instead of individuals paying for them") + private boolean bankEnabled = true; + @Comment("Have to be at least moderator to withdraw or pay money to another faction") + private boolean bankMembersCanWithdraw = false; + @Comment("The faction pays for faction command costs, such as sethome") + private boolean bankFactionPaysCosts = true; + @Comment("The faction pays for land claiming costs.") + private boolean bankFactionPaysLandCosts = true; + + public boolean isEnabled() { + return enabled; + } + + public String getUniverseAccount() { + return universeAccount; + } + + public double getCostClaimWilderness() { + return costClaimWilderness; + } + + public double getCostClaimFromFactionBonus() { + return costClaimFromFactionBonus; + } + + public double getOverclaimRewardMultiplier() { + return overclaimRewardMultiplier; + } + + public double getClaimAdditionalMultiplier() { + return claimAdditionalMultiplier; + } + + public double getClaimRefundMultiplier() { + return claimRefundMultiplier; + } + + public double getClaimUnconnectedFee() { + return claimUnconnectedFee; + } + + public double getCostCreate() { + return costCreate; + } + + public double getCostOwner() { + return costOwner; + } + + public double getCostSethome() { + return costSethome; + } + + public double getCostDelhome() { + return costDelhome; + } + + public double getCostJoin() { + return costJoin; + } + + public double getCostLeave() { + return costLeave; + } + + public double getCostKick() { + return costKick; + } + + public double getCostInvite() { + return costInvite; + } + + public double getCostHome() { + return costHome; + } + + public double getCostTag() { + return costTag; + } + + public double getCostDesc() { + return costDesc; + } + + public double getCostTitle() { + return costTitle; + } + + public double getCostList() { + return costList; + } + + public double getCostMap() { + return costMap; + } + + public double getCostPower() { + return costPower; + } + + public double getCostShow() { + return costShow; + } + + public double getCostStuck() { + return costStuck; + } + + public double getCostOpen() { + return costOpen; + } + + public double getCostAlly() { + return costAlly; + } + + public double getCostTruce() { + return costTruce; + } + + public double getCostEnemy() { + return costEnemy; + } + + public double getCostNeutral() { + return costNeutral; + } + + public double getCostNoBoom() { + return costNoBoom; + } + + public double getCostWarp() { + return costWarp; + } + + public double getCostSetWarp() { + return costSetWarp; + } + + public double getCostDelWarp() { + return costDelWarp; + } + + public boolean isBankEnabled() { + return bankEnabled; + } + + public boolean isBankMembersCanWithdraw() { + return bankMembersCanWithdraw; + } + + public boolean isBankFactionPaysCosts() { + return bankFactionPaysCosts; + } + + public boolean isBankFactionPaysLandCosts() { + return bankFactionPaysLandCosts; + } + } + + public class MapSettings { + private int height = 17; + private int width = 49; + private boolean showFactionKey = true; + private boolean showNeutralFactionsOnMap = true; + private boolean showEnemyFactions = true; + private boolean showTruceFactions = true; + + public int getHeight() { + return height; + } + + public int getWidth() { + return width; + } + + public boolean isShowFactionKey() { + return showFactionKey; + } + + public boolean isShowNeutralFactionsOnMap() { + return showNeutralFactionsOnMap; + } + + public boolean isShowEnemyFactions() { + return showEnemyFactions; + } + + public boolean isShowTruceFactions() { + return showTruceFactions; + } + } + + public class Data { + public class Json { + @Comment("If true, data files will be stored without extra whitespace and linebreaks.\n" + + "This becomes less readable, but can cut storage use in half.") + private boolean efficientStorage = false; + + public boolean useEfficientStorage() { + return efficientStorage; + } + } + + @Comment("Presently, the only option is JSON.") + private String storage = "JSON"; + private Json json = new Json(); + + public Json json() { + return json; + } + } + + public class RestrictWorlds { + @Comment("If true, Factions will only function on certain worlds") + private boolean restrictWorlds = false; + @Comment("If restrictWorlds is true, this setting determines if the world list below is a whitelist or blacklist.\n" + + "True for whitelist, false for blacklist.") + private boolean whitelist = true; + private Set worldList = new HashSet<>(); + + public boolean isRestrictWorlds() { + return restrictWorlds; + } + + public boolean isWhitelist() { + return whitelist; + } + + public Set getWorldList() { + return worldList == null ? Collections.emptySet() : worldList; + } + } + + public class Scoreboard { + public class Constant { + private boolean enabled = false; + @Comment("Can use any placeholders, but does not update once set") + private String title = "Faction Status"; + @Comment("If true, show faction prefixes on nametags and in tab list if scoreboard is enabled") + private boolean prefixes = true; + private List content = new ArrayList() { + { + this.add("&6Your Faction"); + this.add("{faction}"); + this.add("&3Your Power"); + this.add("{power}"); + this.add("&aBalance"); + this.add("${balance}"); + } + }; + private boolean factionlessEnabled = false; + private List factionlessContent = new ArrayList() { + { + this.add("Make a new Faction"); + this.add("Use /f create"); + } + }; + + public boolean isEnabled() { + return enabled; + } + + public String getTitle() { + return title; + } + + public boolean isPrefixes() { + return prefixes; + } + + public List getContent() { + return content != null ? content : Collections.emptyList(); + } + + public boolean isFactionlessEnabled() { + return factionlessEnabled; + } + + public List getFactionlessContent() { + return factionlessContent != null ? content : Collections.emptyList(); + } + } + + public class Info { + @Comment("send faction change message as well when scoreboard is up?") + private boolean alsoSendChat = true; + @Comment("How long do we want scoreboards to stay") + private int expiration = 7; + private boolean enabled = false; + @Comment("Supports placeholders") + private List content = new ArrayList() { + { + this.add("&6Power"); + this.add("{power}"); + this.add("&3Members"); + this.add("{online}/{members}"); + this.add("&4Leader"); + this.add("{leader}"); + this.add("&bTerritory"); + this.add("{chunks}"); + } + }; + + public boolean isAlsoSendChat() { + return alsoSendChat; + } + + public int getExpiration() { + return expiration; + } + + public boolean isEnabled() { + return enabled; + } + + public List getContent() { + return content != null ? content : Collections.emptyList(); + } + } + + @Comment("Constant scoreboard stays around all the time, displaying status info.\n" + + "Also, if prefixes are enabled while it is enabled, will show prefixes on nametags and tab") + private Constant constant = new Constant(); + @Comment("Info scoreboard is displayed when a player walks into a new Faction's territory.\n" + + "Scoreboard disappears after seconds.") + private Info info = new Info(); + + public Constant constant() { + return constant; + } + + public Info info() { + return info; + } + } + + public class LWC { + private boolean enabled = true; + private boolean resetLocksOnUnclaim = false; + private boolean resetLocksOnCapture = false; + + public boolean isEnabled() { + return enabled; + } + + public boolean isResetLocksOnUnclaim() { + return resetLocksOnUnclaim; + } + + public boolean isResetLocksOnCapture() { + return resetLocksOnCapture; + } + } + + public class PlayerVaults { + @Comment("The %s is for the faction id") + private String vaultPrefix = "faction-%s"; + private int defaultMaxVaults = 0; + + public String getVaultPrefix() { + return vaultPrefix; + } + + public int getDefaultMaxVaults() { + return defaultMaxVaults; + } + } + + public class WorldGuard { + private boolean checking; + private boolean buildPriority; + + public boolean isChecking() { + return checking; + } + + public boolean isBuildPriority() { + return buildPriority; + } + } + + public class WorldBorder { + @Comment("WorldBorder support\n" + + "This is for Minecraft's built-in command. To get your current border: /minecraft:worldborder get\n" + + "A buffer of 0 means faction claims can go right up to the border of the world.\n" + + "The buffer is in chunks, so 1 as a buffer means an entire chunk of buffer between\n" + + "the border of the world and what can be claimed to factions") + private int buffer = 0; + + public int getBuffer() { + return buffer; + } + } + + @Comment("The command base (by default f, making the command /f)") + private List commandBase = new ArrayList() { + { + this.add("f"); + } + }; + + @Comment("FactionsUUID by drtshock\n" + + "Support and documentation https://factions.support\n" + + "Updates https://www.spigotmc.org/resources/factionsuuid.1035/\n" + + "\n" + + "Made with love <3") + private AVeryFriendlyFactionsConfig aVeryFriendlyFactionsConfig = new AVeryFriendlyFactionsConfig(); + + @Comment("Colors for relationships and default factions") + private Colors colors = new Colors(); + private Commands commands = new Commands(); + private Factions factions = new Factions(); + @Comment("What should be logged?") + private Logging logging = new Logging(); + @Comment("Controls certain exploit preventions") + private Exploits exploits = new Exploits(); + @Comment("Economy support requires Vault and a compatible economy plugin") + private Economy economy = new Economy(); + @Comment("Control for the default settings of /f map") + private MapSettings map = new MapSettings(); + @Comment("Data storage settings") + private Data data = new Data(); + private RestrictWorlds restrictWorlds = new RestrictWorlds(); + private Scoreboard scoreboard = new Scoreboard(); + @Comment("LWC integration\n" + + "This support targets the modern fork of LWC, called LWC Extended.\n" + + "You can find it here: https://www.spigotmc.org/resources/lwc-extended.69551/\n" + + "Note: Modern LWC is no longer supported, and its former maintainer now runs LWC Extended") + private LWC lwc = new LWC(); + @Comment("PlayerVaults faction vault settings.\n" + + "Enable faction-owned vaults!\n" + + "https://www.spigotmc.org/resources/playervaultsx.51204/") + private PlayerVaults playerVaults = new PlayerVaults(); + @Comment("WorldGuard settings") + private WorldGuard worldGuard = new WorldGuard(); + private WorldBorder worldBorder = new WorldBorder(); + + public List getCommandBase() { + return commandBase == null ? (commandBase = Collections.singletonList("f")) : commandBase; + } + + public Colors colors() { + return colors; + } + + public Commands commands() { + return commands; + } + + public Factions factions() { + return factions; + } + + public Logging logging() { + return logging; + } + + public Exploits exploits() { + return exploits; + } + + public Economy economy() { + return economy; + } + + public MapSettings map() { + return map; + } + + public RestrictWorlds restrictWorlds() { + return restrictWorlds; + } + + public Scoreboard scoreboard() { + return scoreboard; + } + + public PlayerVaults playerVaults() { + return playerVaults; + } + + public WorldGuard worldGuard() { + return worldGuard; + } + + public WorldBorder worldBorder() { + return worldBorder; + } + + public Data data() { + return data; + } + + public void update(OldMainConfigV1 oldConf, FileConfiguration o) { + factions.other.allowMultipleColeaders = oldConf.factions.allowMultipleColeaders; + factions.other.tagLengthMin = oldConf.factions.tagLengthMin; + factions.other.tagLengthMax = oldConf.factions.tagLengthMax; + factions.other.tagForceUpperCase = oldConf.factions.tagForceUpperCase; + factions.other.newFactionsDefaultOpen = oldConf.factions.newFactionsDefaultOpen; + factions.other.factionMemberLimit = oldConf.factions.factionMemberLimit; + factions.other.newPlayerStartingFactionID = oldConf.factions.newPlayerStartingFactionID; + factions.other.saveToFileEveryXMinutes = oldConf.factions.saveToFileEveryXMinutes; + factions.other.autoLeaveAfterDaysOfInactivity = oldConf.factions.autoLeaveAfterDaysOfInactivity; + factions.other.autoLeaveRoutineRunsEveryXMinutes = oldConf.factions.autoLeaveRoutineRunsEveryXMinutes; + factions.other.autoLeaveRoutineMaxMillisecondsPerTick = oldConf.factions.autoLeaveRoutineMaxMillisecondsPerTick; + factions.other.removePlayerDataWhenBanned = oldConf.factions.removePlayerDataWhenBanned; + factions.other.autoLeaveDeleteFPlayerData = oldConf.factions.autoLeaveDeleteFPlayerData; + factions.other.considerFactionsReallyOfflineAfterXMinutes = oldConf.factions.considerFactionsReallyOfflineAfterXMinutes; + factions.other.actionDeniedPainAmount = oldConf.factions.actionDeniedPainAmount; + factions.other.separateOfflinePerms = oldConf.factions.separateOfflinePerms; + + aVeryFriendlyFactionsConfig.debug = o.getBoolean("debug", false); + + commands.fly.particles.amount = o.getInt("f-fly.trails.amount", 20); + commands.fly.particles.spawnRate = o.getDouble("f-fly.trails.spawn-rate", 0.2); + commands.fly.particles.speed = o.getDouble("f-fly.trails.speed", 0.02); + commands.fly.enable = o.getBoolean("f-fly.enable", true); + commands.fly.delay = o.getInt("warmups.f-fly", 0); + commands.fly.fallDamageCooldown = o.getInt("f-fly.falldamage-cooldown", 3); + commands.fly.enemyRadius = o.getInt("f-fly.enemy-radius", 7); + commands.fly.radiusCheck = o.getInt("f-fly.radius-check", 1); + commands.fly.disableOnGenericDamage = o.getBoolean("f-fly.disable-generic-damage", false); + + ConfigurationSection help = o.getConfigurationSection("help"); + Map> helpMap = new HashMap<>(); + for (String key : help.getKeys(false)) { + List list = help.getStringList(key); + if (list != null) { + helpMap.put(key, help.getStringList(key)); + } + } + if (!helpMap.isEmpty()) { + commands.help.entries = helpMap; + } + commands.help.useOldHelp = o.getBoolean("use-old-help", true); + + commands.home.delay = o.getInt("warmups.f-home", 0); + + commands.list.header = o.getString("list.header", "&e&m----------&r&e[ &2Faction List &9{pagenumber}&e/&9{pagecount} &e]&m----------"); + commands.list.factionlessEntry = o.getString("list.factionless", "Factionless {factionless} online"); + commands.list.entry = o.getString("list.entry", "{faction-relation-color}{faction} {online} / {members} online, Land / Power / Maxpower: {chunks}/{power}/{maxPower}"); + + commands.map.cooldown = o.getInt("findfactionsexploit", 700); + + commands.near.radius = o.getInt("f-near.radius", 20); + + commands.seeChunk.particleName = o.getString("see-chunk.particle", "REDSTONE"); + commands.seeChunk.particles = o.getBoolean("see-chunk.particles", true); + commands.seeChunk.particleUpdateTime = o.getDouble("see-chunk.particle-update-time", 0.75); + commands.seeChunk.relationalColor = o.getBoolean("see-chunk.relational-color", true); + + commands.show.exempt = o.getStringList("show-exempt"); + if (commands.show.exempt == null) { + commands.show.exempt = Arrays.asList("Put_faction_tag_here"); + } + commands.show.minimal = o.getBoolean("minimal-show", false); + if (!o.getStringList("show").isEmpty()) { + commands.show.format = o.getStringList("show"); + } + + commands.stuck.delay = o.getInt("hcf.stuck.delay", 30); + commands.stuck.radius = o.getInt("hcf.stuck.radius", 10); + + commands.warp.delay = o.getInt("warmups.f-warp", 0); + commands.warp.maxWarps = o.getInt("max-warps", 5); + + if (!o.getStringList("tooltips.list").isEmpty()) { + commands.toolTips.faction = o.getStringList("tooltips.list"); + } + if (!o.getStringList("tooltips.show").isEmpty()) { + commands.toolTips.player = o.getStringList("tooltips.show"); + } + + factions.landRaidControl.power.raidability = o.getBoolean("hcf.raidable", false); + factions.landRaidControl.power.powerFreeze = o.getInt("hcf.powerfreeze", 0); + + factions.maxRelations.enabled = o.getBoolean("max-relations.enabled", false); + factions.maxRelations.ally = o.getInt("max-relations.ally", 10); + factions.maxRelations.truce = o.getInt("max-relations.truce", 10); + factions.maxRelations.neutral = o.getInt("max-relations.neutral", -1); + factions.maxRelations.enemy = o.getInt("max-relations.enemy", 10); + + factions.portals.limit = o.getBoolean("portals.limit", false); + factions.portals.minimumRelation = o.getString("portals.minimum-relation", "MEMBER"); + + factions.claims.bufferZone = o.getInt("hcf.buffer-zone", 0); + factions.claims.allowOverClaim = o.getBoolean("hcf.allow-overclaim", true); + + factions.other.deleteEssentialsHomes = o.getBoolean("delete-ess-homes", true); + factions.other.defaultRelation = o.getString("default-relation", "neutral"); + factions.other.disablePistonsInTerritory = o.getBoolean("disable-pistons-in-territory", false); + + factions.enterTitles.enabled = o.getBoolean("enter-titles.enabled", true); + factions.enterTitles.fadeIn = o.getInt("enter-titles.fade-in", 10); + factions.enterTitles.fadeOut = o.getInt("enter-titles.fade-out", 20); + factions.enterTitles.stay = o.getInt("enter-titles.stay", 70); + factions.enterTitles.alsoShowChat = o.getBoolean("enter-titles.also-show-chat", false); + + boolean warpCostEnabled = economy.enabled && o.getBoolean("warp-cost.enabled", false); + economy.costWarp = warpCostEnabled ? o.getInt("warp-cost.warp", 5) : 0; + economy.costSetWarp = warpCostEnabled ? o.getInt("warp-cost.setwarp", 5) : 0; + economy.costDelWarp = warpCostEnabled ? o.getInt("warp-cost.delwarp", 5) : 0; + + scoreboard.constant.enabled = o.getBoolean("scoreboard.default-enabled", false); + scoreboard.constant.title = o.getString("scoreboard.default-title", "Faction Status"); + scoreboard.constant.prefixes = o.getBoolean("scoreboard.default-prefixes", true); + if (!o.getStringList("scoreboard.default").isEmpty()) { + scoreboard.constant.content = o.getStringList("scoreboard.default"); + } + scoreboard.constant.factionlessEnabled = o.getBoolean("scoreboard.factionless-enabled", false); + if (!o.getStringList("scoreboard.factionless").isEmpty()) { + scoreboard.constant.factionlessContent = o.getStringList("scoreboard.factionless"); + } + + scoreboard.info.enabled = o.getBoolean("scoreboard.finfo-enabled", false); + scoreboard.info.alsoSendChat = o.getBoolean("scoreboard.also-sent-chat", true); + scoreboard.info.expiration = o.getInt("scoreboard.expiration"); + if (!o.getStringList("scoreboard.finfo").isEmpty()) { + scoreboard.info.content = o.getStringList("scoreboard.finfo"); + } + + lwc.enabled = o.getBoolean("lwc.integration", false); + lwc.resetLocksOnCapture = o.getBoolean("lwc.reset-locks-unclaim"); + lwc.resetLocksOnUnclaim = o.getBoolean("lwc.reset-locks-capture"); + + worldBorder.buffer = o.getInt("world-border.buffer", 0); + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/data/MemoryBoard.java b/Factions/src/main/java/com/massivecraft/factions/data/MemoryBoard.java new file mode 100644 index 0000000..ec5ec4d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/MemoryBoard.java @@ -0,0 +1,373 @@ +package com.massivecraft.factions.data; + +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Multimap; +import com.massivecraft.factions.*; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.util.AsciiCompass; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.TextUtil; +import mkremins.fanciful.FancyMessage; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; + + +public abstract class MemoryBoard extends Board { + + public class MemoryBoardMap extends ConcurrentHashMap { + private static final long serialVersionUID = -6689617828610585368L; + + Multimap factionToLandMap = HashMultimap.create(); + + @Override + public String put(FLocation floc, String factionId) { + String previousValue = super.put(floc, factionId); + if (previousValue != null) { + factionToLandMap.remove(previousValue, floc); + } + + factionToLandMap.put(factionId, floc); + return previousValue; + } + + @Override + public String remove(Object key) { + String result = super.remove(key); + if (result != null) { + FLocation floc = (FLocation) key; + factionToLandMap.remove(result, floc); + } + + return result; + } + + @Override + public void clear() { + super.clear(); + factionToLandMap.clear(); + } + + public int getOwnedLandCount(String factionId) { + return factionToLandMap.get(factionId).size(); + } + + public void removeFaction(String factionId) { + Collection fLocations = factionToLandMap.removeAll(factionId); + for (FPlayer fPlayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fLocations.contains(fPlayer.getLastStoodAt())) { + if (FactionsPlugin.getInstance().conf().commands().fly().isEnable() && !fPlayer.isAdminBypassing() && fPlayer.isFlying()) { + //fPlayer.setFlying(false); + } + if (fPlayer.isWarmingUp()) { + fPlayer.clearWarmup(); + fPlayer.msg(TL.WARMUPS_CANCELLED); + } + } + } + for (FLocation floc : fLocations) { + super.remove(floc); + } + } + } + + + private final char[] mapKeyChrs = "\\/#$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz?".toCharArray(); + + public MemoryBoardMap flocationIds = new MemoryBoardMap(); + + //----------------------------------------------// + // Get and Set + //----------------------------------------------// + public String getIdAt(FLocation flocation) { + if (!flocationIds.containsKey(flocation)) { + return "0"; + } + + return flocationIds.get(flocation); + } + + public Faction getFactionAt(FLocation flocation) { + return Factions.getInstance().getFactionById(getIdAt(flocation)); + } + + public void setIdAt(String id, FLocation flocation) { + clearOwnershipAt(flocation); + + if (id.equals("0")) { + removeAt(flocation); + } + + flocationIds.put(flocation, id); + } + + public void setFactionAt(Faction faction, FLocation flocation) { + setIdAt(faction.getId(), flocation); + } + + public void removeAt(FLocation flocation) { + Faction faction = getFactionAt(flocation); + faction.getWarps().values().removeIf(lazyLocation -> flocation.isInChunk(lazyLocation.getLocation())); + if(Bukkit.isPrimaryThread()){ + for (Entity entity : flocation.getChunk().getEntities()) { + if (entity instanceof Player) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer((Player) entity); + if (!fPlayer.isAdminBypassing() && fPlayer.isFlying()) { + //fPlayer.setFlying(false); + } + if (fPlayer.isWarmingUp()) { + fPlayer.clearWarmup(); + fPlayer.msg(TL.WARMUPS_CANCELLED); + } + } + } + }else{ + new BukkitRunnable(){ + @Override + public void run(){ + for (Entity entity : flocation.getChunk().getEntities()) { + if (entity instanceof Player) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer((Player) entity); + if (!fPlayer.isAdminBypassing() && fPlayer.isFlying()) { + //fPlayer.setFlying(false); + } + if (fPlayer.isWarmingUp()) { + fPlayer.clearWarmup(); + fPlayer.msg(TL.WARMUPS_CANCELLED); + } + } + } + } + }.runTask(FactionsPlugin.getInstance()); + } + clearOwnershipAt(flocation); + flocationIds.remove(flocation); + } + + public Set getAllClaims(String factionId) { + Set locs = new HashSet<>(); + for (Entry entry : flocationIds.entrySet()) { + if (entry.getValue().equals(factionId)) { + locs.add(entry.getKey()); + } + } + return locs; + } + + + public Set getAllClaims(Faction faction) { + return getAllClaims(faction.getId()); + } + + // not to be confused with claims, ownership referring to further member-specific ownership of a claim + public void clearOwnershipAt(FLocation flocation) { + Faction faction = getFactionAt(flocation); + if (faction != null && faction.isNormal()) { + faction.clearClaimOwnership(flocation); + } + } + + public void unclaimAll(String factionId) { + Faction faction = Factions.getInstance().getFactionById(factionId); + if (faction != null && faction.isNormal()) { + faction.clearAllClaimOwnership(); + faction.clearWarps(); + } + clean(factionId); + } + + public void unclaimAllInWorld(String factionId, World world) { + for (FLocation loc : getAllClaims(factionId)) { + if (loc.getWorldName().equals(world.getName())) { + removeAt(loc); + } + } + } + + public void clean(String factionId) { + flocationIds.removeFaction(factionId); + } + + // Is this coord NOT completely surrounded by coords claimed by the same faction? + // Simpler: Is there any nearby coord with a faction other than the faction here? + public boolean isBorderLocation(FLocation flocation) { + Faction faction = getFactionAt(flocation); + FLocation a = flocation.getRelative(1, 0); + FLocation b = flocation.getRelative(-1, 0); + FLocation c = flocation.getRelative(0, 1); + FLocation d = flocation.getRelative(0, -1); + return faction != getFactionAt(a) || faction != getFactionAt(b) || faction != getFactionAt(c) || faction != getFactionAt(d); + } + + // Is this coord connected to any coord claimed by the specified faction? + public boolean isConnectedLocation(FLocation flocation, Faction faction) { + FLocation a = flocation.getRelative(1, 0); + FLocation b = flocation.getRelative(-1, 0); + FLocation c = flocation.getRelative(0, 1); + FLocation d = flocation.getRelative(0, -1); + return faction == getFactionAt(a) || faction == getFactionAt(b) || faction == getFactionAt(c) || faction == getFactionAt(d); + } + + /** + * Checks if there is another faction within a given radius other than Wilderness. Used for HCF feature that + * requires a 'buffer' between factions. + * + * @param flocation - center location. + * @param faction - faction checking for. + * @param radius - chunk radius to check. + * @return true if another Faction is within the radius, otherwise false. + */ + public boolean hasFactionWithin(FLocation flocation, Faction faction, int radius) { + for (int x = -radius; x <= radius; x++) { + for (int z = -radius; z <= radius; z++) { + if (x == 0 && z == 0) { + continue; + } + + FLocation relative = flocation.getRelative(x, z); + Faction other = getFactionAt(relative); + + if (other.isNormal() && other != faction) { + return true; + } + } + } + return false; + } + + + //----------------------------------------------// + // Cleaner. Remove orphaned foreign keys + //----------------------------------------------// + + public void clean() { + Iterator> iter = flocationIds.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = iter.next(); + if (!Factions.getInstance().isValidFactionId(entry.getValue())) { + FactionsPlugin.getInstance().log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); + iter.remove(); + } + } + } + + //----------------------------------------------// + // Coord count + //----------------------------------------------// + + public int getFactionCoordCount(String factionId) { + return flocationIds.getOwnedLandCount(factionId); + } + + public int getFactionCoordCount(Faction faction) { + return getFactionCoordCount(faction.getId()); + } + + public int getFactionCoordCountInWorld(Faction faction, String worldName) { + String factionId = faction.getId(); + int ret = 0; + for (Entry entry : flocationIds.entrySet()) { + if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) { + ret += 1; + } + } + return ret; + } + + //----------------------------------------------// + // Map generation + //----------------------------------------------// + + /** + * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction + * of decreasing z + */ + public ArrayList getMap(FPlayer fplayer, FLocation flocation, double inDegrees) { + Faction faction = fplayer.getFaction(); + ArrayList ret = new ArrayList<>(); + Faction factionLoc = getFactionAt(flocation); + ret.add(new FancyMessage(FactionsPlugin.getInstance().txt().titleize(TextUtil.parseColor("&8(&a" + flocation.getCoordString() + "&8) &a") + factionLoc.getTag(fplayer)))); + + // Get the compass + ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, FactionsPlugin.getInstance().txt().parse("")); + + int halfWidth = FactionsPlugin.getInstance().conf().map().getWidth() / 2; + // Use player's value for height + int halfHeight = fplayer.getMapHeight() / 2; + FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); + int width = halfWidth * 2 + 1; + int height = halfHeight * 2 + 1; + + if (FactionsPlugin.getInstance().conf().map().isShowFactionKey()) { + height--; + } + + Map fList = new HashMap<>(); + int chrIdx = 0; + + // For each row + for (int dz = 0; dz < height; dz++) { + // Draw and add that row + FancyMessage row = new FancyMessage(""); + + if (dz < 3) { + row.then(asciiCompass.get(dz)); + } + for (int dx = (dz < 3 ? 6 : 3); dx < width; dx++) { + if (dx == halfWidth && dz == halfHeight) { + row.then("+").color(ChatColor.AQUA); + } else { + final int buffer = FactionsPlugin.getInstance().conf().worldBorder().getBuffer(); + FLocation flocationHere = topLeft.getRelative(dx, dz); + Faction factionHere = getFactionAt(flocationHere); + Relation relation = fplayer.getRelationTo(factionHere); + + + if (flocationHere.isOutsideWorldBorder(buffer)){ + row.then("-").color(ChatColor.BLACK); + } else if (factionHere.isWilderness()) { + row.then("-").color(FactionsPlugin.getInstance().conf().colors().factions().getWilderness()); + } else if (factionHere.isSafeZone()) { + row.then("+").color(FactionsPlugin.getInstance().conf().colors().factions().getSafezone()); + } else if (factionHere.isWarZone()) { + row.then("+").color(FactionsPlugin.getInstance().conf().colors().factions().getWarzone()); + } else if (factionHere == faction || factionHere == factionLoc || relation.isAtLeast(Relation.ALLY) || + (FactionsPlugin.getInstance().conf().map().isShowNeutralFactionsOnMap() && relation.equals(Relation.NEUTRAL)) || + (FactionsPlugin.getInstance().conf().map().isShowEnemyFactions() && relation.equals(Relation.ENEMY)) || + FactionsPlugin.getInstance().conf().map().isShowTruceFactions() && relation.equals(Relation.TRUCE)) { + if (!fList.containsKey(factionHere.getTag())) { + fList.put(factionHere.getTag(), this.mapKeyChrs[Math.min(chrIdx++, this.mapKeyChrs.length - 1)]); + } + + char tag = fList.get(factionHere.getTag()); + row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)); + } else { + row.then("-").color(ChatColor.GRAY); + } + } + } + ret.add(row); + } + + // Add the faction key + if (FactionsPlugin.getInstance().conf().map().isShowFactionKey()) { + FancyMessage fRow = new FancyMessage(""); + for (String key : fList.keySet()) { + final Relation relation = fplayer.getRelationTo(Factions.getInstance().getByTag(key)); + fRow.then(String.format("%s: %s ", fList.get(key), key)).color(relation.getColor()); + } + ret.add(fRow); + } + + return ret; + } + + public abstract void convertFrom(MemoryBoard old); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/MemoryFPlayer.java b/Factions/src/main/java/com/massivecraft/factions/data/MemoryFPlayer.java new file mode 100644 index 0000000..6b22262 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/MemoryFPlayer.java @@ -0,0 +1,1348 @@ +package com.massivecraft.factions.data; + +import com.massivecraft.factions.*; +import com.massivecraft.factions.event.FPlayerLeaveEvent; +import com.massivecraft.factions.event.FactionAutoDisbandEvent; +import com.massivecraft.factions.event.LandClaimEvent; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.iface.RelationParticipator; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.integration.Essentials; +import com.massivecraft.factions.landraidcontrol.DTRControl; +import com.massivecraft.factions.landraidcontrol.PowerControl; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.scoreboards.FScoreboard; +import com.massivecraft.factions.scoreboards.sidebar.FInfoSidebar; +import com.massivecraft.factions.struct.ChatMode; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.tag.Tag; +import com.massivecraft.factions.util.*; +import mkremins.fanciful.FancyMessage; +import net.crankedpvp.toggles.struct.Toggle; +import org.bukkit.*; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.metadata.MetadataValue; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + + +/** + * Logged in players always have exactly one FPlayer instance. Logged out players may or may not have an FPlayer + * instance. They will always have one if they are part of a faction. This is because only players with a faction are + * saved to disk (in order to not waste disk space). + *

+ * The FPlayer is linked to a minecraft player using the player name. + *

+ * The same instance is always returned for the same player. This means you can use the == operator. No .equals method + * necessary. + */ + +public abstract class MemoryFPlayer implements FPlayer { + + protected String factionId; + protected String factionRosterId; + protected Role role; + protected String title; + protected double power; + protected double powerBoost; + protected long lastPowerUpdateTime; + protected long lastLoginTime; + protected ChatMode chatMode; + protected boolean ignoreAllianceChat = false; + protected String id; + protected String name; + protected boolean monitorJoins; + protected boolean spyingChat = false; + protected boolean showScoreboard = true; + protected WarmUpUtil.Warmup warmup; + protected int warmupTask; + protected boolean isAdminBypassing = false; + protected int kills, deaths; + protected boolean willAutoLeave = true; + protected int mapHeight = 8; // default to old value + protected boolean isAutoFlying = false; + protected boolean flyTrailsState = false; + protected String flyTrailsEffect = null; + protected boolean stealth = false; + protected boolean inspect = false; + + protected boolean seeingChunk = false; + + protected transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked? + protected transient boolean mapAutoUpdating; + protected transient Faction autoClaimFor; + protected transient boolean autoSafeZoneEnabled; + protected transient boolean autoWarZoneEnabled; + protected transient boolean loginPvpDisabled; + protected transient long lastFrostwalkerMessage; + protected transient boolean shouldTakeFallDamage = true; + protected transient OfflinePlayer offlinePlayer; + + public void login() { + this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); + this.deaths = getPlayer().getStatistic(Statistic.DEATHS); + } + + public void logout() { + this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); + this.deaths = getPlayer().getStatistic(Statistic.DEATHS); + } + + public Faction getFaction() { + if (this.factionId == null) { + this.factionId = "0"; + } + return Factions.getInstance().getFactionById(this.factionId); + } + + public String getFactionId() { + return this.factionId; + } + + public String getRosterFactionId() { + return this.factionRosterId; + } + + public boolean hasFaction() { + return !factionId.equals("0"); + } + + public boolean isOnRoster() { + return factionRosterId != null && !factionRosterId.equals("0"); + } + + public void setFaction(Faction faction) { + Faction oldFaction = this.getFaction(); + if (oldFaction != null) { + oldFaction.removeFPlayer(this); + } + faction.addFPlayer(this); + this.factionId = faction.getId(); + } + + public void setMonitorJoins(boolean monitor) { + this.monitorJoins = monitor; + } + + public boolean isMonitoringJoins() { + return this.monitorJoins; + } + + public Role getRole() { + // Hack to fix null roles.. + if (role == null) { + this.role = Role.NORMAL; + } + + return this.role; + } + + public void setRole(Role role) { + Faction faction = this.getFaction(); + + if (faction != null) { + if (role == Role.ADMIN || this.role == Role.ADMIN) { + this.role = role; + + ((MemoryFaction) faction).recalcFPlayerAdmin(); + return; + } + } + this.role = role; + } + + public double getPowerBoost() { + return this.powerBoost; + } + + public void setPowerBoost(double powerBoost) { + this.powerBoost = powerBoost; + } + + public boolean willAutoLeave() { + return this.willAutoLeave; + } + + public void setAutoLeave(boolean willLeave) { + this.willAutoLeave = willLeave; + FactionsPlugin.getInstance().debug(name + " set autoLeave to " + willLeave); + } + + public long getLastFrostwalkerMessage() { + return this.lastFrostwalkerMessage; + } + + public void setLastFrostwalkerMessage() { + this.lastFrostwalkerMessage = System.currentTimeMillis(); + } + + public Faction getAutoClaimFor() { + return autoClaimFor; + } + + public void setAutoClaimFor(Faction faction) { + this.autoClaimFor = faction; + if (this.autoClaimFor != null) { + // TODO: merge these into same autoclaim + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + } + } + + public boolean isAutoSafeClaimEnabled() { + return autoSafeZoneEnabled; + } + + public void setIsAutoSafeClaimEnabled(boolean enabled) { + this.autoSafeZoneEnabled = enabled; + if (enabled) { + this.autoClaimFor = null; + this.autoWarZoneEnabled = false; + } + } + + public boolean isAutoWarClaimEnabled() { + return autoWarZoneEnabled; + } + + public void setIsAutoWarClaimEnabled(boolean enabled) { + this.autoWarZoneEnabled = enabled; + if (enabled) { + this.autoClaimFor = null; + this.autoSafeZoneEnabled = false; + } + } + + public boolean isAdminBypassing() { + return this.isAdminBypassing; + } + + public boolean isVanished() { + Player player = this.getPlayer(); + if (Essentials.isVanished(player)) { + return true; + } + if (player != null) { + for (MetadataValue metadataValue : player.getMetadata("vanished")) { + if (metadataValue != null && metadataValue.asBoolean()) { + return true; + } + } + } + return false; + } + + public void setIsAdminBypassing(boolean val) { + this.isAdminBypassing = val; + } + + public void setChatMode(ChatMode chatMode) { + this.chatMode = chatMode; + } + + public ChatMode getChatMode() { + if (this.chatMode == null || this.factionId.equals("0") || !FactionsPlugin.getInstance().conf().factions().chat().isFactionOnlyChat()) { + this.chatMode = ChatMode.PUBLIC; + } + return chatMode; + } + + public void setIgnoreAllianceChat(boolean ignore) { + this.ignoreAllianceChat = ignore; + } + + public boolean isIgnoreAllianceChat() { + return ignoreAllianceChat; + } + + public void setSpyingChat(boolean chatSpying) { + this.spyingChat = chatSpying; + } + + public boolean isSpyingChat() { + return spyingChat; + } + + public boolean isStealth() { + return this.stealth; + } + + public void setStealth(boolean stealth) { + this.stealth = stealth; + } + + public boolean isInspectMode() { + return this.inspect; + } + + public void setInspectMode(boolean status) { + this.inspect = status; + } + + // FIELD: account + public String getAccountId() { + return this.getId(); + } + + public OfflinePlayer getOfflinePlayer() { + if (this.offlinePlayer == null) { + this.offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(getId())); + } + return this.offlinePlayer; + } + + public void setOfflinePlayer(Player player) { + this.offlinePlayer = player; + } + + public MemoryFPlayer() { + } + + public MemoryFPlayer(String id) { + this.id = id; + this.resetFactionData(false); + this.power = FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getPlayerStarting(); + this.lastPowerUpdateTime = System.currentTimeMillis(); + this.lastLoginTime = System.currentTimeMillis(); + this.mapAutoUpdating = false; + this.autoClaimFor = null; + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + this.loginPvpDisabled = FactionsPlugin.getInstance().conf().factions().pvp().getNoPVPDamageToOthersForXSecondsAfterLogin() > 0; + this.powerBoost = 0.0; + this.kills = 0; + this.deaths = 0; + this.mapHeight = FactionsPlugin.getInstance().conf().map().getHeight(); + this.stealth = false; + + if (!FactionsPlugin.getInstance().conf().factions().other().getNewPlayerStartingFactionID().equals("0") && Factions.getInstance().isValidFactionId(FactionsPlugin.getInstance().conf().factions().other().getNewPlayerStartingFactionID())) { + this.factionId = FactionsPlugin.getInstance().conf().factions().other().getNewPlayerStartingFactionID(); + + this.factionRosterId = factionId; + } + } + + public MemoryFPlayer(MemoryFPlayer other) { + this.factionId = other.factionId; + this.factionRosterId = other.factionRosterId; + this.id = other.id; + this.power = other.power; + this.lastLoginTime = other.lastLoginTime; + this.mapAutoUpdating = other.mapAutoUpdating; + this.autoClaimFor = other.autoClaimFor; + this.autoSafeZoneEnabled = other.autoSafeZoneEnabled; + this.autoWarZoneEnabled = other.autoWarZoneEnabled; + this.loginPvpDisabled = other.loginPvpDisabled; + this.powerBoost = other.powerBoost; + this.role = other.role; + this.title = other.title; + this.chatMode = other.chatMode; + this.spyingChat = other.spyingChat; + this.lastStoodAt = other.lastStoodAt; + this.isAdminBypassing = other.isAdminBypassing; + this.kills = other.kills; + this.deaths = other.deaths; + this.mapHeight = other.mapHeight; + this.stealth = other.stealth; + } + + public void resetFactionData(boolean doSpoutUpdate) { + // clean up any territory ownership in old faction, if there is one + if (factionId != null && Factions.getInstance().isValidFactionId(this.getFactionId())) { + Faction currentFaction = this.getFaction(); + currentFaction.removeFPlayer(this); + if (currentFaction.isNormal()) { + currentFaction.clearClaimOwnership(this); + } + } + + if (factionRosterId != null && Factions.getInstance().isValidFactionId(this.getRosterFactionId())) { + Faction currentFaction = Factions.getInstance().getFactionById(factionRosterId); + + if (currentFaction.isNormal()) { + currentFaction.clearClaimOwnership(this); + } + } + + this.factionId = "0"; // The default neutral faction + this.factionRosterId = "0"; + this.chatMode = ChatMode.PUBLIC; + this.role = Role.NORMAL; + this.title = ""; + this.autoClaimFor = null; + } + + public boolean attemptRotateIn() { + if (!isOnRoster()) return false; + + Faction faction = Factions.getInstance().getFactionById(factionRosterId); + + if (faction == null) return false; + + Set fplayersOffline = faction.getFPlayersWhereOnline(false); + + fplayersOffline.remove(this); + + fplayersOffline = fplayersOffline.stream().filter(z -> z.getRole() != Role.ADMIN).collect(Collectors.toSet()); + + if (fplayersOffline.size() == 0) { + this.msg(TL.COMMAND_ROSTER_ROTATE_FULL); + return false; + } + + boolean rotated = false; + for (FPlayer fPlayer : fplayersOffline) { + if (((MemoryFPlayer) fPlayer).rotateOut()) { + rotated = true; + break; + } + } + + if (!rotated) { + this.msg(TL.COMMAND_ROSTER_ROTATE_FULL); + return false; + } + + faction.addFPlayer(this); + + this.factionId = factionRosterId; + + for (FPlayer fPlayer : faction.getFPlayersWhereOnline(true)) { + fPlayer.msg(TL.COMMAND_ROSTER_ROTATE_SUCCESS, this.describeTo(fPlayer), faction.describeTo(fPlayer)); + } + + this.autoClaimFor = null; + return true; + } + + public boolean rotateOut() { + if (!isOnRoster()) return false; + + Faction faction = getFaction(); + for (FPlayer fPlayer : faction.getFPlayersWhereOnline(true)) { + fPlayer.msg(TL.COMMAND_ROSTER_ROTATE_SUCCESS, this.describeTo(fPlayer), faction.describeTo(fPlayer)); + } + + faction.removeFPlayer(this); + + this.factionId = "0"; + + this.chatMode = ChatMode.PUBLIC; + + this.autoClaimFor = null; + + //this.setFlying(false, false); + return true; + } + + public void resetFactionData() { + this.resetFactionData(true); + } + + // -------------------------------------------- // + // Getters And Setters + // -------------------------------------------- // + + + public long getLastLoginTime() { + return lastLoginTime; + } + + public void setLastLoginTime(long lastLoginTime) { + this.lastLoginTime = lastLoginTime; + if (FactionsPlugin.getInstance().conf().factions().pvp().getNoPVPDamageToOthersForXSecondsAfterLogin() > 0) { + this.loginPvpDisabled = true; + } + } + + public boolean isMapAutoUpdating() { + return mapAutoUpdating; + } + + public void setMapAutoUpdating(boolean mapAutoUpdating) { + this.mapAutoUpdating = mapAutoUpdating; + } + + public boolean hasLoginPvpDisabled() { + if (!loginPvpDisabled) { + return false; + } + if (this.lastLoginTime + (FactionsPlugin.getInstance().conf().factions().pvp().getNoPVPDamageToOthersForXSecondsAfterLogin() * 1000L) < System.currentTimeMillis()) { + this.loginPvpDisabled = false; + return false; + } + return true; + } + + public FLocation getLastStoodAt() { + return this.lastStoodAt; + } + + public void setLastStoodAt(FLocation flocation) { + this.lastStoodAt = flocation; + } + + //----------------------------------------------// + // Title, Name, Faction Tag and Chat + //----------------------------------------------// + + // Base: + + public String getTitle() { + return this.hasFaction() ? title : TL.NOFACTION_PREFIX.toString(); + } + + public void setTitle(CommandSender sender, String title) { + // Check if the setter has it. + if (sender.hasPermission(Permission.TITLE_COLOR.node)) { + title = ChatColor.translateAlternateColorCodes('&', title); + } + + this.title = title; + } + + public String getName() { + if (this.name == null) { + // Older versions of FactionsUUID don't save the name, + // so `name` will be null the first time it's retrieved + // after updating + OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(getId())); + this.name = offline.getName() != null ? offline.getName() : getId(); + } + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTag() { + return this.hasFaction() ? this.getFaction().getTag() : ""; + } + + // Base concatenations: + + public String getNameAndSomething(String something) { + String ret = this.role.getPrefix(); + if (something != null && something.length() > 0) { + ret += something + " "; + } + ret += this.getName(); + return ret; + } + + public String getNameAndTitle() { + return this.getNameAndSomething(this.getTitle()); + } + + public String getNameAndTag() { + return this.getNameAndSomething(this.getTag()); + } + + // Colored concatenations: + // These are used in information messages + + public String getNameAndTitle(Faction faction) { + return this.getColorTo(faction) + this.getNameAndTitle(); + } + + public String getNameAndTitle(MemoryFPlayer fplayer) { + return this.getColorTo(fplayer) + this.getNameAndTitle(); + } + + // Chat Tag: + // These are injected into the format of global chat messages. + + public String getChatTag() { + return this.hasFaction() ? String.format(FactionsPlugin.getInstance().conf().factions().chat().getTagFormat(), this.getRole().getPrefix() + this.getTag()) : TL.NOFACTION_PREFIX.toString(); + } + + // Colored Chat Tag + public String getChatTag(Faction faction) { + return this.hasFaction() ? this.getRelationTo(faction).getColor() + getChatTag() : TL.NOFACTION_PREFIX.toString(); + } + + @Override + public String getChatTag(FPlayer fplayer) { + return this.hasFaction() ? this.getRelationTo(fplayer).getColor() + getChatTag() : TL.NOFACTION_PREFIX.toString(); + } + + public int getKills() { + return isOnline() ? getPlayer().getStatistic(Statistic.PLAYER_KILLS) : this.kills; + } + + public int getDeaths() { + return isOnline() ? getPlayer().getStatistic(Statistic.DEATHS) : this.deaths; + + } + + // ------------------------------- + // Relation and relation colors + // ------------------------------- + + @Override + public String describeTo(RelationParticipator that, boolean ucfirst) { + return RelationUtil.describeThatToMe(this, that, ucfirst); + } + + @Override + public String describeTo(RelationParticipator that) { + return RelationUtil.describeThatToMe(this, that); + } + + @Override + public Relation getRelationTo(RelationParticipator rp) { + return RelationUtil.getRelationTo(this, rp); + } + + @Override + public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { + return RelationUtil.getRelationTo(this, rp, ignorePeaceful); + } + + public Relation getRelationToLocation() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this); + } + + public Relation getRelationToLocation(FLocation fLocation) { + return RelationUtil.getRelationTo(this, Board.getInstance().getFactionAt(fLocation)); + } + + @Override + public ChatColor getColorTo(RelationParticipator rp) { + return RelationUtil.getColorOfThatToMe(this, rp); + } + + //----------------------------------------------// + // Health + //----------------------------------------------// + public void heal(int amnt) { + Player player = this.getPlayer(); + if (player == null) { + return; + } + player.setHealth(player.getHealth() + amnt); + } + + + //----------------------------------------------// + // Power + //----------------------------------------------// + public double getPower() { + this.updatePower(); + return this.power; + } + + public void alterPower(double delta) { + this.power += delta; + if (this.power > this.getPowerMax()) { + this.power = this.getPowerMax(); + } else if (this.power < this.getPowerMin()) { + this.power = this.getPowerMin(); + } + } + + public double getPowerMax() { + return FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getPlayerMax() + this.powerBoost; + } + + public double getPowerMin() { + return FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getPlayerMin() + this.powerBoost; + } + + public int getPowerRounded() { + return (int) Math.round(this.getPower()); + } + + public int getPowerMaxRounded() { + return (int) Math.round(this.getPowerMax()); + } + + public int getPowerMinRounded() { + return (int) Math.round(this.getPowerMin()); + } + + public void updatePower() { + if (this.isOffline()) { + losePowerFromBeingOffline(); + if (!FactionsPlugin.getInstance().conf().factions().landRaidControl().power().isRegenOffline()) { + return; + } + } else if (hasFaction() && getFaction().isPowerFrozen()) { + return; // Don't let power regen if faction power is frozen. + } + long now = System.currentTimeMillis(); + long millisPassed = now - this.lastPowerUpdateTime; + this.lastPowerUpdateTime = now; + + Player thisPlayer = this.getPlayer(); + if (thisPlayer != null && thisPlayer.isDead()) { + return; // don't let dead players regain power until they respawn + } + + int millisPerMinute = 60 * 1000; + this.alterPower(millisPassed * FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getPowerPerMinute() / millisPerMinute); + } + + public void losePowerFromBeingOffline() { + long now = System.currentTimeMillis(); + if (FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getOfflineLossPerDay() > 0.0 && this.power > FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getOfflineLossLimit()) { + long millisPassed = now - this.lastPowerUpdateTime; + + double loss = millisPassed * FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getOfflineLossPerDay() / (24 * 60 * 60 * 1000); + if (this.power - loss < FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getOfflineLossLimit()) { + loss = this.power; + } + this.alterPower(-loss); + } + this.lastPowerUpdateTime = now; + } + + public void onDeath() { + if (hasFaction()) { + getFaction().setLastDeath(System.currentTimeMillis()); + } + } + + //----------------------------------------------// + // Territory + //----------------------------------------------// + public boolean isInOwnTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)) == this.getFaction(); + } + + public boolean isInOthersTerritory() { + Faction factionHere = Board.getInstance().getFactionAt(new FLocation(this)); + return factionHere != null && factionHere.isNormal() && factionHere != this.getFaction(); + } + + public boolean isInAllyTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isAlly(); + } + + public boolean isInNeutralTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isNeutral(); + } + + public boolean isInEnemyTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isEnemy(); + } + + public void sendFactionHereMessage(Faction from) { + Faction toShow = Board.getInstance().getFactionAt(getLastStoodAt()); + boolean showTitle = FactionsPlugin.getInstance().conf().factions().enterTitles().isEnabled(); + boolean showChat = true; + Player player = getPlayer(); + + if (showTitle && player != null) { + int in = FactionsPlugin.getInstance().conf().factions().enterTitles().getFadeIn(); + int stay = FactionsPlugin.getInstance().conf().factions().enterTitles().getStay(); + int out = FactionsPlugin.getInstance().conf().factions().enterTitles().getFadeOut(); + + String title = Tag.parsePlain(toShow, this, FactionsPlugin.getInstance().conf().factions().enterTitles().getTitle()); + String sub = FactionsPlugin.getInstance().txt().parse(Tag.parsePlain(toShow, this, FactionsPlugin.getInstance().conf().factions().enterTitles().getSubtitle())); + + // We send null instead of empty because Spigot won't touch the title if it's null, but clears if empty. + // We're just trying to be as unintrusive as possible. + + + if (Toggle.FACTION_LAND_TITLE.getToggle(player)) { + TitleAPI.getInstance().sendTitle(player, title, sub, in, stay, out); + } + + + showChat = FactionsPlugin.getInstance().conf().factions().enterTitles().isAlsoShowChat(); + } + + if (showInfoBoard(toShow)) { + FScoreboard.get(this).setTemporarySidebar(new FInfoSidebar(toShow)); + showChat = FactionsPlugin.getInstance().conf().scoreboard().info().isAlsoSendChat(); + } + if (showChat) { + this.sendMessage(FactionsPlugin.getInstance().txt().parse(TL.FACTION_LEAVE.format(from.getTag(this), toShow.getTag(this)))); + } + } + + /** + * Check if the scoreboard should be shown. Simple method to be used by above method. + * + * @param toShow Faction to be shown. + * @return true if should show, otherwise false. + */ + public boolean showInfoBoard(Faction toShow) { + return showScoreboard && !toShow.isWarZone() && !toShow.isWilderness() && !toShow.isSafeZone() && FactionsPlugin.getInstance().conf().scoreboard().info().isEnabled() && FScoreboard.get(this) != null; + } + + @Override + public boolean showScoreboard() { + return this.showScoreboard; + } + + @Override + public void setShowScoreboard(boolean show) { + this.showScoreboard = show; + } + + // ------------------------------- + // Actions + // ------------------------------- + + public void leave(boolean makePay) { + Faction myFaction = this.getFaction(); + boolean econMakePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); + + if (myFaction == null) { + resetFactionData(); + return; + } + + boolean perm = myFaction.isPermanent(); + + if (!perm && this.getRole() == Role.ADMIN && myFaction.getFPlayers().size() > 1) { + msg(TL.LEAVE_PASSADMIN); + return; + } + + if (makePay && !FactionsPlugin.getInstance().getLandRaidControl().canLeaveFaction(this)) { + return; + } + + // if economy is enabled and they're not on the bypass list, make sure they can pay + if (econMakePay && !Econ.hasAtLeast(this, FactionsPlugin.getInstance().conf().economy().getCostLeave(), TL.LEAVE_TOLEAVE.toString())) { + return; + } + + FPlayerLeaveEvent leaveEvent = new FPlayerLeaveEvent(this, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.LEAVE); + Bukkit.getServer().getPluginManager().callEvent(leaveEvent); + if (leaveEvent.isCancelled()) { + return; + } + + // then make 'em pay (if applicable) + if (econMakePay && !Econ.modifyMoney(this, -FactionsPlugin.getInstance().conf().economy().getCostLeave(), TL.LEAVE_TOLEAVE.toString(), TL.LEAVE_FORLEAVE.toString())) { + return; + } + + // Am I the last one in the faction? + if (myFaction.getFPlayers().size() == 1) { + // Transfer all money + if (Econ.shouldBeUsed()) { + Econ.transferMoney(this, myFaction, this, Econ.getBalance(myFaction)); + } + } + + if (myFaction.isNormal()) { + for (FPlayer fplayer : myFaction.getFPlayersWhereOnline(true)) { + fplayer.msg(TL.LEAVE_LEFT, this.describeTo(fplayer, true), myFaction.describeTo(fplayer)); + } + + if (FactionsPlugin.getInstance().conf().logging().isFactionLeave()) { + FactionsPlugin.getInstance().log(TL.LEAVE_LEFT.format(this.getName(), myFaction.getTag())); + } + } + + myFaction.removeAnnouncements(this); + this.resetFactionData(); + //setFlying(false, false); + + if (myFaction.isNormal() && !perm && myFaction.getFPlayers().isEmpty()) { + // Remove this faction + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.LEAVE_DISBANDED, myFaction.describeTo(fplayer, true)); + } + + FactionsPlugin.getInstance().getServer().getPluginManager().callEvent(new FactionAutoDisbandEvent(myFaction)); + Factions.getInstance().removeFaction(myFaction.getId()); + if (FactionsPlugin.getInstance().conf().logging().isFactionDisband()) { + FactionsPlugin.getInstance().log(TL.LEAVE_DISBANDEDLOG.format(myFaction.getTag(), myFaction.getId(), this.getName())); + } + } + } + + public boolean canClaimForFaction(Faction forFaction) { + return this.isAdminBypassing() || !forFaction.isWilderness() && (forFaction == this.getFaction() && this.getFaction().hasAccess(this, PermissibleAction.TERRITORY)) || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())); + } + + // Not used + public boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure) { + return canClaimForFactionAtLocation(forFaction, new FLocation(location), notifyFailure); + } + + public boolean canClaimForFactionAtLocation(Faction forFaction, FLocation location, boolean notifyFailure) { + return canClaimForFactionAtLocation(forFaction, location, notifyFailure, null); + } + + public boolean canClaimForFactionAtLocation(Faction forFaction, FLocation location, boolean notifyFailure, SpiralTask spiralTask) { + return canClaimForFactionAtLocation(forFaction, Board.getInstance().getFactionAt(location), location, notifyFailure, spiralTask); + } + + public boolean canClaimForFactionAtLocation(Faction forFaction, Faction currentFaction, FLocation flocation, boolean notifyFailure, SpiralTask spiralTask) { + FactionsPlugin plugin = FactionsPlugin.getInstance(); + String denyReason = null; + Faction myFaction = getFaction(); + int ownedLand = forFaction.getLandRounded(); + int factionBuffer = plugin.conf().factions().claims().getBufferZone(); + int worldBuffer = plugin.conf().worldBorder().getBuffer(); + + boolean doCancel = false; + + if (plugin.conf().worldGuard().isChecking() && plugin.getWorldguard() != null && plugin.getWorldguard().checkForRegionsInChunk(flocation.getChunk())) { + // Checks for WorldGuard regions in the chunk attempting to be claimed + denyReason = plugin.txt().parse(TL.CLAIM_PROTECTED.toString()); + } else if (plugin.conf().factions().claims().getWorldsNoClaiming().contains(flocation.getWorldName())) { + // Cannot claim in this world + denyReason = plugin.txt().parse(TL.CLAIM_DISABLED.toString()); + } else if (this.isAdminBypassing()) { + // Admin bypass + return true; + } else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { + // Safezone and can claim for such + return true; + } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { + // Warzone and can claim for such + return true; + } else if (!forFaction.hasAccess(this, PermissibleAction.TERRITORY)) { + // Lacking perms to territory claim + denyReason = plugin.txt().parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); + } else if (forFaction == currentFaction) { + // Already owned by this faction, nitwit + if (spiralTask == null) + denyReason = plugin.txt().parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true)); + } else if (forFaction.getFPlayers().size() < plugin.conf().factions().claims().getRequireMinFactionMembers()) { + // Need more members in order to claim land + denyReason = plugin.txt().parse(TL.CLAIM_MEMBERS.toString(), plugin.conf().factions().claims().getRequireMinFactionMembers()); + } else if (currentFaction.isSafeZone()) { + // Cannot claim safezone + denyReason = plugin.txt().parse(TL.CLAIM_SAFEZONE.toString()); + } else if (currentFaction.isWarZone()) { + // Cannot claim warzone + denyReason = plugin.txt().parse(TL.CLAIM_WARZONE.toString()); + } else if (plugin.getLandRaidControl() instanceof PowerControl && ownedLand >= forFaction.getPowerRounded()) { + // Already own at least as much land as power + doCancel = true; + denyReason = plugin.txt().parse(TL.CLAIM_POWER.toString()); + } else if (plugin.getLandRaidControl() instanceof DTRControl && ownedLand >= plugin.getLandRaidControl().getLandLimit(forFaction)) { + // Already own at least as much land as land limit (DTR) + doCancel = true; + denyReason = plugin.txt().parse(TL.CLAIM_DTR_LAND.toString()); + } else if (plugin.conf().factions().claims().getLandsMax() != 0 && ownedLand >= plugin.conf().factions().claims().getLandsMax() && forFaction.isNormal()) { + // Land limit reached + denyReason = plugin.txt().parse(TL.CLAIM_LIMIT.toString()); + doCancel = true; + } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { + // // Can't claim ally + denyReason = plugin.txt().parse(TL.CLAIM_ALLY.toString()); + } else if (plugin.conf().factions().claims().isMustBeConnected() && !this.isAdminBypassing() && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, myFaction) && (!plugin.conf().factions().claims().isCanBeUnconnectedIfOwnedByOtherFaction() || !currentFaction.isNormal())) { + // Must be contiguous/connected + if (plugin.conf().factions().claims().isCanBeUnconnectedIfOwnedByOtherFaction()) { + denyReason = plugin.txt().parse(TL.CLAIM_CONTIGIOUS.toString()); + } else { + denyReason = plugin.txt().parse(TL.CLAIM_FACTIONCONTIGUOUS.toString()); + } + } else if (!(currentFaction.isNormal() && plugin.conf().factions().claims().isAllowOverClaimAndIgnoringBuffer() && currentFaction.hasLandInflation()) && factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) { + // Too close to buffer + denyReason = plugin.txt().parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer)); + } else if (flocation.isOutsideWorldBorder(worldBuffer)) { + // Border buffer + if (worldBuffer > 0) { + denyReason = plugin.txt().parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer)); + } else { + denyReason = plugin.txt().parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); + } + + doCancel = true; + } else if (currentFaction.isNormal()) { + if (myFaction.isPeaceful()) { + // Cannot claim as peaceful + denyReason = plugin.txt().parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this)); + } else if (currentFaction.isPeaceful()) { + // Cannot claim from peaceful + denyReason = plugin.txt().parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this)); + } else if (!currentFaction.hasLandInflation()) { + // Cannot claim other faction (perhaps based on power/land ratio) + // TODO more messages WARN current faction most importantly + denyReason = plugin.txt().parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this)); + } else if (currentFaction.hasLandInflation() && !plugin.conf().factions().claims().isAllowOverClaim()) { + // deny over claim when it normally would be allowed. + denyReason = plugin.txt().parse(TL.CLAIM_OVERCLAIM_DISABLED.toString()); + } else if (!Board.getInstance().isBorderLocation(flocation)) { + denyReason = plugin.txt().parse(TL.CLAIM_BORDER.toString()); + } + } + // TODO: Add more else if statements. + + if (doCancel && spiralTask != null) { + msg(denyReason); + spiralTask.stopTooSoon(); + return false; + } + if (notifyFailure && denyReason != null) { + msg(denyReason); + } + return denyReason == null; + } + + public boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure) { + return attemptClaim(forFaction, new FLocation(location), notifyFailure); + } + + public boolean attemptClaim(Faction forFaction, FLocation location, boolean notifyFailure) { + return attemptClaim(forFaction, location, notifyFailure, null); + } + + public boolean attemptClaim(Faction forFaction, FLocation flocation, boolean notifyFailure, SpiralTask spiralTask) { + // notifyFailure is false if called by auto-claim; no need to notify on every failure for it + // return value is false on failure, true on success + + WorldBorder worldBorder = flocation.getWorld().getWorldBorder(); + + double radius = worldBorder.getSize() / 2; + + double cxMin = Math.floor((worldBorder.getCenter().getX() - radius - 1) / 16.0D); + double cxMax = Math.floor((worldBorder.getCenter().getX() + radius) / 16.0D); + + double czMin = Math.floor((worldBorder.getCenter().getZ() - radius - 1) / 16.0D); + double czMax = Math.floor((worldBorder.getCenter().getZ() + radius) / 16.0D); + + if (flocation.getX() < cxMin || flocation.getX() > cxMax || flocation.getZ() < czMin || flocation.getZ() > czMax) { + this.msg(TL.COMMAND_CLAIM_OUTSIDEBORDER); + return false; + } + + Faction currentFaction = Board.getInstance().getFactionAt(flocation); + + int ownedLand = forFaction.getLandRounded(); + + if (!this.canClaimForFactionAtLocation(forFaction, currentFaction, flocation, notifyFailure, spiralTask)) { + return false; + } else if (currentFaction == forFaction) { + return true; + } + + // if economy is enabled and they're not on the bypass list, make sure they can pay + boolean mustPay = Econ.shouldBeUsed() && !this.isAdminBypassing() && !forFaction.isSafeZone() && !forFaction.isWarZone(); + double cost = 0.0; + EconomyParticipator payee = null; + if (mustPay && FactionsPlugin.getInstance().conf().economy().getClaimUnconnectedFee() != 0.0) { + cost = Econ.calculateClaimCost(ownedLand, currentFaction.isNormal()); + + if (forFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, forFaction)) { + cost += FactionsPlugin.getInstance().conf().economy().getClaimUnconnectedFee(); + } + + if (FactionsPlugin.getInstance().conf().economy().isBankEnabled() && FactionsPlugin.getInstance().conf().economy().isBankFactionPaysLandCosts() && this.hasFaction() && this.getFaction().hasAccess(this, PermissibleAction.ECONOMY)) { + payee = this.getFaction(); + } else { + payee = this; + } + + if (!Econ.hasAtLeast(payee, cost, TL.CLAIM_TOCLAIM.toString())) { + return false; + } + } else { + mustPay = false; + } + + LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); + Bukkit.getServer().getPluginManager().callEvent(claimEvent); + if (claimEvent.isCancelled()) { + return false; + } + + // then make 'em pay (if applicable) + if (mustPay && !Econ.modifyMoney(payee, -cost, TL.CLAIM_TOCLAIM.toString(), TL.CLAIM_FORCLAIM.toString())) { + return false; + } + + // Was an over claim + if (mustPay && currentFaction.isNormal() && currentFaction.hasLandInflation()) { + // Give them money for over claiming. + Econ.modifyMoney(payee, FactionsPlugin.getInstance().conf().economy().getOverclaimRewardMultiplier(), TL.CLAIM_TOOVERCLAIM.toString(), TL.CLAIM_FOROVERCLAIM.toString()); + } + + // announce success + if (spiralTask == null) { + Set informTheseFPlayers = new HashSet<>(); + informTheseFPlayers.add(this); + informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); + for (FPlayer fp : informTheseFPlayers) { + fp.msg(TL.CLAIM_CLAIMED, this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); + } + } + + Board.getInstance().setFactionAt(forFaction, flocation); + + if (FactionsPlugin.getInstance().conf().logging().isLandClaims()) { + FactionsPlugin.getInstance().log(TL.CLAIM_CLAIMEDLOG.toString(), this.getName(), flocation.getCoordString(), forFaction.getTag(), flocation.getWorldName()); + } + + return true; + } + + public boolean shouldBeSaved() { + return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getPlayerStarting())); + } + + public void msg(String str, Object... args) { + this.sendMessage(FactionsPlugin.getInstance().txt().parse(str, args)); + } + + public void msg(TL translation, Object... args) { + this.msg(translation.toString(), args); + } + + public Player getPlayer() { + return Bukkit.getPlayer(UUID.fromString(this.getId())); + } + + public Location getLocation() { + return getPlayer().getLocation(); + } + + public FLocation getFLocation() { + return new FLocation(getLocation()); + } + + public boolean isOnline() { + Player player = this.getPlayer(); + return player != null && FactionsPlugin.getInstance().worldUtil().isEnabled(player.getWorld()); + } + + // make sure target player should be able to detect that this player is online + public boolean isOnlineAndVisibleTo(Player player) { + Player target = this.getPlayer(); + return target != null && player.canSee(target) && FactionsPlugin.getInstance().worldUtil().isEnabled(player.getWorld()); + } + + public boolean isOffline() { + return !isOnline(); + } + + public boolean isFlying() { + Player player = getPlayer(); + return player != null && this.getPlayer().getAllowFlight(); + } + + public void setFlying(boolean fly) { + setFlying(fly, false); + } + + public void setFlying(boolean fly, boolean damage) { +/* if (fly && !this.isFlying() && FactionsPlugin.getInstance().isSOTW() && !Permission.SOTW.has(this.getPlayer())) { + this.msg(TL.PLAYER_SOTW_NOFLY); + return; + } + + Player player = getPlayer(); + if (player != null) { + player.setAllowFlight(fly); + player.setFlying(fly); + } + + if (!damage) { + msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); + } else { + msg(TL.COMMAND_FLY_DAMAGE); + } + + // If leaving fly mode, don't let them take fall damage for x seconds. + if (!fly) { + int cooldown = FactionsPlugin.getInstance().conf().commands().fly().getFallDamageCooldown(); + + // If the value is 0 or lower, make them take fall damage. + // Otherwise, start a timer and have this cancel after a few seconds. + // Short task so we're just doing it in method. Not clean but eh. + if (cooldown > 0) { + setTakeFallDamage(false); + new BukkitRunnable() { + @Override + public void run() { + setTakeFallDamage(true); + } + }.runTaskLater(FactionsPlugin.getInstance(), 20L * cooldown); + } + }*/ + } + + public boolean isAutoFlying() { + return isAutoFlying; + } + + public void setAutoFlying(boolean autoFly) { + msg(TL.COMMAND_FLY_AUTO, autoFly ? "enabled" : "disabled"); + this.isAutoFlying = autoFly; + } + + public boolean canFlyAtLocation() { + return canFlyAtLocation(lastStoodAt); + } + + public boolean canFlyAtLocation(FLocation location) { + return this.canFlyInFactionTerritory(Board.getInstance().getFactionAt(location)); + } + + public boolean canFlyInFactionTerritory(Faction faction) { + if (this.getPlayer() != null && Permission.FLY_ANY.has(this.getPlayer())) return true; + if (faction.isWilderness()) { + return Permission.FLY_WILDERNESS.has(getPlayer()); + } else if (faction.isSafeZone()) { + return Permission.FLY_SAFEZONE.has(getPlayer()); + } else if (faction.isWarZone()) { + return Permission.FLY_WARZONE.has(getPlayer()); + } + + // admin bypass (ops) can fly. + if (isAdminBypassing) { + return true; + } + + return faction.hasAccess(this, PermissibleAction.FLY); + } + + public boolean shouldTakeFallDamage() { + return this.shouldTakeFallDamage; + } + + public void setTakeFallDamage(boolean fallDamage) { + this.shouldTakeFallDamage = fallDamage; + } + + public boolean isSeeingChunk() { + return seeingChunk; + } + + public void setSeeingChunk(boolean seeingChunk) { + this.seeingChunk = seeingChunk; + FactionsPlugin.getInstance().getSeeChunkUtil().updatePlayerInfo(UUID.fromString(getId()), seeingChunk); + } + + public boolean getFlyTrailsState() { + return flyTrailsState; + } + + public void setFlyTrailsState(boolean state) { + flyTrailsState = state; + msg(TL.COMMAND_FLYTRAILS_CHANGE, state ? "enabled" : "disabled"); + } + + public String getFlyTrailsEffect() { + return flyTrailsEffect; + } + + public void setFlyTrailsEffect(String effect) { + flyTrailsEffect = effect; + msg(TL.COMMAND_FLYTRAILS_PARTICLE_CHANGE, effect); + } + + // -------------------------------------------- // + // Message Sending Helpers + // -------------------------------------------- // + + public void sendMessage(String msg) { + if (msg.contains("{null}")) { + return; // user wants this message to not send + } + if (msg.contains("/n/")) { + for (String s : msg.split("/n/")) { + sendMessage(s); + } + return; + } + Player player = this.getPlayer(); + if (player == null) { + return; + } + player.sendMessage(msg); + } + + public void sendMessage(List msgs) { + for (String msg : msgs) { + this.sendMessage(msg); + } + } + + public void sendFancyMessage(FancyMessage message) { + Player player = getPlayer(); + if (player == null) { + return; + } + + message.send(player); + } + + public void sendFancyMessage(List messages) { + Player player = getPlayer(); + if (player == null) { + return; + } + + for (FancyMessage msg : messages) { + msg.send(player); + } + } + + public int getMapHeight() { + if (this.mapHeight < 1) { + this.mapHeight = FactionsPlugin.getInstance().conf().map().getHeight(); + } + + return this.mapHeight; + } + + public void setMapHeight(int height) { + this.mapHeight = Math.min(height, (FactionsPlugin.getInstance().conf().map().getHeight() * 2)); + } + + public String getNameAndTitle(FPlayer fplayer) { + return this.getColorTo(fplayer) + this.getNameAndTitle(); + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public void clearWarmup() { + if (warmup != null) { + Bukkit.getScheduler().cancelTask(warmupTask); + this.stopWarmup(); + } + } + + @Override + public void stopWarmup() { + warmup = null; + } + + @Override + public boolean isWarmingUp() { + return warmup != null; + } + + @Override + public WarmUpUtil.Warmup getWarmupType() { + return warmup; + } + + @Override + public void addWarmup(WarmUpUtil.Warmup warmup, int taskId) { + if (this.warmup != null) { + this.clearWarmup(); + } + this.warmup = warmup; + this.warmupTask = taskId; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/MemoryFPlayers.java b/Factions/src/main/java/com/massivecraft/factions/data/MemoryFPlayers.java new file mode 100644 index 0000000..c64ddd0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/MemoryFPlayers.java @@ -0,0 +1,66 @@ +package com.massivecraft.factions.data; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentSkipListMap; + +public abstract class MemoryFPlayers extends FPlayers { + public Map fPlayers = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); + + public void clean() { + for (FPlayer fplayer : this.fPlayers.values()) { + if (!Factions.getInstance().isValidFactionId(fplayer.getFactionId())) { + FactionsPlugin.getInstance().log("Reset faction data (invalid faction:" + fplayer.getFactionId() + ") for player " + fplayer.getName()); + fplayer.resetFactionData(false); + } + } + } + + public Collection getOnlinePlayers() { + Set entities = new HashSet<>(); + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + entities.add(this.getByPlayer(player)); + } + return entities; + } + + @Override + public FPlayer getByPlayer(Player player) { + return getById(player.getUniqueId().toString()); + } + + @Override + public List getAllFPlayers() { + return new ArrayList<>(fPlayers.values()); + } + + @Override + public FPlayer getByOfflinePlayer(OfflinePlayer player) { + return getById(player.getUniqueId().toString()); + } + + @Override + public FPlayer getById(String id) { + FPlayer player = fPlayers.get(id); + if (player == null) { + player = generateFPlayer(id); + } + return player; + } + + protected abstract FPlayer generateFPlayer(String id); + + public abstract void convertFrom(MemoryFPlayers old); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/MemoryFaction.java b/Factions/src/main/java/com/massivecraft/factions/data/MemoryFaction.java new file mode 100644 index 0000000..5cde36a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/MemoryFaction.java @@ -0,0 +1,1483 @@ +package com.massivecraft.factions.data; + +import com.massivecraft.factions.*; +import com.massivecraft.factions.config.file.DefaultPermissionsConfig; +import com.massivecraft.factions.event.FactionAutoDisbandEvent; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.iface.RelationParticipator; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.landraidcontrol.DTRControl; +import com.massivecraft.factions.landraidcontrol.LandRaidControl; +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.BanInfo; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +public abstract class MemoryFaction implements Faction, EconomyParticipator { + protected String id = null; + protected boolean peacefulExplosionsEnabled; + protected boolean permanent; + protected String tag; + protected String description; + protected boolean open; + protected boolean peaceful; + protected Integer permanentPower; + protected LazyLocation home; + protected long foundedDate; + protected transient int maxAlts = FactionsPlugin.getInstance().conf().factions().other().maxAlts(); + protected transient long lastPlayerLoggedOffTime; + protected double powerBoost; + protected Map relationWish = new HashMap<>(); + protected List strikes = new ArrayList<>(); + protected Map> claimOwnership = new ConcurrentHashMap<>(); + protected transient Set fplayers = new HashSet<>(); + protected transient FPlayer fPlayerAdmin; + protected String payPalLink; + protected Set invites = new HashSet<>(); + protected HashMap> announcements = new HashMap<>(); + protected ConcurrentHashMap warps = new ConcurrentHashMap<>(); + protected ConcurrentHashMap warpPasswords = new ConcurrentHashMap<>(); + private long lastDeath; + protected int maxVaults; + protected Role defaultRole; + protected Map> permissions = new HashMap<>(); + protected Map> permissionsOffline = new HashMap<>(); + protected Set bans = new HashSet<>(); + protected double dtr; + protected long lastDTRUpdateTime; + protected long frozenDTRUntilTime; + protected int tntBank = 0; + protected String altJoinString = "-1"; + protected transient OfflinePlayer offlinePlayer; + + protected Map upgrades = new HashMap<>(); + + public HashMap> getAnnouncements() { + return this.announcements; + } + + protected String items = ""; + + protected transient Inventory inventory; + + public void addAnnouncement(FPlayer fPlayer, String msg) { + List list = announcements.containsKey(fPlayer.getId()) ? announcements.get(fPlayer.getId()) : new ArrayList<>(); + list.add(msg); + announcements.put(fPlayer.getId(), list); + } + + public void sendUnreadAnnouncements(FPlayer fPlayer) { + if (!announcements.containsKey(fPlayer.getId())) { + return; + } + fPlayer.msg(TL.FACTIONS_ANNOUNCEMENT_TOP); + for (String s : announcements.get(fPlayer.getPlayer().getUniqueId().toString())) { + fPlayer.sendMessage(s); + } + fPlayer.msg(TL.FACTIONS_ANNOUNCEMENT_BOTTOM); + announcements.remove(fPlayer.getId()); + } + + public void setItems() { + ItemStack[] stacks = this.getChest().getContents(); + + this.items = ItemBase64.itemStackArrayToBase64(stacks); + } + + public void removeAnnouncements(FPlayer fPlayer) { + announcements.remove(fPlayer.getId()); + } + + public ConcurrentHashMap getWarps() { + return this.warps; + } + + public LazyLocation getWarp(String name) { + return this.warps.get(name); + } + + public void setWarp(String name, LazyLocation loc) { + this.warps.put(name, loc); + } + + public int getMaxWarps() { + if(!FactionsPlugin.getInstance().conf().upgrades().isEnabled()) return FactionsPlugin.getInstance().conf().commands().warp().getMaxWarps(); + return FactionsPlugin.getInstance().conf().upgrades().warpAmount().getNumber(this.getUpgrade(UpgradeType.WARP_AMOUNT)); + } + + public boolean isWarp(String name) { + return this.warps.containsKey(name); + } + + public boolean removeWarp(String name) { + warpPasswords.remove(name); // remove password no matter what. + return warps.remove(name) != null; + } + + public boolean isWarpPassword(String warp, String password) { + return hasWarpPassword(warp) && warpPasswords.get(warp.toLowerCase()).equals(password); + } + + public boolean hasWarpPassword(String warp) { + return warpPasswords.containsKey(warp.toLowerCase()); + } + + public void setWarpPassword(String warp, String password) { + warpPasswords.put(warp.toLowerCase(), password); + } + + public void clearWarps() { + warps.clear(); + } + + public int getMaxVaults() { + return this.maxVaults; + } + + public void setMaxVaults(int value) { + this.maxVaults = value; + } + + public Set getInvites() { + return invites; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + this.offlinePlayer = null; + } + + public void invite(FPlayer fplayer) { + this.invites.add(fplayer.getId()); + } + + public void deinvite(FPlayer fplayer) { + this.invites.remove(fplayer.getId()); + } + + public boolean isInvited(FPlayer fplayer) { + return this.invites.contains(fplayer.getId()); + } + + public void ban(FPlayer target, FPlayer banner) { + BanInfo info = new BanInfo(banner.getId(), target.getId(), System.currentTimeMillis()); + this.bans.add(info); + } + + public void unban(FPlayer player) { + bans.removeIf(banInfo -> banInfo.getBanned().equalsIgnoreCase(player.getId())); + } + + public boolean isBanned(FPlayer player) { + for (BanInfo info : bans) { + if (info.getBanned().equalsIgnoreCase(player.getId())) { + return true; + } + } + + return false; + } + + public Set getBannedPlayers() { + return this.bans; + } + + public boolean getOpen() { + return open; + } + + public void setOpen(boolean isOpen) { + open = isOpen; + } + + public boolean isPeaceful() { + return this.peaceful; + } + + public void setPeaceful(boolean isPeaceful) { + this.peaceful = isPeaceful; + } + + public void setPeacefulExplosionsEnabled(boolean val) { + peacefulExplosionsEnabled = val; + } + + public boolean getPeacefulExplosionsEnabled() { + return this.peacefulExplosionsEnabled; + } + + public boolean noExplosionsInTerritory() { + return this.peaceful && !peacefulExplosionsEnabled; + } + + public boolean isPermanent() { + return permanent || !this.isNormal(); + } + + public void setPermanent(boolean isPermanent) { + permanent = isPermanent; + } + + public String getTag() { + return this.tag; + } + + public String getTag(String prefix) { + return prefix + this.tag; + } + + public String getTag(Faction otherFaction) { + if (otherFaction == null) { + return getTag(); + } + return this.getTag(this.getColorTo(otherFaction).toString()); + } + + public String getTag(FPlayer otherFplayer) { + if (otherFplayer == null) { + return getTag(); + } + return this.getTag(this.getColorTo(otherFplayer).toString()); + } + + public void setTag(String str) { + if (FactionsPlugin.getInstance().conf().factions().other().isTagForceUpperCase()) { + str = str.toUpperCase(); + } + this.tag = str; + } + + public String getComparisonTag() { + return MiscUtil.getComparisonString(this.tag); + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String value) { + this.description = value; + } + + public void setHome(Location home) { + this.home = new LazyLocation(home); + } + + public void delHome() { + this.home = null; + } + + public boolean hasHome() { + return this.getHome() != null; + } + + public Location getHome() { + confirmValidHome(); + return (this.home != null) ? this.home.getLocation() : null; + } + + public long getFoundedDate() { + if (this.foundedDate == 0) { + setFoundedDate(System.currentTimeMillis()); + } + return this.foundedDate; + } + + public void setFoundedDate(long newDate) { + this.foundedDate = newDate; + } + + public void confirmValidHome() { + if (!FactionsPlugin.getInstance().conf().factions().homes().isMustBeInClaimedTerritory() || this.home == null || (this.home.getLocation() != null && Board.getInstance().getFactionAt(new FLocation(this.home.getLocation())) == this)) { + return; + } + + msg("Your faction home has been un-set since it is no longer in your territory."); + this.home = null; + } + + public String getAltJoinString() { + return altJoinString; + } + + public String setAltOpen() { + return altJoinString = TextUtil.generateRandomString(6); + } + + public void setAltClosed(){ + this.altJoinString = "-1"; + } + + public String getAccountId() { + return "faction-" + this.getId(); + } + + public OfflinePlayer getOfflinePlayer() { + if (this.offlinePlayer == null) { + this.offlinePlayer = Bukkit.getOfflinePlayer(this.getAccountId()); + } + return this.offlinePlayer; + } + + public void setLastDeath(long time) { + this.lastDeath = time; + } + + public long getLastDeath() { + return this.lastDeath; + } + + public int getKills() { + int kills = 0; + for (FPlayer fp : getFPlayers()) { + kills += fp.getKills(); + } + + return kills; + } + + public int getDeaths() { + int deaths = 0; + for (FPlayer fp : getFPlayers()) { + deaths += fp.getDeaths(); + } + + return deaths; + } + + // -------------------------------------------- // + // F Permissions stuff + // -------------------------------------------- // + + + public boolean hasAccess(boolean online, Permissible permissible, PermissibleAction permissibleAction) { + if (permissible == null || permissibleAction == null) { + return false; // Fail in a safe way + } + if (permissible == Role.ADMIN) { + return true; + } + + Map> permissionsMap = this.getPermissionsMap(online); + + DefaultPermissionsConfig.Permissions.PermissiblePermInfo permInfo = this.getPermInfo(online, permissible, permissibleAction); + if (permInfo == null) { // Not valid lookup, like a role-only lookup of a relation + return false; + } + if (permInfo.isLocked()) { // Locked, so ignore the faction's setting + return permInfo.defaultAllowed(); + } + + Map accessMap = permissionsMap.get(permissible); + if (accessMap != null && accessMap.containsKey(permissibleAction)) { + return accessMap.get(permissibleAction); + } + + return permInfo.defaultAllowed(); // Fall back on default if something went wrong + } + + public boolean isLocked(boolean online, Permissible permissible, PermissibleAction permissibleAction) { + DefaultPermissionsConfig.Permissions.PermissiblePermInfo permInfo = this.getPermInfo(online, permissible, permissibleAction); + if (permInfo == null) { // Not valid lookup, like a role-only lookup of a relation + return false; + } + return permInfo.isLocked(); + } + + private DefaultPermissionsConfig.Permissions.PermissiblePermInfo getPermInfo(boolean online, Permissible permissible, PermissibleAction permissibleAction) { + DefaultPermissionsConfig.Permissions defaultPermissions = this.getDefaultPermissions(online); + if (permissibleAction.isFactionOnly()) { + if (permissible instanceof Role) { + return permissibleAction.getFactionOnly(defaultPermissions).get(permissible); + } else { + return null; // Can't do things faction only if not in the faction. + } + } else { + return permissibleAction.getFullPerm(defaultPermissions).get(permissible); + } + } + + private Map> getPermissionsMap(boolean online) { + if (online || !FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms()) { + return this.permissions; + } else { + return this.permissionsOffline; + } + } + + private DefaultPermissionsConfig.Permissions getDefaultPermissions(boolean online) { + if (online || !FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms()) { + return FactionsPlugin.getInstance().getConfigManager().getPermissionsConfig().getPermissions(); + } else { + return FactionsPlugin.getInstance().getConfigManager().getOfflinePermissionsConfig().getPermissions(); + } + } + + /** + * Get the Access of a player. Will use player's Role if they are a faction member. Otherwise, uses their Relation. + * + * @param player player + * @param permissibleAction permissible + * @return player's access + */ + public boolean hasAccess(FPlayer player, PermissibleAction permissibleAction) { + if (player == null || permissibleAction == null) { + return false; // Fail in a safe way + } + + Permissible perm; + boolean online = true; + if (player.getFaction() == this) { + perm = player.getRole(); + } else { + perm = player.getFaction().getRelationTo(this); + online = this.hasPlayersOnline(); + } + + return this.hasAccess(online, perm, permissibleAction); + } + + public boolean setPermission(boolean online, Permissible permissible, PermissibleAction permissibleAction, boolean value) { + Map> permissionsMap = this.getPermissionsMap(online); + DefaultPermissionsConfig.Permissions defaultPermissions = this.getDefaultPermissions(online); + + DefaultPermissionsConfig.Permissions.PermissiblePermInfo permInfo = this.getPermInfo(online, permissible, permissibleAction); + if (permInfo == null || permInfo.isLocked()) { + return false; // Locked, can't continue; + } + + Map accessMap = permissionsMap.get(permissible); + if (accessMap == null) { + accessMap = new HashMap<>(); + } + + accessMap.put(permissibleAction, value); + return true; + } + + public void checkPerms() { + if (this.permissions == null || this.permissions.isEmpty()) { + this.resetPerms(); + } else { + this.updatePerms(this.permissions, FactionsPlugin.getInstance().getConfigManager().getPermissionsConfig().getPermissions(), true); + this.updatePerms(this.permissionsOffline, FactionsPlugin.getInstance().getConfigManager().getOfflinePermissionsConfig().getPermissions(), false); + } + } + + public void resetPerms() { + // FactionsPlugin.getInstance().log(Level.WARNING, "Resetting permissions for Faction: " + tag); + + this.resetPerms(this.permissions, FactionsPlugin.getInstance().getConfigManager().getPermissionsConfig().getPermissions(), true); + this.resetPerms(this.permissionsOffline, FactionsPlugin.getInstance().getConfigManager().getOfflinePermissionsConfig().getPermissions(), false); + } + + private void resetPerms(Map> permissions, DefaultPermissionsConfig.Permissions defaults, boolean online) { + permissions.clear(); + + for (Relation relation : Relation.values()) { + if (relation != Relation.MEMBER) { + permissions.put(relation, new HashMap<>()); + } + } + if (online) { + for (Role role : Role.values()) { + if (role != Role.ADMIN) { + permissions.put(role, new HashMap<>()); + } + } + } + + for (Map.Entry> entry : permissions.entrySet()) { + for (PermissibleAction permissibleAction : PermissibleAction.values()) { + if (permissibleAction.isFactionOnly()) { + if (online && !(entry.getKey() instanceof Relation)) { + entry.getValue().put(permissibleAction, permissibleAction.getFactionOnly(defaults).get(entry.getKey()).defaultAllowed()); + } + } else { + entry.getValue().put(permissibleAction, permissibleAction.getFullPerm(defaults).get(entry.getKey()).defaultAllowed()); + } + } + } + } + + private void updatePerms(Map> permissions, DefaultPermissionsConfig.Permissions defaults, boolean online) { + for (Relation relation : Relation.values()) { + if (relation != Relation.MEMBER) { + permissions.computeIfAbsent(relation, p -> new HashMap<>()); + } + } + if (online) { + for (Role role : Role.values()) { + if (role != Role.ADMIN) { + permissions.computeIfAbsent(role, p -> new HashMap<>()); + } + } + } + + for (Map.Entry> entry : permissions.entrySet()) { + for (PermissibleAction permissibleAction : PermissibleAction.values()) { + if (permissibleAction.isFactionOnly()) { + if (online && !(entry.getKey() instanceof Relation)) { + entry.getValue().computeIfAbsent(permissibleAction, p -> p.getFactionOnly(defaults).get(entry.getKey()).defaultAllowed()); + } + } else if (online || (entry.getKey() instanceof Relation)) { + entry.getValue().computeIfAbsent(permissibleAction, p -> p.getFullPerm(defaults).get(entry.getKey()).defaultAllowed()); + } + } + entry.getValue().remove(null); + } + } + + /** + * Read only map of Permissions. + * + * @return map of permissions + */ + public Map> getPermissions() { + return Collections.unmodifiableMap(permissions); + } + + public Map> getOfflinePermissions() { + return Collections.unmodifiableMap(permissionsOffline); + } + + public Role getDefaultRole() { + return this.defaultRole; + } + + public void setDefaultRole(Role role) { + this.defaultRole = role; + } + + // -------------------------------------------- // + // Construct + // -------------------------------------------- // + protected MemoryFaction() { + } + + public MemoryFaction(String id) { + this.id = id; + this.tntBank = 0; + this.open = FactionsPlugin.getInstance().conf().factions().other().isNewFactionsDefaultOpen(); + this.tag = "???"; + this.description = TL.GENERIC_DEFAULTDESCRIPTION.toString(); + this.lastPlayerLoggedOffTime = 0; + this.peaceful = FactionsPlugin.getInstance().conf().factions().other().isNewFactionsDefaultPeaceful(); + this.peacefulExplosionsEnabled = false; + this.permanent = false; + this.altJoinString = "-1"; + this.powerBoost = 0.0; + this.fPlayerAdmin = null; + this.foundedDate = System.currentTimeMillis(); + this.maxVaults = FactionsPlugin.getInstance().conf().playerVaults().getDefaultMaxVaults(); + this.defaultRole = FactionsPlugin.getInstance().conf().factions().other().getDefaultRole(); + this.dtr = FactionsPlugin.getInstance().conf().factions().landRaidControl().dtr().getStartingDTR(); + + this.inventory = Bukkit.createInventory(new FChestHolder(), + FactionsPlugin.getInstance().conf().upgrades().chest().getDefaultRows() * 9, + TextUtil.parseColor(FactionsPlugin.getInstance().conf().upgrades().chest().getChestName())); + + resetPerms(); // Reset on new Faction so it has default values. + } + + public MemoryFaction(MemoryFaction old) { + id = old.id; + tntBank = old.tntBank; + peacefulExplosionsEnabled = old.peacefulExplosionsEnabled; + permanent = old.permanent; + tag = old.tag; + payPalLink = old.payPalLink; + description = old.description; + open = old.open; + foundedDate = old.foundedDate; + peaceful = old.peaceful; + permanentPower = old.permanentPower; + home = old.home; + altJoinString = old.altJoinString; + lastPlayerLoggedOffTime = old.lastPlayerLoggedOffTime; + powerBoost = old.powerBoost; + relationWish = old.relationWish; + claimOwnership = old.claimOwnership; + fplayers = new HashSet<>(); + fPlayerAdmin = old.fPlayerAdmin; + invites = old.invites; + announcements = old.announcements; + this.strikes = old.strikes; + this.defaultRole = old.defaultRole; + this.dtr = old.dtr; + + upgrades = old.upgrades; + + this.items = old.items; + + resetPerms(); // Reset on new Faction so it has default values. + } + + // -------------------------------------------- // + // Extra Getters And Setters + // -------------------------------------------- // + public boolean noPvPInTerritory() { + return isSafeZone() || (peaceful && FactionsPlugin.getInstance().conf().factions().specialCase().isPeacefulTerritoryDisablePVP()); + } + + public boolean noMonstersInTerritory() { + return isSafeZone() || + (peaceful && FactionsPlugin.getInstance().conf().factions().specialCase().isPeacefulTerritoryDisableMonsters()); + } + + public List getStrikes(){ + return new ArrayList<>(strikes); + } + + public void addStrike(String reason, long date){ + this.strikes.add(new StrikeInfo(date, reason)); + } + + public boolean takeStrike(int index){ + if(this.strikes.size() <= index || index < 0)return false; + + this.strikes.remove(index); + return true; + } + + // ------------------------------- + // Understand the type + // ------------------------------- + + public boolean isNormal() { + return !(this.isWilderness() || this.isSafeZone() || this.isWarZone()); + } + + public boolean isNone() { + return this.getId().equals("0"); + } + + public boolean isWilderness() { + return this.getId().equals("0"); + } + + public boolean isSafeZone() { + return this.getId().equals("-1"); + } + + public boolean isWarZone() { + return this.getId().equals("-2"); + } + + public boolean isPlayerFreeType() { + return this.isSafeZone() || this.isWarZone(); + } + + // ------------------------------- + // Relation and relation colors + // ------------------------------- + + @Override + public String describeTo(RelationParticipator that, boolean ucfirst) { + return RelationUtil.describeThatToMe(this, that, ucfirst); + } + + @Override + public String describeTo(RelationParticipator that) { + return RelationUtil.describeThatToMe(this, that); + } + + @Override + public Relation getRelationTo(RelationParticipator rp) { + return RelationUtil.getRelationTo(this, rp); + } + + public Relation getRelationToLocation(FLocation fLocation){ + return RelationUtil.getRelationTo(this, Board.getInstance().getFactionAt(fLocation)); + } + + @Override + public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { + return RelationUtil.getRelationTo(this, rp, ignorePeaceful); + } + + @Override + public ChatColor getColorTo(RelationParticipator rp) { + return RelationUtil.getColorOfThatToMe(this, rp); + } + + public Relation getRelationWish(Faction otherFaction) { + if (this.relationWish.containsKey(otherFaction.getId())) { + return this.relationWish.get(otherFaction.getId()); + } + return FactionsPlugin.getInstance().conf().factions().other().getDefaultRelationActual(); // Always default to old behavior. + } + + public void setRelationWish(Faction otherFaction, Relation relation) { + if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL)) { + this.relationWish.remove(otherFaction.getId()); + } else { + this.relationWish.put(otherFaction.getId(), relation); + } + } + + public int getRelationCount(Relation relation) { + int count = 0; + for (Faction faction : Factions.getInstance().getAllFactions()) { + if (faction.getRelationTo(this) == relation) { + count++; + } + } + return count; + } + + // ----------------------------------------------// + // DTR + // ----------------------------------------------// + + @Override + public double getDTR() { + LandRaidControl lrc = FactionsPlugin.getInstance().getLandRaidControl(); + if (lrc instanceof DTRControl) { + ((DTRControl) lrc).updateDTR(this); + } + return this.dtr; + } + + @Override + public double getDTRWithoutUpdate() { + return this.dtr; + } + + @Override + public void setDTR(double dtr) { + this.dtr = dtr; + this.lastDTRUpdateTime = System.currentTimeMillis(); + } + + @Override + public long getLastDTRUpdateTime() { + return this.lastDTRUpdateTime; + } + + @Override + public long getFrozenDTRUntilTime() { + return this.frozenDTRUntilTime; + } + + @Override + public void setFrozenDTR(long time) { + this.frozenDTRUntilTime = time; + } + + @Override + public boolean isFrozenDTR() { + return System.currentTimeMillis() < this.frozenDTRUntilTime; + } + + // ----------------------------------------------// + // Power + // ----------------------------------------------// + @Deprecated + public double getPower() { + if (this.hasPermanentPower()) { + return this.getPermanentPower(); + } + + double ret = 0; + for (FPlayer fplayer : fplayers) { + ret += fplayer.getPower(); + } + if (FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getFactionMax() > 0 && ret > FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getFactionMax()) { + ret = FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getFactionMax(); + } + return ret + this.powerBoost; + } + + @Deprecated + public double getPowerMax() { + if (this.hasPermanentPower()) { + return this.getPermanentPower(); + } + + double ret = 0; + for (FPlayer fplayer : fplayers) { + ret += fplayer.getPowerMax(); + } + if (FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getFactionMax() > 0 && ret > FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getFactionMax()) { + ret = FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getFactionMax(); + } + return ret + this.powerBoost; + } + + public int getPowerRounded() { + return (int) Math.round(this.getPower()); + } + + public int getPowerMaxRounded() { + return (int) Math.round(this.getPowerMax()); + } + + public boolean hasLandInflation() { + return FactionsPlugin.getInstance().getLandRaidControl().hasLandInflation(this); + } + + public Integer getPermanentPower() { + return this.permanentPower; + } + + public void setPermanentPower(Integer permanentPower) { + this.permanentPower = permanentPower; + } + + public boolean hasPermanentPower() { + return this.permanentPower != null; + } + + public double getPowerBoost() { + return this.powerBoost; + } + + public void setPowerBoost(double powerBoost) { + this.powerBoost = powerBoost; + } + + public boolean isPowerFrozen() { + int freezeSeconds = FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getPowerFreeze(); + return freezeSeconds != 0 && System.currentTimeMillis() - lastDeath < freezeSeconds * 1000; + } + + public int getLandRounded() { + return Board.getInstance().getFactionCoordCount(this); + } + + public int getLandRoundedInWorld(String worldName) { + return Board.getInstance().getFactionCoordCountInWorld(this, worldName); + } + + public int getTNTBank() { + return this.tntBank; + } + + public void setTNTBank(int amount) { + this.tntBank = amount; + } + + // ------------------------------- + // FPlayers + // ------------------------------- + + // maintain the reference list of FPlayers in this faction + public void refreshFPlayers() { + fplayers.clear(); + if (this.isPlayerFreeType()) { + return; + } + + for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { + if (fplayer.getFactionId().equalsIgnoreCase(id)) { + fplayers.add(fplayer); + } + } + } + + public boolean addFPlayer(FPlayer fplayer) { + return !this.isPlayerFreeType() && fplayers.add(fplayer); + } + + public boolean removeFPlayer(FPlayer fplayer) { + return !this.isPlayerFreeType() && (fplayers.remove(fplayer)); + } + + public int getSize() { + return getFPlayers().size(); + } + + public Set getFPlayers() { + // return a shallow copy of the FPlayer list, to prevent tampering and + // concurrency issues + Set set = new HashSet<>(fplayers); + return set.stream().filter(z -> z.getRole().isAtLeast(Role.RECRUIT)).collect(Collectors.toSet()); + } + + public Set getFPlayersWhereOnline(boolean online) { + Set ret = new HashSet<>(); + if (!this.isNormal()) { + return ret; + } + + for (FPlayer fplayer : fplayers) { + if (fplayer.isOnline() == online && fplayer.getRole().isAtLeast(Role.RECRUIT)) { + ret.add(fplayer); + } + } + + return ret; + } + + public Set getFPlayersWhereOnline(boolean online, FPlayer viewer) { + Set ret = new HashSet<>(); + if (!this.isNormal()) { + return ret; + } + + for (FPlayer viewed : fplayers) { + // Add if their online status is what we want + if (viewed.isOnline() == online && viewed.getRole().isAtLeast(Role.RECRUIT)) { + // If we want online, check to see if we are able to see this player + // This checks if they are in vanish. + if (online + && viewed.getPlayer() != null + && viewer.getPlayer() != null + && viewer.getPlayer().canSee(viewed.getPlayer())) { + ret.add(viewed); + // If we want offline, just add them. + // Prob a better way to do this but idk. + } else if (!online) { + ret.add(viewed); + } + } + } + + return ret; + } + + public FPlayer getFPlayerAdmin() { + if (!this.isNormal()) { + return null; + } + if(fPlayerAdmin == null || !fPlayerAdmin.getFactionId().equals(this.id) || fPlayerAdmin.getRole() != Role.ADMIN){ + recalcFPlayerAdmin(); + } + return fPlayerAdmin; + } + + @Override + public FPlayer getLeader() { + return getFPlayerAdmin(); + } + + public void recalcFPlayerAdmin(){ + for(FPlayer fPlayer : fplayers){ + if(fPlayer.getRole() == Role.ADMIN)fPlayerAdmin = fPlayer; + } + } + + public ArrayList getFPlayersWhereRole(Role role) { + ArrayList ret = new ArrayList<>(); + if (!this.isNormal()) { + return ret; + } + + for (FPlayer fplayer : fplayers) { + if (fplayer.getRole() == role) { + ret.add(fplayer); + } + } + + return ret; + } + + public ArrayList getOnlinePlayers() { + ArrayList ret = new ArrayList<>(); + if (this.isPlayerFreeType()) { + return ret; + } + + for (Player player : FactionsPlugin.getInstance().getServer().getOnlinePlayers()) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (fplayer.getFaction() == this && fplayer.getRole().isAtLeast(Role.RECRUIT)) { + ret.add(player); + } + } + + return ret; + } + + @Override + public Inventory getChest() { + if(inventory == null){ + this.inventory = Bukkit.createInventory(new FChestHolder(), + FactionsPlugin.getInstance().conf().upgrades().chest().getNumber(getUpgrade(UpgradeType.CHEST)) * 9, + TextUtil.parseColor(FactionsPlugin.getInstance().conf().upgrades().chest().getChestName())); + + try{ + this.inventory.setContents(ItemBase64.itemStackArrayFromBase64(this.items)); + }catch(IOException exc){ + exc.printStackTrace(); + + Bukkit.getLogger().severe("Not able to save " + this.getTag() + "'s chest data!"); + } + } + return inventory; + } + + // slightly faster check than getOnlinePlayers() if you just want to see if + // there are any players online + public boolean hasPlayersOnline() { + // only real factions can have players online, not safe zone / war zone + if (this.isPlayerFreeType()) { + return false; + } + + for (FPlayer player : fplayers) { + if (player != null && player.isOnline()) { + return true; + } + } + + // even if all players are technically logged off, maybe someone was on + // recently enough to not consider them officially offline yet + return FactionsPlugin.getInstance().conf().factions().other().getConsiderFactionsReallyOfflineAfterXMinutes() > 0 && System.currentTimeMillis() < lastPlayerLoggedOffTime + (FactionsPlugin.getInstance().conf().factions().other().getConsiderFactionsReallyOfflineAfterXMinutes() * 60000); + } + + public void memberLoggedOff() { + if (this.isNormal()) { + lastPlayerLoggedOffTime = System.currentTimeMillis(); + } + } + + public void setPayPal(String payPal){ + this.payPalLink = payPal; + } + + public String getPayPal(){ + return this.payPalLink; + } + + // used when current leader is about to be removed from the faction; + // promotes new leader, or disbands faction if no other members left + public void promoteNewLeader() { + if (!this.isNormal()) { + return; + } + if (this.isPermanent() && FactionsPlugin.getInstance().conf().factions().specialCase().isPermanentFactionsDisableLeaderPromotion()) { + return; + } + + FPlayer oldLeader = this.getFPlayerAdmin(); + + // get list of coleaders, or mods, or list of normal members if there are no moderators + ArrayList replacements = this.getFPlayersWhereRole(Role.COLEADER); + if (replacements == null || replacements.isEmpty()) { + replacements = this.getFPlayersWhereRole(Role.MODERATOR); + } + + if (replacements == null || replacements.isEmpty()) { + replacements = this.getFPlayersWhereRole(Role.NORMAL); + } + + if (replacements == null || replacements.isEmpty()) { // faction admin is the only member; one-man faction + if (this.isPermanent()) { + if (oldLeader != null) { + oldLeader.setRole(Role.NORMAL); + } + return; + } + + // no members left and faction isn't permanent, so disband it + if (FactionsPlugin.getInstance().conf().logging().isFactionDisband()) { + FactionsPlugin.getInstance().log("The faction " + this.getTag() + " (" + this.getId() + ") has been disbanded since it has no members left."); + } + + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.LEAVE_DISBANDED, this.getTag(fplayer)); + } + + FactionsPlugin.getInstance().getServer().getPluginManager().callEvent(new FactionAutoDisbandEvent(this)); + + Factions.getInstance().removeFaction(getId()); + } else { // promote new faction admin + if (oldLeader != null) { + oldLeader.setRole(Role.COLEADER); + } + replacements.get(0).setRole(Role.ADMIN); + fPlayerAdmin = replacements.get(0); + //TODO:TL + this.msg("Faction admin %s has been removed. %s has been promoted as the new faction admin.", oldLeader == null ? "" : oldLeader.getName(), replacements.get(0).getName()); + FactionsPlugin.getInstance().log("Faction " + this.getTag() + " (" + this.getId() + ") admin was removed. Replacement admin: " + replacements.get(0).getName()); + } + } + + // ----------------------------------------------// + // Messages + // ----------------------------------------------// + public void msg(String message, Object... args) { + message = FactionsPlugin.getInstance().txt().parse(message, args); + + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(message); + } + } + + public void msg(TL translation, Object... args) { + msg(translation.toString(), args); + } + + public void sendMessage(String message) { + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(message); + } + } + + public void sendMessage(List messages) { + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(messages); + } + } + + // ----------------------------------------------// + // Ownership of specific claims + // ----------------------------------------------// + + public Map> getClaimOwnership() { + return claimOwnership; + } + + public void clearAllClaimOwnership() { + claimOwnership.clear(); + } + + public void clearClaimOwnership(FLocation loc) { + claimOwnership.remove(loc); + } + + public void clearClaimOwnership(FPlayer player) { + if (id == null || id.isEmpty()) { + return; + } + + Set ownerData; + + for (Entry> entry : claimOwnership.entrySet()) { + ownerData = entry.getValue(); + + if (ownerData == null) { + continue; + } + + ownerData.removeIf(s -> s.equals(player.getId())); + + if (ownerData.isEmpty()) { + claimOwnership.remove(entry.getKey()); + } + } + } + + public int getCountOfClaimsWithOwners() { + return claimOwnership.isEmpty() ? 0 : claimOwnership.size(); + } + + public boolean doesLocationHaveOwnersSet(FLocation loc) { + if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) { + return false; + } + + Set ownerData = claimOwnership.get(loc); + return ownerData != null && !ownerData.isEmpty(); + } + + public boolean isPlayerInOwnerList(FPlayer player, FLocation loc) { + if (claimOwnership.isEmpty()) { + return false; + } + Set ownerData = claimOwnership.get(loc); + return ownerData != null && ownerData.contains(player.getId()); + } + + public void setPlayerAsOwner(FPlayer player, FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null) { + ownerData = new HashSet<>(); + } + ownerData.add(player.getId()); + claimOwnership.put(loc, ownerData); + } + + public void removePlayerAsOwner(FPlayer player, FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null) { + return; + } + ownerData.remove(player.getId()); + claimOwnership.put(loc, ownerData); + } + + public int getMaxTNT(){ + if(!FactionsPlugin.getInstance().conf().upgrades().isEnabled())return FactionsPlugin.getInstance().conf().commands().tnt().getMaxStorage(); + return FactionsPlugin.getInstance().conf().upgrades().tnt().getNumber(this.getUpgrade(UpgradeType.TNT)); + } + + public Set getOwnerList(FLocation loc) { + return claimOwnership.get(loc); + } + + public String getOwnerListString(FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null || ownerData.isEmpty()) { + return ""; + } + + StringBuilder ownerList = new StringBuilder(); + + for (String anOwnerData : ownerData) { + if (ownerList.length() > 0) { + ownerList.append(", "); + } + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(anOwnerData)); + //TODO:TL + ownerList.append(offlinePlayer != null ? offlinePlayer.getName() : "null player"); + } + return ownerList.toString(); + } + + public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) { + // in own faction, with sufficient role or permission to bypass + // ownership? + if (fplayer.getFaction() == this && (fplayer.getRole().isAtLeast(FactionsPlugin.getInstance().conf().factions().ownedArea().isModeratorsBypass() ? Role.MODERATOR : Role.ADMIN) || Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()))) { + return true; + } + + // make sure claimOwnership is initialized + if (claimOwnership.isEmpty()) { + return true; + } + + // need to check the ownership list, then + Set ownerData = claimOwnership.get(loc); + + // if no owner list, owner list is empty, or player is in owner list, + // they're allowed + return ownerData == null || ownerData.isEmpty() || ownerData.contains(fplayer.getId()); + } + + //Upgrades + public void commitUpgrade(UpgradeType upgradeType){ + switch(upgradeType){ + case CHEST: + int slots = FactionsPlugin.getInstance().conf().upgrades().chest().getNumber(getUpgrade(upgradeType)) * 9; + + ItemStack[] stacks = this.getChest().getContents(); + + List viewers = new ArrayList<>(this.getChest().getViewers()); + + for(HumanEntity entity : viewers){ + entity.closeInventory(); + } + + Inventory inventory = Bukkit.createInventory(new FChestHolder(), slots, + TextUtil.parseColor(FactionsPlugin.getInstance().conf().upgrades().chest().getChestName())); + + for(int z = 0; z < stacks.length; z++){ + inventory.setItem(z, stacks[z]); + } + + this.inventory = inventory; + + this.items = ItemBase64.itemStackArrayToBase64(this.inventory.getContents()); + return; + } + } + + public int getUpgrade(UpgradeType type){ + return upgrades.getOrDefault(type, 0); + } + + public boolean doUpgrade(UpgradeType type, FPlayer user){ + int maxLevel; + int currentLevel; + long money; + int cost; + switch(type){ + case TNT: + maxLevel = FactionsPlugin.getInstance().conf().upgrades().tnt().getLevels().size(); + + currentLevel = getUpgrade(type); + + if(currentLevel + 1 > maxLevel){ + user.msg(TL.COMMAND_UPGRADE_ALREADY_MAX); + return false; + } + + money = (long) Econ.getBalance(user); + + cost = FactionsPlugin.getInstance().conf().upgrades().tnt().getCost(currentLevel + 1); + + if(cost > money){ + user.msg(TL.COMMAND_UPGRADE_NOT_ENOUGH); + return false; + } + + Econ.withdraw(user, cost); + + user.msg(TL.COMMAND_UPGRADE_SUCCESSFUL, "TNT", currentLevel + 1); + + this.upgrades.put(type, currentLevel + 1); + return true; + case CHEST: + maxLevel = FactionsPlugin.getInstance().conf().upgrades().chest().getLevels().size(); + + currentLevel = getUpgrade(type); + + if(currentLevel + 1 > maxLevel){ + user.msg(TL.COMMAND_UPGRADE_ALREADY_MAX); + return false; + } + + money = (long) Econ.getBalance(user); + + cost = FactionsPlugin.getInstance().conf().upgrades().chest().getCost(currentLevel + 1); + + if(cost > money){ + user.msg(TL.COMMAND_UPGRADE_NOT_ENOUGH); + return false; + } + + Econ.withdraw(user, cost); + + user.msg(TL.COMMAND_UPGRADE_SUCCESSFUL, "Chest", currentLevel + 1); + + this.upgrades.put(type, currentLevel + 1); + return true; + + case WARP_AMOUNT: + maxLevel = FactionsPlugin.getInstance().conf().upgrades().warpAmount().getLevels().size(); + + currentLevel = getUpgrade(type); + + if(currentLevel + 1 > maxLevel){ + user.msg(TL.COMMAND_UPGRADE_ALREADY_MAX); + return false; + } + + money = (long) Econ.getBalance(user); + + cost = FactionsPlugin.getInstance().conf().upgrades().warpAmount().getCost(currentLevel + 1); + + if(cost > money){ + user.msg(TL.COMMAND_UPGRADE_NOT_ENOUGH); + return false; + } + + Econ.withdraw(user, cost); + + user.msg(TL.COMMAND_UPGRADE_SUCCESSFUL, "Warp Amount", currentLevel + 1); + + this.upgrades.put(type, currentLevel + 1); + return true; + + case FACTION_SIZE: + maxLevel = FactionsPlugin.getInstance().conf().upgrades().factionSize().getLevels().size(); + + currentLevel = getUpgrade(type); + + if(currentLevel + 1 > maxLevel){ + user.msg(TL.COMMAND_UPGRADE_ALREADY_MAX); + return false; + } + + money = (long) Econ.getBalance(user); + + cost = FactionsPlugin.getInstance().conf().upgrades().factionSize().getCost(currentLevel + 1); + + if(cost > money){ + user.msg(TL.COMMAND_UPGRADE_NOT_ENOUGH); + return false; + } + + Econ.withdraw(user, cost); + + user.msg(TL.COMMAND_UPGRADE_SUCCESSFUL, "Faction Size", currentLevel + 1); + + this.upgrades.put(type, currentLevel + 1); + return true; +/* case SPAWNER_BOOST: + maxLevel = FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().getLevels().size(); + + currentLevel = getUpgrade(type); + + if(currentLevel + 1 > maxLevel){ + user.msg(TL.COMMAND_UPGRADE_ALREADY_MAX); + return false; + } + + money = (long) Econ.getBalance(user); + + cost = FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().getCost(currentLevel + 1); + + if(cost > money){ + user.msg(TL.COMMAND_UPGRADE_NOT_ENOUGH); + return false; + } + + Econ.withdraw(user, cost); + + user.msg(TL.COMMAND_UPGRADE_SUCCESSFUL, "Spawner Boost", currentLevel + 1); + + this.upgrades.put(type, currentLevel + 1); + return true; + case CROP_BOOST: + maxLevel = FactionsPlugin.getInstance().conf().upgrades().warpAmount().getLevels().size(); + + currentLevel = getUpgrade(type); + + if(currentLevel + 1 > maxLevel){ + user.msg(TL.COMMAND_UPGRADE_ALREADY_MAX); + return false; + } + + money = (long) Econ.getBalance(user); + + cost = FactionsPlugin.getInstance().conf().upgrades().warpAmount().getCost(currentLevel + 1); + + if(cost > money){ + user.msg(TL.COMMAND_UPGRADE_NOT_ENOUGH); + return false; + } + + Econ.withdraw(user, cost); + + user.msg(TL.COMMAND_UPGRADE_SUCCESSFUL, "Crop Boost", currentLevel + 1); + + this.upgrades.put(type, currentLevel + 1); + return true;*/ + } + return false; + } + + // ----------------------------------------------// + // Persistance and entity management + // ----------------------------------------------// + public void remove() { + if (Econ.shouldBeUsed()) { + Econ.setBalance(this, 0); + } + + // Clean the board + ((MemoryBoard) Board.getInstance()).clean(id); + + for (FPlayer fPlayer : fplayers) { + fPlayer.resetFactionData(false); + } + } + + public Set getAllClaims() { + return Board.getInstance().getAllClaims(this); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/MemoryFactions.java b/Factions/src/main/java/com/massivecraft/factions/data/MemoryFactions.java new file mode 100644 index 0000000..6295f3d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/MemoryFactions.java @@ -0,0 +1,177 @@ +package com.massivecraft.factions.data; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.util.MiscUtil; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public abstract class MemoryFactions extends Factions { + public final Map factions = new ConcurrentHashMap<>(); + public int nextId = 1; + + public int load() { + // Make sure the default neutral faction exists + if (!factions.containsKey("0")) { + Faction faction = generateFactionObject("0"); + factions.put("0", faction); + faction.setTag(TL.WILDERNESS.toString()); + faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("0"); + if (!faction.getTag().equalsIgnoreCase(TL.WILDERNESS.toString())) { + faction.setTag(TL.WILDERNESS.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) { + faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); + } + } + + // Make sure the safe zone faction exists + if (!factions.containsKey("-1")) { + Faction faction = generateFactionObject("-1"); + factions.put("-1", faction); + faction.setTag(TL.SAFEZONE.toString()); + faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("-1"); + if (!faction.getTag().equalsIgnoreCase(TL.SAFEZONE.toString())) { + faction.setTag(TL.SAFEZONE.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) { + faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); + } + // if SafeZone has old pre-1.6.0 name, rename it to remove troublesome " " + if (faction.getTag().contains(" ")) { + faction.setTag(TL.SAFEZONE.toString()); + } + } + + // Make sure the war zone faction exists + if (!factions.containsKey("-2")) { + Faction faction = generateFactionObject("-2"); + factions.put("-2", faction); + faction.setTag(TL.WARZONE.toString()); + faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("-2"); + if (!faction.getTag().equalsIgnoreCase(TL.WARZONE.toString())) { + faction.setTag(TL.WARZONE.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) { + faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); + } + // if WarZone has old pre-1.6.0 name, rename it to remove troublesome " " + if (faction.getTag().contains(" ")) { + faction.setTag(TL.WARZONE.toString()); + } + } + return 0; + } + + public Faction getFactionById(String id) { + return factions.get(id); + } + + public abstract Faction generateFactionObject(String string); + + public Faction getByTag(String str) { + String compStr = MiscUtil.getComparisonString(str); + for (Faction faction : factions.values()) { + if (faction.getComparisonTag().equals(compStr)) { + return faction; + } + } + return null; + } + + public Faction getBestTagMatch(String start) { + int best = 0; + start = start.toLowerCase(); + int minlength = start.length(); + Faction bestMatch = null; + for (Faction faction : factions.values()) { + String candidate = faction.getTag(); + candidate = ChatColor.stripColor(candidate); + if (candidate.length() < minlength) { + continue; + } + if (!candidate.toLowerCase().startsWith(start)) { + continue; + } + + // The closer to zero the better + int lendiff = candidate.length() - minlength; + if (lendiff == 0) { + return faction; + } + if (lendiff < best || best == 0) { + best = lendiff; + bestMatch = faction; + } + } + + return bestMatch; + } + + public boolean isTagTaken(String str) { + return this.getByTag(str) != null; + } + + public boolean isValidFactionId(String id) { + return factions.containsKey(id); + } + + public Faction createFaction() { + Faction faction = generateFactionObject(); + factions.put(faction.getId(), faction); + return faction; + } + + public Set getFactionTags() { + Set tags = new HashSet<>(); + for (Faction faction : factions.values()) { + tags.add(faction.getTag()); + } + return tags; + } + + public abstract Faction generateFactionObject(); + + public void removeFaction(String id) { + factions.remove(id).remove(); + } + + @Override + public ArrayList getAllFactions() { + return new ArrayList<>(factions.values()); + } + + @Override + public Faction getNone() { + return factions.get("0"); + } + + @Override + public Faction getWilderness() { + return factions.get("0"); + } + + @Override + public Faction getSafeZone() { + return factions.get("-1"); + } + + @Override + public Faction getWarZone() { + return factions.get("-2"); + } + + public abstract void convertFrom(MemoryFactions old); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/SaveTask.java b/Factions/src/main/java/com/massivecraft/factions/data/SaveTask.java new file mode 100644 index 0000000..b471de2 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/SaveTask.java @@ -0,0 +1,28 @@ +package com.massivecraft.factions.data; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; + +public class SaveTask implements Runnable { + + private static boolean running = false; + + private final FactionsPlugin plugin; + + public SaveTask(FactionsPlugin plugin) { + this.plugin = plugin; + } + + public void run() { + if (!plugin.getAutoSave() || running) { + return; + } + running = true; + Factions.getInstance().forceSave(false); + FPlayers.getInstance().forceSave(false); + Board.getInstance().forceSave(false); + running = false; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/json/JSONBoard.java b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONBoard.java new file mode 100644 index 0000000..605b27e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONBoard.java @@ -0,0 +1,100 @@ +package com.massivecraft.factions.data.json; + +import com.google.gson.reflect.TypeToken; +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.data.MemoryBoard; +import com.massivecraft.factions.util.DiscUtil; + +import java.io.File; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; +import java.util.logging.Level; + + +public class JSONBoard extends MemoryBoard { + private static final transient File file = new File(FactionsPlugin.getInstance().getDataFolder(), "data/board.json"); + + // -------------------------------------------- // + // Persistance + // -------------------------------------------- // + + public Map> dumpAsSaveFormat() { + Map> worldCoordIds = new HashMap<>(); + + String worldName, coords; + String id; + + for (Entry entry : flocationIds.entrySet()) { + worldName = entry.getKey().getWorldName(); + coords = entry.getKey().getCoordString(); + id = entry.getValue(); + if (!worldCoordIds.containsKey(worldName)) { + worldCoordIds.put(worldName, new TreeMap<>()); + } + + worldCoordIds.get(worldName).put(coords, id); + } + + return worldCoordIds; + } + + public void loadFromSaveFormat(Map> worldCoordIds) { + flocationIds.clear(); + + String worldName; + String[] coords; + int x, z; + String factionId; + + for (Entry> entry : worldCoordIds.entrySet()) { + worldName = entry.getKey(); + for (Entry entry2 : entry.getValue().entrySet()) { + coords = entry2.getKey().trim().split("[,\\s]+"); + x = Integer.parseInt(coords[0]); + z = Integer.parseInt(coords[1]); + factionId = entry2.getValue(); + flocationIds.put(new FLocation(worldName, x, z), factionId); + } + } + } + + public void forceSave() { + forceSave(true); + } + + public void forceSave(boolean sync) { + DiscUtil.writeCatch(file, FactionsPlugin.getInstance().getGson().toJson(dumpAsSaveFormat()), sync); + } + + public int load() { + if (!file.exists()) { + FactionsPlugin.getInstance().getLogger().info("No board to load from disk. Creating new file."); + forceSave(); + return 0; + } + + try { + Type type = new TypeToken>>() { + }.getType(); + Map> worldCoordIds = FactionsPlugin.getInstance().getGson().fromJson(DiscUtil.read(file), type); + loadFromSaveFormat(worldCoordIds); + } catch (Exception e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to load the board from disk.", e); + return 0; + } + + return flocationIds.size(); + } + + @Override + public void convertFrom(MemoryBoard old) { + this.flocationIds = old.flocationIds; + forceSave(); + Board.instance = this; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFPlayer.java b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFPlayer.java new file mode 100644 index 0000000..03fc67b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFPlayer.java @@ -0,0 +1,29 @@ +package com.massivecraft.factions.data.json; + +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.data.MemoryFPlayer; +import com.massivecraft.factions.landraidcontrol.PowerControl; + +public class JSONFPlayer extends MemoryFPlayer { + + public JSONFPlayer(MemoryFPlayer arg0) { + super(arg0); + } + + public JSONFPlayer(String id) { + super(id); + } + + @Override + public void remove() { + ((JSONFPlayers) FPlayers.getInstance()).fPlayers.remove(getId()); + } + + public boolean shouldBeSaved() { + return this.hasFaction() || + (FactionsPlugin.getInstance().getLandRaidControl() instanceof PowerControl && + (this.getPowerRounded() != this.getPowerMaxRounded() && + this.getPowerRounded() != (int) Math.round(FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getPlayerStarting()))); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFPlayers.java b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFPlayers.java new file mode 100644 index 0000000..498ef7b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFPlayers.java @@ -0,0 +1,187 @@ +package com.massivecraft.factions.data.json; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.data.MemoryFPlayer; +import com.massivecraft.factions.data.MemoryFPlayers; +import com.massivecraft.factions.util.DiscUtil; +import com.massivecraft.factions.util.UUIDFetcher; +import org.apache.commons.lang.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Level; + +public class JSONFPlayers extends MemoryFPlayers { + public Gson getGson() { + return FactionsPlugin.getInstance().getGson(); + } + + public void setGson(Gson gson) { + // NOOP + } + + private final File file; + + public JSONFPlayers() { + if (FactionsPlugin.getInstance().getServerUUID() == null) { + FactionsPlugin.getInstance().grumpException(new RuntimeException()); + } + file = new File(FactionsPlugin.getInstance().getDataFolder(), "data/players.json"); + } + + public void convertFrom(MemoryFPlayers old) { + old.fPlayers.forEach((id, faction) -> this.fPlayers.put(id, new JSONFPlayer((MemoryFPlayer) faction))); + forceSave(); + FPlayers.instance = this; + } + + public void forceSave() { + forceSave(true); + } + + public void forceSave(boolean sync) { + final Map entitiesThatShouldBeSaved = new HashMap<>(); + for (FPlayer entity : this.fPlayers.values()) { + if (((MemoryFPlayer) entity).shouldBeSaved()) { + entitiesThatShouldBeSaved.put(entity.getId(), (JSONFPlayer) entity); + } + } + + saveCore(file, entitiesThatShouldBeSaved, sync); + } + + private boolean saveCore(File target, Map data, boolean sync) { + return DiscUtil.writeCatch(target, FactionsPlugin.getInstance().getGson().toJson(data), sync); + } + + public int load() { + Map fplayers = this.loadCore(); + if (fplayers == null) { + return 0; + } + this.fPlayers.clear(); + this.fPlayers.putAll(fplayers); + return fPlayers.size(); + } + + private Map loadCore() { + if (!this.file.exists()) { + return new HashMap<>(); + } + + String content = DiscUtil.readCatch(this.file); + if (content == null) { + return null; + } + + Map data = FactionsPlugin.getInstance().getGson().fromJson(content, new TypeToken>() { + }.getType()); + Set list = new HashSet<>(); + Set invalidList = new HashSet<>(); + for (Entry entry : data.entrySet()) { + String key = entry.getKey(); + entry.getValue().setId(key); + if (doesKeyNeedMigration(key)) { + if (!isKeyInvalid(key)) { + list.add(key); + } else { + invalidList.add(key); + } + } + } + + if (list.size() > 0) { + // We've got some converting to do! + FactionsPlugin.getInstance().log(Level.INFO, "Factions is now updating players.json"); + + // First we'll make a backup, because god forbid anybody heed a + // warning + File file = new File(this.file.getParentFile(), "players.json.old"); + try { + file.createNewFile(); + } catch (IOException e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to create file players.json.old", e); + } + saveCore(file, data, true); + FactionsPlugin.getInstance().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); + + // Start fetching those UUIDs + FactionsPlugin.getInstance().log(Level.INFO, "Please wait while Factions converts " + list.size() + " old player names to UUID. This may take a while."); + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String s : list) { + // Are we missing any responses? + if (!response.containsKey(s)) { + // They don't have a UUID so they should just be removed + invalidList.add(s); + } + } + for (String value : response.keySet()) { + // For all the valid responses, let's replace their old + // named entry with a UUID key + String id = response.get(value).toString(); + + JSONFPlayer player = data.get(value); + + if (player == null) { + // The player never existed here, and shouldn't persist + invalidList.add(value); + continue; + } + + player.setId(id); // Update the object so it knows + + data.remove(value); // Out with the old... + data.put(id, player); // And in with the new + } + } catch (Exception e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed name to UUID conversion", e); + } + if (invalidList.size() > 0) { + for (String name : invalidList) { + // Remove all the invalid names we collected + data.remove(name); + } + FactionsPlugin.getInstance().log(Level.INFO, "While converting we found names that either don't have a UUID or aren't players and removed them from storage."); + FactionsPlugin.getInstance().log(Level.INFO, "The following names were detected as being invalid: " + StringUtils.join(invalidList, ", ")); + } + saveCore(this.file, data, true); // Update the + // flatfile + FactionsPlugin.getInstance().log(Level.INFO, "Done converting players.json to UUID."); + } + return data; + } + + private boolean doesKeyNeedMigration(String key) { + if (!key.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + // Not a valid UUID.. + // Valid playername, we'll mark this as one for conversion + // to UUID + return key.matches("[a-zA-Z0-9_]{2,16}"); + } + return false; + } + + private boolean isKeyInvalid(String key) { + return !key.matches("[a-zA-Z0-9_]{2,16}"); + } + + @Override + public FPlayer generateFPlayer(String id) { + FPlayer player = new JSONFPlayer(id); + this.fPlayers.put(player.getId(), player); + return player; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFaction.java b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFaction.java new file mode 100644 index 0000000..0b050e3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFaction.java @@ -0,0 +1,18 @@ +package com.massivecraft.factions.data.json; + +import com.massivecraft.factions.data.MemoryFaction; +import org.bukkit.inventory.Inventory; + +public class JSONFaction extends MemoryFaction { + + public JSONFaction(MemoryFaction arg0) { + super(arg0); + } + + private JSONFaction() { + } + + public JSONFaction(String id) { + super(id); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFactions.java b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFactions.java new file mode 100644 index 0000000..317d326 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/data/json/JSONFactions.java @@ -0,0 +1,253 @@ +package com.massivecraft.factions.data.json; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.data.MemoryFaction; +import com.massivecraft.factions.data.MemoryFactions; +import com.massivecraft.factions.util.DiscUtil; +import com.massivecraft.factions.util.UUIDFetcher; +import org.bukkit.inventory.ItemStack; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Level; + +public class JSONFactions extends MemoryFactions { + public Gson getGson() { + return FactionsPlugin.getInstance().getGson(); + } + + private final File file; + + public File getFile() { + return file; + } + + // -------------------------------------------- // + // CONSTRUCTORS + // -------------------------------------------- // + + public JSONFactions() { + if (FactionsPlugin.getInstance().getServerUUID() == null) { + FactionsPlugin.getInstance().grumpException(new RuntimeException()); + } + this.file = new File(FactionsPlugin.getInstance().getDataFolder(), "data/factions.json"); + this.nextId = 1; + } + + public void forceSave() { + forceSave(true); + } + + public void forceSave(boolean sync) { + final Map entitiesThatShouldBeSaved = new HashMap<>(); + for (Faction entity : this.factions.values()) { + ((MemoryFaction) entity).setItems(); + entitiesThatShouldBeSaved.put(entity.getId(), (JSONFaction) entity); + } + + saveCore(file, entitiesThatShouldBeSaved, sync); + } + + private boolean saveCore(File target, Map entities, boolean sync) { + return DiscUtil.writeCatch(target, FactionsPlugin.getInstance().getGson().toJson(entities), sync); + } + + public int load() { + Map factions = this.loadCore(); + if (factions == null) { + return 0; + } + this.factions.putAll(factions); + + super.load(); + return factions.size(); + } + + private Map loadCore() { + if (!this.file.exists()) { + return new HashMap<>(); + } + + String content = DiscUtil.readCatch(this.file); + if (content == null) { + return null; + } + + Map data = FactionsPlugin.getInstance().getGson().fromJson(content, new TypeToken>() { + }.getType()); + + this.nextId = 1; + // Do we have any names that need updating in claims or invites? + + int needsUpdate = 0; + for (Entry entry : data.entrySet()) { + String id = entry.getKey(); + Faction f = entry.getValue(); + f.checkPerms(); + f.setId(id); + this.updateNextIdForId(id); + needsUpdate += whichKeysNeedMigration(f.getInvites()).size(); + for (Set keys : f.getClaimOwnership().values()) { + needsUpdate += whichKeysNeedMigration(keys).size(); + } + } + + if (needsUpdate > 0) { + // We've got some converting to do! + FactionsPlugin.getInstance().log(Level.INFO, "Factions is now updating factions.json"); + + // First we'll make a backup, because god forbid anybody heed a + // warning + File file = new File(this.file.getParentFile(), "factions.json.old"); + try { + file.createNewFile(); + } catch (IOException e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to create file factions.json.old", e); + } + saveCore(file, data, true); + FactionsPlugin.getInstance().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); + + FactionsPlugin.getInstance().log(Level.INFO, "Please wait while Factions converts " + needsUpdate + " old player names to UUID. This may take a while."); + + // Update claim ownership + + for (String string : data.keySet()) { + Faction f = data.get(string); + Map> claims = f.getClaimOwnership(); + for (FLocation key : claims.keySet()) { + Set set = claims.get(key); + + Set list = whichKeysNeedMigration(set); + + if (list.size() > 0) { + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String value : response.keySet()) { + // Let's replace their old named entry with a + // UUID key + String id = response.get(value).toString(); + set.remove(value.toLowerCase()); // Out with the + // old... + set.add(id); // And in with the new + } + } catch (Exception e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Encountered exception looking up UUIDs", e); + } + claims.put(key, set); // Update + } + } + } + + // Update invites + + for (String string : data.keySet()) { + Faction f = data.get(string); + Set invites = f.getInvites(); + Set list = whichKeysNeedMigration(invites); + + if (list.size() > 0) { + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String value : response.keySet()) { + // Let's replace their old named entry with a UUID + // key + String id = response.get(value).toString(); + invites.remove(value.toLowerCase()); // Out with the + // old... + invites.add(id); // And in with the new + } + } catch (Exception e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Encountered exception looking up UUIDs", e); + } + } + } + + saveCore(this.file, data, true); // Update the flatfile + FactionsPlugin.getInstance().log(Level.INFO, "Done converting factions.json to UUID."); + } + return data; + } + + private Set whichKeysNeedMigration(Set keys) { + HashSet list = new HashSet<>(); + for (String value : keys) { + if (!value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + // Not a valid UUID.. + if (value.matches("[a-zA-Z0-9_]{2,16}")) { + // Valid playername, we'll mark this as one for conversion + // to UUID + list.add(value); + } + } + } + return list; + } + + // -------------------------------------------- // + // ID MANAGEMENT + // -------------------------------------------- // + + public String getNextId() { + while (!isIdFree(this.nextId)) { + this.nextId += 1; + } + return Integer.toString(this.nextId); + } + + public boolean isIdFree(String id) { + return !this.factions.containsKey(id); + } + + public boolean isIdFree(int id) { + return this.isIdFree(Integer.toString(id)); + } + + protected synchronized void updateNextIdForId(int id) { + if (this.nextId < id) { + this.nextId = id + 1; + } + } + + protected void updateNextIdForId(String id) { + try { + int idAsInt = Integer.parseInt(id); + this.updateNextIdForId(idAsInt); + } catch (Exception ignored) { + } + } + + @Override + public Faction generateFactionObject() { + String id = getNextId(); + Faction faction = new JSONFaction(id); + updateNextIdForId(id); + return faction; + } + + @Override + public Faction generateFactionObject(String id) { + return new JSONFaction(id); + } + + @Override + public void convertFrom(MemoryFactions old) { + old.factions.forEach((tag, faction) -> this.factions.put(tag, new JSONFaction((MemoryFaction) faction))); + this.nextId = old.nextId; + forceSave(); + Factions.instance = this; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/DTRLossEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/DTRLossEvent.java new file mode 100644 index 0000000..a02d1ac --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/DTRLossEvent.java @@ -0,0 +1,62 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +/** + * Event called when a player loses dtr. + */ +public class DTRLossEvent extends FactionPlayerEvent implements Cancellable { + + private boolean cancelled = false; + + public DTRLossEvent(Faction f, FPlayer p) { + super(f, p); + } + + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } + + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } + + /** + * Get the Player involved in the event. + * + * @return Player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java new file mode 100644 index 0000000..6ce76cc --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java @@ -0,0 +1,42 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.event.Cancellable; + +/** + * Event called when an FPlayer joins a Faction. + */ +public class FPlayerJoinEvent extends FactionPlayerEvent implements Cancellable { + + private final PlayerJoinReason reason; + private boolean cancelled = false; + + public enum PlayerJoinReason { + CREATE, LEADER, COMMAND + } + + public FPlayerJoinEvent(FPlayer fp, Faction f, PlayerJoinReason r) { + super(f, fp); + reason = r; + } + + /** + * Get the reason the player joined the faction. + * + * @return reason player joined the faction. + */ + public PlayerJoinReason getReason() { + return reason; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + cancelled = c; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java new file mode 100644 index 0000000..18764a2 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java @@ -0,0 +1,40 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.event.Cancellable; + +public class FPlayerLeaveEvent extends FactionPlayerEvent implements Cancellable { + + private final PlayerLeaveReason reason; + boolean cancelled = false; + + public enum PlayerLeaveReason { + KICKED, DISBAND, RESET, JOINOTHER, LEAVE, BANNED + } + + public FPlayerLeaveEvent(FPlayer p, Faction f, PlayerLeaveReason r) { + super(f, p); + reason = r; + } + + /** + * Get the reason the player left the faction. + * + * @return reason player left the faction. + */ + public PlayerLeaveReason getReason() { + return reason; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + // Don't let them cancel factions disbanding. + cancelled = reason != PlayerLeaveReason.DISBAND && reason != PlayerLeaveReason.RESET && c; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FPlayerTeleportEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FPlayerTeleportEvent.java new file mode 100644 index 0000000..0a07702 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FPlayerTeleportEvent.java @@ -0,0 +1,51 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import org.bukkit.Location; +import org.bukkit.event.Cancellable; + +public class FPlayerTeleportEvent extends FactionPlayerEvent implements Cancellable { + + private final PlayerTeleportReason reason; + private boolean cancelled = false; + private final Location location; + + public enum PlayerTeleportReason { + HOME, AHOME, WARP, STUCK + } + + public FPlayerTeleportEvent(FPlayer p, Location location, FPlayerTeleportEvent.PlayerTeleportReason r) { + super(p.getFaction(), p); + reason = r; + this.location = location; + } + + /** + * Get the reason the player is teleporting. + * + * @return reason player is teleporting. + */ + public FPlayerTeleportEvent.PlayerTeleportReason getReason() { + return reason; + } + + /** + * Gets the destination, if known before starting to teleport. + * + * @return destination unless STUCK + */ + public Location getDestination() { + return location; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + cancelled = c; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionAttemptCreateEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionAttemptCreateEvent.java new file mode 100644 index 0000000..fb8f0a1 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionAttemptCreateEvent.java @@ -0,0 +1,53 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Event called when a Faction is soon to be created. + */ +public class FactionAttemptCreateEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private final String factionTag; + private final Player sender; + private boolean cancelled; + + public FactionAttemptCreateEvent(Player sender, String tag) { + this.factionTag = tag; + this.sender = sender; + } + + public FPlayer getFPlayer() { + return FPlayers.getInstance().getByPlayer(sender); + } + + @Deprecated + public String getFactionTag() { + return factionTag; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionAutoDisbandEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionAutoDisbandEvent.java new file mode 100644 index 0000000..49b12e1 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionAutoDisbandEvent.java @@ -0,0 +1,12 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.Faction; + +/** + * Event called when a faction is disbanded automatically. + */ +public class FactionAutoDisbandEvent extends FactionEvent { + public FactionAutoDisbandEvent(Faction faction) { + super(faction); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java new file mode 100644 index 0000000..c0d5f4a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java @@ -0,0 +1,49 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Event called when a Faction is created. + */ +public class FactionCreateEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + + private final String factionTag; + private final Player sender; + private final Faction faction; + + public FactionCreateEvent(Player sender, String tag, Faction faction) { + this.factionTag = tag; + this.sender = sender; + this.faction = faction; + } + + public FPlayer getFPlayer() { + return FPlayers.getInstance().getByPlayer(sender); + } + + @Deprecated + public String getFactionTag() { + return factionTag; + } + + public Faction getFaction() { + return this.faction; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java new file mode 100644 index 0000000..50b212b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java @@ -0,0 +1,39 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Factions; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +/** + * Event called when a faction is disbanded. + */ +public class FactionDisbandEvent extends FactionEvent implements Cancellable { + + private boolean cancelled = false; + private final Player sender; + + public FactionDisbandEvent(Player sender, String factionId) { + super(Factions.getInstance().getFactionById(factionId)); + this.sender = sender; + } + + public FPlayer getFPlayer() { + return FPlayers.getInstance().getByPlayer(sender); + } + + public Player getPlayer() { + return sender; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + cancelled = c; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionEvent.java new file mode 100644 index 0000000..53c87fd --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionEvent.java @@ -0,0 +1,36 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.Faction; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Represents an event involving a Faction. + */ +public class FactionEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final Faction faction; + + public FactionEvent(Faction faction) { + this.faction = faction; + } + + /** + * Get the Faction involved in the event. + * + * @return faction involved in the event. + */ + public Faction getFaction() { + return this.faction; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionPlayerEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionPlayerEvent.java new file mode 100644 index 0000000..8a2552d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionPlayerEvent.java @@ -0,0 +1,21 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; + +/** + * Represents an event involving a Faction and a FPlayer. + */ +public class FactionPlayerEvent extends FactionEvent { + + private final FPlayer fPlayer; + + public FactionPlayerEvent(Faction faction, FPlayer fPlayer) { + super(faction); + this.fPlayer = fPlayer; + } + + public FPlayer getfPlayer() { + return this.fPlayer; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java new file mode 100644 index 0000000..3f160bb --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java @@ -0,0 +1,50 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.perms.Relation; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Event called when a Faction relation is called. + */ +public class FactionRelationEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + + private final Faction fsender; + private final Faction ftarget; + private final Relation foldrel; + private final Relation frel; + + public FactionRelationEvent(Faction sender, Faction target, Relation oldrel, Relation rel) { + fsender = sender; + ftarget = target; + foldrel = oldrel; + frel = rel; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Relation getOldRelation() { + return foldrel; + } + + public Relation getRelation() { + return frel; + } + + public Faction getFaction() { + return fsender; + } + + public Faction getTargetFaction() { + return ftarget; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionRelationWishEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionRelationWishEvent.java new file mode 100644 index 0000000..5fcef4a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionRelationWishEvent.java @@ -0,0 +1,44 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.perms.Relation; +import org.bukkit.event.Cancellable; + +public class FactionRelationWishEvent extends FactionPlayerEvent implements Cancellable { + private final Faction targetFaction; + private final Relation currentRelation; + private final Relation targetRelation; + + private boolean cancelled; + + public FactionRelationWishEvent(FPlayer caller, Faction sender, Faction targetFaction, Relation currentRelation, Relation targetRelation) { + super(sender, caller); + + this.targetFaction = targetFaction; + this.currentRelation = currentRelation; + this.targetRelation = targetRelation; + } + + public Faction getTargetFaction() { + return targetFaction; + } + + public Relation getCurrentRelation() { + return currentRelation; + } + + public Relation getTargetRelation() { + return targetRelation; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java new file mode 100644 index 0000000..eaf0653 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java @@ -0,0 +1,57 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +public class FactionRenameEvent extends FactionPlayerEvent implements Cancellable { + + private boolean cancelled = false; + private final String tag; + + public FactionRenameEvent(FPlayer sender, String newTag) { + super(sender.getFaction(), sender); + tag = newTag; + } + + /** + * Get the player involved in the event. + * + * @return Player involved in the event. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } + + /** + * Get the faction tag before it was renamed. + * + * @return old faction tag. + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getOldFactionTag() { + return getFaction().getTag(); + } + + /** + * Get the new faction tag. + * + * @return new faction tag as String. + */ + public String getFactionTag() { + return tag; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java new file mode 100644 index 0000000..eaaa698 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java @@ -0,0 +1,74 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +/** + * Event called when an FPlayer claims land for a Faction. + */ +public class LandClaimEvent extends FactionPlayerEvent implements Cancellable { + + private boolean cancelled; + private final FLocation location; + + public LandClaimEvent(FLocation loc, Faction f, FPlayer p) { + super(f, p); + cancelled = false; + location = loc; + } + + /** + * Get the FLocation involved in this event. + * + * @return the FLocation (also a chunk) involved in this event. + */ + public FLocation getLocation() { + return this.location; + } + + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } + + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } + + /** + * Get the Player involved in this event. + * + * @return player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/LandClaimRadiusEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/LandClaimRadiusEvent.java new file mode 100644 index 0000000..c9e6d66 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/LandClaimRadiusEvent.java @@ -0,0 +1,78 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +public class LandClaimRadiusEvent extends FactionPlayerEvent implements Cancellable { + + private boolean cancelled; + private final FLocation location; + private final int radius; + + public LandClaimRadiusEvent(FLocation loc, int rad, Faction f, FPlayer p) { + super(f, p); + cancelled = false; + location = loc; + radius = rad; + } + + /** + * Get the FLocation involved in this event. + * + * @return the FLocation (also a chunk) involved in this event. + */ + public FLocation getLocation() { + return this.location; + } + + + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } + + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } + + /** + * Get the Player involved in this event. + * + * @return player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } + + public int getRadius() { + return radius; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java new file mode 100644 index 0000000..5b807bf --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java @@ -0,0 +1,57 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +public class LandUnclaimAllEvent extends FactionPlayerEvent implements Cancellable { + private boolean cancelled; + + public LandUnclaimAllEvent(Faction f, FPlayer p) { + super(f, p); + } + + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } + + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } + + /** + * Get the Player involved in the event. + * + * @return Player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java new file mode 100644 index 0000000..1ff89e2 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java @@ -0,0 +1,69 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +/** + * Event called when an FPlayer unclaims land for a Faction. + */ +public class LandUnclaimEvent extends FactionPlayerEvent implements Cancellable { + + private boolean cancelled; + private final FLocation location; + + public LandUnclaimEvent(FLocation loc, Faction f, FPlayer p) { + super(f, p); + cancelled = false; + location = loc; + } + + public FLocation getLocation() { + return this.location; + } + + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } + + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } + + /** + * Get the Player involved in the event. + * + * @return Player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + cancelled = c; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java b/Factions/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java new file mode 100644 index 0000000..c74a84d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java @@ -0,0 +1,81 @@ +package com.massivecraft.factions.event; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +/** + * Event called when a player loses power. + */ +public class PowerLossEvent extends FactionPlayerEvent implements Cancellable { + + private boolean cancelled = false; + private String message; + + public PowerLossEvent(Faction f, FPlayer p) { + super(f, p); + } + + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } + + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } + + /** + * Get the Player involved in the event. + * + * @return Player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } + + /** + * Get the power loss message. + * + * @return power loss message as String. + */ + public String getMessage() { + return message; + } + + /** + * Set the power loss message. + * + * @param message message + */ + public void setMessage(String message) { + this.message = message; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/gui/FDisbandConfirmGUI.java b/Factions/src/main/java/com/massivecraft/factions/gui/FDisbandConfirmGUI.java new file mode 100644 index 0000000..95b98eb --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/gui/FDisbandConfirmGUI.java @@ -0,0 +1,45 @@ +package com.massivecraft.factions.gui; + + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.util.CC; +import com.massivecraft.factions.util.ItemBuilder; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; + +public class FDisbandConfirmGUI { + private Faction faction; + private final PaginatedGui confirmGUI; + + public FDisbandConfirmGUI(Player player, Faction faction) { + this.confirmGUI = new PaginatedGui(1, 9, "Faction Disband Confirm Menu"); + this.faction = faction; + + + ItemStack confirm = new ItemBuilder(Material.getMaterial("STAINED_GLASS_PANE"), 1, (short) DyeColor.LIME.getWoolData()).setName(CC.GreenB + "Confirm").addLore(CC.Gray + "Confirm disbanding of " + CC.GreenB + this.faction.getTag() + CC.Gray + "!").build(); + ItemStack cancel = new ItemBuilder(Material.getMaterial("STAINED_GLASS_PANE"), CC.RedB + "Cancel", CC.Gray + "Click to cancel faction disband.").setColor(DyeColor.RED).build(); + + this.confirmGUI.setItem(3, new GuiItem(confirm,event -> { + player.closeInventory(); + player.setMetadata("disband_confirm", new FixedMetadataValue(FactionsPlugin.getInstance(), System.currentTimeMillis())); + player.performCommand("f disband"); + })); + this.confirmGUI.setItem(5, new GuiItem(cancel,event -> { + player.closeInventory(); + player.sendMessage(CC.RedB + "(!) " + CC.Red + "Disband cancelled."); + })); + + } + + public PaginatedGui getConfirmGUI() { + return confirmGUI; + } +} + + diff --git a/Factions/src/main/java/com/massivecraft/factions/gui/GUI.java b/Factions/src/main/java/com/massivecraft/factions/gui/GUI.java new file mode 100644 index 0000000..385d519 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/gui/GUI.java @@ -0,0 +1,136 @@ +package com.massivecraft.factions.gui; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.tag.Tag; +import com.massivecraft.factions.util.TextUtil; +import org.bukkit.Bukkit; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class GUI implements InventoryHolder { + protected Inventory inventory; + + protected final int size; + protected int back = -1; + + private Map slotMap = new HashMap<>(); + + protected FPlayer user; + + public GUI(FPlayer user, int rows) { + this.size = rows * 9; + this.user = user; + } + + protected abstract String getName(); + + // Parse all the placeholder values in this String, will be injected into the SimpleItem and return it + protected abstract String parse(String toParse, Type type); + + protected abstract void onClick(Type action, ClickType clickType); + + // Should only be called by the InventoryListener + public void click(int slot, ClickType clickType) { + if (slotMap.containsKey(slot)) { + onClick(slotMap.get(slot), clickType); + } else if (this instanceof Backable && back == slot) { + ((Backable) this).onBack(); + } + } + + protected abstract Map createSlotMap(); + + public void build() { + String guiName = this.getName(); + inventory = Bukkit.createInventory(this, size, guiName); + + this.slotMap = this.createSlotMap(); + + buildDummyItems(); + buildItems(); + } + + protected abstract SimpleItem getItem(Type type); + + protected void buildItems() { + for (Map.Entry entry : slotMap.entrySet()) { + setItemAtSlot(entry.getKey(), entry.getValue()); + } + } + + protected void buildItem(Type type) { + for (Map.Entry entry : slotMap.entrySet()) { + if (entry.getValue().equals(type)) { + setItemAtSlot(entry.getKey(), entry.getValue()); + } + } + } + + private void setItemAtSlot(int slot, Type type) { + SimpleItem item = getItem(type); + parse(item, type); + inventory.setItem(slot, item.get()); + } + + protected abstract Map createDummyItems(); + + protected void buildDummyItems() { + for (Map.Entry entry : createDummyItems().entrySet()) { + SimpleItem item = entry.getValue(); + parse(item, null); + inventory.setItem(entry.getKey(), item.get()); + } + } + + // Will parse default faction stuff, ie: Faction Name, Power, Colors etc + protected void parse(SimpleItem item, Type type) { + if (type != null) { + item.setName(parse(item.getName(), type)); + } + item.setName(parseDefault(item.getName())); + if (item.getLore() != null) { + item.setLore(parseList(item.getLore(), type)); + } + } + + protected List parseList(List stringList, Type type) { + List newList = new ArrayList<>(); + for (String toParse : stringList) { + String parsed = toParse; + if (type != null) { + parsed = parse(parsed, type); + } + parsed = parseDefault(parsed); + newList.add(parsed); + } + return newList; + } + + protected String parseDefault(String toParse) { + toParse = TextUtil.parseColor(toParse); + toParse = Tag.parsePlain(user, toParse); + toParse = Tag.parsePlain(user.getFaction(), toParse); + toParse = Tag.parsePlaceholders(user.getPlayer(), toParse); + return toParse; + } + + @Override + public Inventory getInventory() { + return inventory; + } + + public void open() { + user.getPlayer().openInventory(getInventory()); + } + + public interface Backable { + void onBack(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/gui/PermissibleActionGUI.java b/Factions/src/main/java/com/massivecraft/factions/gui/PermissibleActionGUI.java new file mode 100644 index 0000000..8ff99b4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/gui/PermissibleActionGUI.java @@ -0,0 +1,146 @@ +package com.massivecraft.factions.gui; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.event.inventory.ClickType; + +import java.util.HashMap; +import java.util.Map; + +public class PermissibleActionGUI extends GUI implements GUI.Backable { + private static final SimpleItem backItem = SimpleItem.builder().setMaterial(MaterialDb.get("ARROW")).setName(TL.GUI_BUTTON_BACK.toString()).build(); + private static final SimpleItem base; + private static final String locked; + private static final String allow; + private static final String deny; + private static final String allowLower; + private static final String denyLower; + + static { + base = SimpleItem.builder().setLore(FactionsPlugin.getInstance().conf().commands().perms().getGuiLore()).setName("&8[{action-access-color}{action}&8]").build(); + locked = ' ' + TL.GUI_PERMS_ACTION_LOCKED.toString(); + allow = TL.GUI_PERMS_ACTION_ALLOW.toString(); + allowLower = allow.toLowerCase(); + deny = TL.GUI_PERMS_ACTION_DENY.toString(); + denyLower = deny.toLowerCase(); + } + + private final Permissible permissible; + private final boolean online; + + public PermissibleActionGUI(boolean online, FPlayer user, Permissible permissible) { + super(user, (int) Math.ceil(((double) PermissibleAction.values().length) / 9d) + 1); + this.permissible = permissible; + this.online = online; + build(); + } + + @Override + protected String getName() { + String bit = FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms() ? + TL.GUI_PERMS_ACTION_ONLINEOFFLINEBIT.format(online ? TL.GUI_PERMS_ONLINE.toString() : TL.GUI_PERMS_OFFLINE) + : ""; + return TL.GUI_PERMS_ACTION_NAME.format(permissible.name().toLowerCase(), bit); + } + + @Override + protected String parse(String toParse, PermissibleAction action) { + String actionName = action.getShortDescription().substring(0, 1).toUpperCase() + action.getShortDescription().substring(1); + toParse = toParse.replace("{action}", actionName); + + boolean access = user.getFaction().hasAccess(online, permissible, action); + String extra = ""; + if (user.getFaction().isLocked(online, permissible, action)) { + extra = locked; + } + + toParse = toParse.replace("{action-access}", (access ? allow : deny) + extra); + toParse = toParse.replace("{action-access-color}", access ? ChatColor.GREEN.toString() : ChatColor.DARK_RED.toString()); + toParse = toParse.replace("{action-desc}", action.getDescription()); + + return toParse; + } + + @Override + public void click(int slot, ClickType clickType) { + if (FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms() && permissible instanceof Relation && slot == this.back + 4) { + new PermissibleActionGUI(!online, user, permissible).open(); + } else { + super.click(slot, clickType); + } + } + + @Override + protected void onClick(PermissibleAction action, ClickType click) { + boolean access; + if (click == ClickType.LEFT) { + access = true; + } else if (click == ClickType.RIGHT) { + access = false; + } else { + return; + } + if (user.getFaction().setPermission(online, permissible, action, access)) { + // Reload item to reparse placeholders + buildItem(action); + user.msg(TL.COMMAND_PERM_SET, action.getShortDescription(), access ? allowLower : denyLower, permissible.name()); + FactionsPlugin.getInstance().log(TL.COMMAND_PERM_SET.format(action.getShortDescription(), access ? "Allow" : "Deny", permissible.name()) + " for faction " + user.getTag()); + } else { + user.msg(TL.COMMAND_PERM_INVALID_SET); + } + } + + @Override + protected Map createSlotMap() { + Map map = new HashMap<>(); + int i = 0; + for (PermissibleAction action : PermissibleAction.values()) { + if (this.permissible instanceof Relation && action.isFactionOnly()) { + continue; + } + map.put(i++, action); + } + return map; + } + + @Override + protected SimpleItem getItem(PermissibleAction permissibleAction) { + SimpleItem item = new SimpleItem(base); + + item.setEnchant(user.getFaction().hasAccess(online, permissible, permissibleAction)); + Material material = permissibleAction.getMaterial(); + item.setMaterial(material == Material.AIR ? Material.STONE : material); + return item; + } + + @Override + protected Map createDummyItems() { + Map map = new HashMap<>(); + map.put((this.back = ((PermissibleAction.values().length / 9) + 1) * 9 - 1), backItem); + if (FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms() && permissible instanceof Relation) { + map.put(this.back + 4, PermissibleRelationGUI.offlineSwitch); + } + return map; + } + + // For dummy items only parseDefault is called, but we want to provide the relation placeholders, so: Override + @Override + protected String parseDefault(String string) { + String permissibleName = permissible.toString().substring(0, 1).toUpperCase() + permissible.toString().substring(1); + String parsed = string.replace("{relation-color}", permissible.getColor().toString()); + parsed = parsed.replace("{relation}", permissibleName); + return super.parseDefault(parsed); + } + + @Override + public void onBack() { + new PermissibleRelationGUI(online, user).open(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/gui/PermissibleRelationGUI.java b/Factions/src/main/java/com/massivecraft/factions/gui/PermissibleRelationGUI.java new file mode 100644 index 0000000..f6cc794 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/gui/PermissibleRelationGUI.java @@ -0,0 +1,129 @@ +package com.massivecraft.factions.gui; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Permissible; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.material.MaterialDb; +import org.apache.commons.lang.StringUtils; +import org.bukkit.event.inventory.ClickType; + +import java.util.*; + +public class PermissibleRelationGUI extends GUI { + private static final Map items; + public static SimpleItem offlineSwitch = SimpleItem.builder().setName(TL.GUI_PERMS_TOGGLE.toString()).setMaterial(MaterialDb.get("LEVER")).build(); + + static { + items = new LinkedHashMap<>(); + SimpleItem.Builder starter = SimpleItem.builder().setName("&8[{relation-color}{relation}&8]"); + + SimpleItem recruit = starter.build(); + recruit.setName("§6" + StringUtils.capitalize(Role.RECRUIT.getTranslation().toString() + " Permissions")); + recruit.setMaterial(MaterialDb.get("WOODEN_SWORD")); + items.put(Role.RECRUIT, recruit); + + SimpleItem normal = starter.build(); + normal.setName("§6" + StringUtils.capitalize(Role.NORMAL.getTranslation().toString() + " Permissions")); + normal.setMaterial(MaterialDb.get("STONE_SWORD")); + items.put(Role.NORMAL, normal); + + SimpleItem moderator = starter.build(); + moderator.setName("§6" + StringUtils.capitalize(Role.MODERATOR.getTranslation().toString() + " Permissions")); + moderator.setMaterial(MaterialDb.get("IRON_SWORD")); + items.put(Role.MODERATOR, moderator); + + SimpleItem coleader = starter.build(); + coleader.setName("§6" + StringUtils.capitalize(Role.COLEADER.getTranslation().toString() + " Permissions")); + coleader.setMaterial(MaterialDb.get("DIAMOND_SWORD")); + items.put(Role.COLEADER, coleader); + + SimpleItem ally = starter.build(); + ally.setName("§6" + StringUtils.capitalize(Relation.ALLY.getTranslation() + " Permissions")); + ally.setMaterial(MaterialDb.get("GOLD_SWORD")); + items.put(Relation.ALLY, ally); + + SimpleItem truce = starter.build(); + truce.setName("§6" + StringUtils.capitalize(Relation.TRUCE.getTranslation() + " Permissions")); + truce.setMaterial(MaterialDb.get("IRON_AXE")); + items.put(Relation.TRUCE, truce); + + SimpleItem neutral = starter.build(); + neutral.setName("§6" + StringUtils.capitalize(Relation.NEUTRAL.getTranslation() + " Permissions")); + neutral.setMaterial(MaterialDb.get("STONE_HOE")); + items.put(Relation.NEUTRAL, neutral); + + SimpleItem enemy = starter.build(); + enemy.setName("§6" + StringUtils.capitalize(Relation.ENEMY.getTranslation() + " Permissions")); + enemy.setMaterial(MaterialDb.get("STONE_AXE")); + items.put(Relation.ENEMY, enemy); + } + + private final boolean online; + + public PermissibleRelationGUI(boolean online, FPlayer user) { + super(user, FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms() ? 2 : 1); + this.online = online; + build(); + } + + @Override + protected String getName() { + String bit = FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms() ? + TL.GUI_PERMS_RELATION_ONLINEOFFLINEBIT.format(online ? TL.GUI_PERMS_ONLINE.toString() : TL.GUI_PERMS_OFFLINE) + : ""; + return TL.GUI_PERMS_RELATION_NAME.format(bit); + } + + @Override + protected String parse(String toParse, Permissible permissible) { + // Uppercase the first letter + String name = permissible.toString().substring(0, 1).toUpperCase() + permissible.toString().substring(1); + + toParse = toParse.replace("{relation-color}", permissible.getColor().toString()); + toParse = toParse.replace("{relation}", name); + return toParse; + } + + @Override + public void click(int slot, ClickType clickType) { + if (FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms() && slot == 13) { + new PermissibleRelationGUI(!online, user).open(); + } else { + super.click(slot, clickType); + } + } + + @Override + protected void onClick(Permissible permissible, ClickType clickType) { + new PermissibleActionGUI(online, user, permissible).open(); + } + + @Override + protected Map createSlotMap() { + Map map = new HashMap<>(); + if (online) { + map.put(0, Role.RECRUIT); + map.put(1, Role.NORMAL); + map.put(2, Role.MODERATOR); + map.put(3, Role.COLEADER); + } + map.put(5, Relation.ALLY); + map.put(6, Relation.NEUTRAL); + map.put(7, Relation.TRUCE); + map.put(8, Relation.ENEMY); + return map; + } + + @Override + protected SimpleItem getItem(Permissible permissible) { + return items.get(permissible); + } + + @Override + protected Map createDummyItems() { + return FactionsPlugin.getInstance().conf().factions().other().isSeparateOfflinePerms() ? Collections.singletonMap(13, offlineSwitch) : Collections.emptyMap(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/gui/SimpleItem.java b/Factions/src/main/java/com/massivecraft/factions/gui/SimpleItem.java new file mode 100644 index 0000000..6e3f76d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/gui/SimpleItem.java @@ -0,0 +1,180 @@ +package com.massivecraft.factions.gui; + +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.List; + +/** + * This class implements an easy way to map + * config values like: materials, lore, name, color + * to a respective ItemStack, also has utility methods + * to merge, clone, etc + */ +public class SimpleItem { + private String name; + private List lore; + private Material material; + private DyeColor color; + private boolean enchant; + + private short data; + + SimpleItem(Builder builder) { + this.name = builder.name; + this.lore = builder.lore; + this.material = builder.material; + this.color = builder.color; + + this.data = builder.data; + } + + public SimpleItem(SimpleItem item) { + this.name = item.name; + this.lore = item.lore; + this.material = item.material; + this.color = item.color; + + this.data = item.data; + } + + public ItemStack get() { + if (isValid()) { + ItemStack itemStack = new ItemStack(material, 1, data); + ItemMeta meta = itemStack.getItemMeta(); + + if (name != null) { + meta.setDisplayName(name); + } + // Empty list if not specified + meta.setLore(lore); + if (FactionsPlugin.getMCVersion() >= 800) { + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); + } + if (enchant) { + meta.addEnchant(Enchantment.LUCK, 1, true); + } + + // If a user places a color, they should be expected to put a colorable object + if (color != null) { + // ItemStack.setData() does not work :( + itemStack.setDurability(color.getWoolData()); + } + + itemStack.setItemMeta(meta); + return itemStack; + } else { + return new ItemStack(Material.AIR); + } + } + + // All non null values in 'from' will be merged into this ItemGUI + public void merge(SimpleItem from) { + if (from.material != null) { + material = from.material; + } + if (from.name != null) { + name = from.name; + } + if (from.color != null) { + color = from.color; + } + if (!from.lore.isEmpty()) { + lore = from.lore; + } + } + + public boolean isValid() { + // For an ItemStack to be built this class needs the material, if more information is available then it will be used + return material != null; + } + + 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 Material getMaterial() { + return material; + } + + public void setMaterial(Material material) { + this.material = material; + } + + public DyeColor getColor() { + return color; + } + + public void setColor(DyeColor color) { + this.color = color; + } + + public boolean isEnchant() { + return enchant; + } + + public void setEnchant(boolean enchant) { + this.enchant = enchant; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private Material material; + private String name; + private List lore; + private DyeColor color; + private short data = 0; + + private Builder() { + } + + public Builder setColor(DyeColor color) { + this.color = color; + return this; + } + + public Builder setLore(List lore) { + this.lore = lore; + return this; + } + + public Builder setName(String name) { + this.name = name; + return this; + } + + public Builder setMaterial(Material material) { + this.material = material; + return this; + } + + public Builder setData(short data) { + this.data = data; + return this; + } + + public SimpleItem build() { + return new SimpleItem(this); + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/gui/UpgradeGUI.java b/Factions/src/main/java/com/massivecraft/factions/gui/UpgradeGUI.java new file mode 100644 index 0000000..85c973a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/gui/UpgradeGUI.java @@ -0,0 +1,137 @@ +package com.massivecraft.factions.gui; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.data.MemoryFaction; +import com.massivecraft.factions.util.TextUtil; +import com.massivecraft.factions.util.UpgradeType; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.event.inventory.ClickType; + +import java.text.NumberFormat; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +public class UpgradeGUI extends GUI{ + private static final Map items; + + static { + items = new LinkedHashMap<>(); + + items.put(UpgradeType.TNT, FactionsPlugin.getInstance().conf().upgrades().tnt().item().getItem()); + + //items.put(UpgradeType.CHEST, FactionsPlugin.getInstance().conf().upgrades().chest().item().getItem()); + + items.put(UpgradeType.WARP_AMOUNT, FactionsPlugin.getInstance().conf().upgrades().warpAmount().item().getItem()); + + //items.put(UpgradeType.FACTION_SIZE, FactionsPlugin.getInstance().conf().upgrades().factionSize().item().getItem()); + + } + + public UpgradeGUI(FPlayer user) { + super(user, FactionsPlugin.getInstance().conf().upgrades().gui().getRows()); + build(); + } + + @Override + protected String getName() { + return TextUtil.parseColor("Faction Upgrades"); + } + + @Override + protected String parse(String toParse, UpgradeType upgradeType) { + String toReturn = toParse; + + switch(upgradeType){ + case TNT: + for(int z = 1; z <= FactionsPlugin.getInstance().conf().upgrades().tnt().getLevels().size(); z++){ + toReturn = toReturn.replace("{AMOUNT_" + z + "}", "" + NumberFormat.getIntegerInstance().format(FactionsPlugin.getInstance().conf().upgrades().tnt().getNumber(z))); + + toReturn = toReturn.replace("{PRICE_" + z + "}", "" + NumberFormat.getIntegerInstance().format(FactionsPlugin.getInstance().conf().upgrades().tnt().getCost(z))); + } + + toReturn = toReturn.replace("{LEVEL}", user.getFaction().getUpgrade(upgradeType) + ""); + break; + /* case CHEST: + for(int z = 1; z <= FactionsPlugin.getInstance().conf().upgrades().chest().getLevels().size(); z++){ + toReturn = toReturn.replace("{AMOUNT_" + z + "}", "" + FactionsPlugin.getInstance().conf().upgrades().chest().getNumber(z)); + + toReturn = toReturn.replace("{PRICE_" + z + "}", "" + NumberFormat.getIntegerInstance().format(FactionsPlugin.getInstance().conf().upgrades().chest().getCost(z))); + } + + toReturn = toReturn.replace("{LEVEL}", user.getFaction().getUpgrade(upgradeType) + ""); + break;*/ +/* case SPAWNER_BOOST: + for(int z = 1; z <= FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().getLevels().size(); z++){ + toReturn = toReturn.replace("{AMOUNT_" + z + "}", "" + FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().getNumber(z)); + + toReturn = toReturn.replace("{PRICE_" + z + "}", "" + FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().getCost(z)); + } + + toReturn = toReturn.replace("{LEVEL}", user.getFaction().getUpgrade(upgradeType) + ""); + break;*/ + case WARP_AMOUNT: + for(int z = 1; z <= FactionsPlugin.getInstance().conf().upgrades().warpAmount().getLevels().size(); z++){ + toReturn = toReturn.replace("{AMOUNT_" + z + "}", "" + FactionsPlugin.getInstance().conf().upgrades().warpAmount().getNumber(z)); + + toReturn = toReturn.replace("{PRICE_" + z + "}", "" + NumberFormat.getIntegerInstance().format(FactionsPlugin.getInstance().conf().upgrades().warpAmount().getCost(z))); + } + + toReturn = toReturn.replace("{LEVEL}", user.getFaction().getUpgrade(upgradeType) + ""); + break; + /*case FACTION_SIZE: + for(int z = 1; z <= FactionsPlugin.getInstance().conf().upgrades().factionSize().getLevels().size(); z++){ + toReturn = toReturn.replace("{AMOUNT_" + z + "}", "" + FactionsPlugin.getInstance().conf().upgrades().factionSize().getNumber(z)); + + toReturn = toReturn.replace("{PRICE_" + z + "}", "" + NumberFormat.getIntegerInstance().format(FactionsPlugin.getInstance().conf().upgrades().factionSize().getCost(z))); + } + + toReturn = toReturn.replace("{LEVEL}", user.getFaction().getUpgrade(upgradeType) + ""); + break;*/ + } + return toReturn; + } + + @Override + protected void onClick(UpgradeType action, ClickType clickType) { + if(user.getFaction().isWilderness()){ + user.msg(TextUtil.parseColor("&cYou cannot use upgrades while in wilderness")); + user.getPlayer().closeInventory(); + return; + } + + if (((MemoryFaction) user.getFaction()).doUpgrade(action, user)) { + ((MemoryFaction) user.getFaction()).commitUpgrade(action); + + user.getPlayer().closeInventory(); + } + } + + @Override + protected Map createSlotMap() { + Map map = new HashMap<>(); + map.put(FactionsPlugin.getInstance().conf().upgrades().tnt().item().getSlot(), UpgradeType.TNT); + map.put(FactionsPlugin.getInstance().conf().upgrades().warpAmount().item().getSlot(), UpgradeType.WARP_AMOUNT); + return map; + } + + @Override + protected SimpleItem getItem(UpgradeType upgradeType) { + return new SimpleItem(items.get(upgradeType)); + } + + @Override + protected Map createDummyItems() { + Map map = new HashMap<>(); + SimpleItem.Builder stained_glass_pane = SimpleItem.builder() + .setData((short) 7) + .setMaterial(MaterialDb.get("STAINED_GLASS_PANE")) + .setName(TextUtil.parseColor("&7") + ); + for(int z = 0; z < this.size; z++){ + map.put(z, stained_glass_pane.build()); + } + return map; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/gui/WarpGUI.java b/Factions/src/main/java/com/massivecraft/factions/gui/WarpGUI.java new file mode 100644 index 0000000..80c1f6f --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/gui/WarpGUI.java @@ -0,0 +1,262 @@ +package com.massivecraft.factions.gui; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.WarmUpUtil; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.conversations.ConversationAbandonedEvent; +import org.bukkit.conversations.ConversationAbandonedListener; +import org.bukkit.conversations.ConversationContext; +import org.bukkit.conversations.ConversationFactory; +import org.bukkit.conversations.InactivityConversationCanceller; +import org.bukkit.conversations.ManuallyAbandonedConversationCanceller; +import org.bukkit.conversations.Prompt; +import org.bukkit.conversations.StringPrompt; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class WarpGUI extends GUI { + private static final SimpleItem warpItem; + private static final SimpleItem passwordModifier; + + static { + warpItem = SimpleItem.builder() + .setName("&8[&7{warp}&8]") + .setMaterial(MaterialDb.get("LIME_STAINED_GLASS")) + .setColor(DyeColor.LIME) + .build(); + passwordModifier = SimpleItem.builder() + .setMaterial(MaterialDb.get("BLACK_STAINED_GLASS")) + .setColor(DyeColor.BLACK) + .setLore(Collections.singletonList("&8Password Protected")) + .build(); + } + + private final List warps; + private final String name; + private final int page; + private final Faction faction; + + public WarpGUI(FPlayer user, Faction faction) { + this(user, -1, faction); + } + + private WarpGUI(FPlayer user, int page, Faction faction) { + super(user, getRows(faction)); + this.faction = faction; + warps = new ArrayList<>(faction.getWarps().keySet()); + if (page == -1 && warps.size() > (5 * 9)) { + page = 0; + } + this.page = page; + name = page == -1 ? TL.GUI_WARPS_ONE_PAGE.format(faction.getTag()) : TL.GUI_WARPS_PAGE.format(faction.getTag(), page + 1); + build(); + } + + @Override + public String getName() { + return name; + } + + private static int getRows(Faction faction) { + int warpCount = faction.getWarps().size(); + if (warpCount == 0) { + return 1; + } + if (warpCount > (5 * 9)) { + return 6; + } + return (int) Math.ceil(((double) warpCount) / 9D); + } + + @Override + protected String parse(String toParse, Integer index) { + if (index < 0) { + return toParse; + } + if (warps.size() > index) { + toParse = toParse.replace("{warp}", warps.get(index)); + } + return toParse; + } + + @Override + protected void onClick(Integer index, ClickType clickType) { + if (!faction.hasAccess(this.user, PermissibleAction.WARP)) { + user.msg(TL.COMMAND_FWARP_NOACCESS, faction.getTag(user)); + this.user.getPlayer().closeInventory(); + return; + } + if (index == -1) { + int targetPage = page + 1; + new WarpGUI(this.user, targetPage, faction).open(); + return; + } + if (index == -2) { + int targetPage = page - 1; + new WarpGUI(this.user, targetPage, faction).open(); + return; + } + // Check if there are enough faction warps for this index + if (warps.size() > index) { + String warp = warps.get(index); + if (!faction.hasWarpPassword(warp)) { + if (transact()) { + doWarmup(warp); + } + } else { + HashMap sessionData = new HashMap<>(); + sessionData.put("warp", warp); + PasswordPrompt passwordPrompt = new PasswordPrompt(); + ConversationFactory inputFactory = new ConversationFactory(FactionsPlugin.getInstance()) + .withModality(false) + .withLocalEcho(false) + .withInitialSessionData(sessionData) + .withFirstPrompt(passwordPrompt) + .addConversationAbandonedListener(passwordPrompt) + .withTimeout(5);// TODO get config.getInt("password-timeout", 5) + + user.getPlayer().closeInventory(); + inputFactory.buildConversation(user.getPlayer()).begin(); + } + } + } + + @Override + protected Map createSlotMap() { + Map map = new HashMap<>(); + final int num; + final int startingIndex; + if (page == -1) { + num = warps.size(); + startingIndex = 0; + } else { + num = Math.min(warps.size() - ((5 * 9) * page), 5 * 9); + startingIndex = (5 * 9) * page; + if (page > 0) { + map.put(45, -2); + } + if (page < (getMaxPages() - 1)) { + map.put(53, -1); + } + } + int modifier = 0; + for (int warpIndex = startingIndex, count = 0; count < num; warpIndex++, count++) { + if (count % 9 == 0) { + int remaining = num - count; + if (remaining < 9) { + modifier = (9 - remaining) / 2; + } + } + map.put(count + modifier, warpIndex); + } + return map; + } + + @Override + protected SimpleItem getItem(Integer index) { + if (index == -1) { + return SimpleItem.builder().setName(TL.GUI_BUTTON_NEXT.toString()).setMaterial(MaterialDb.get("ARROW")).build(); + } + if (index == -2) { + return SimpleItem.builder().setName(TL.GUI_BUTTON_PREV.toString()).setMaterial(MaterialDb.get("ARROW")).build(); + } + SimpleItem item = new SimpleItem(warpItem); + if (faction.hasWarpPassword(warps.get(index))) { + item.merge(passwordModifier); + } + return item; + } + + private int getMaxPages() { + if (warps.size() <= (5 * 9)) { + return 0; + } + return (int) Math.ceil(((double) warps.size()) / (5d * 9d)); + } + + @Override + protected Map createDummyItems() { + return Collections.emptyMap(); + } + + private class PasswordPrompt extends StringPrompt implements ConversationAbandonedListener { + + @Override + public String getPromptText(ConversationContext context) { + return TL.COMMAND_FWARP_PASSWORD_REQUIRED.toString(); + } + + @Override + public Prompt acceptInput(ConversationContext context, String input) { + String warp = (String) context.getSessionData("warp"); + if (faction.isWarpPassword(warp, input)) { + // Valid Password, make em pay + if (transact()) { + doWarmup(warp); + } + } else { + // Invalid Password + user.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); + } + return END_OF_CONVERSATION; + } + + @Override + public void conversationAbandoned(ConversationAbandonedEvent abandonedEvent) { + if (abandonedEvent.getCanceller() instanceof ManuallyAbandonedConversationCanceller || + abandonedEvent.getCanceller() instanceof InactivityConversationCanceller) { + user.msg(TL.COMMAND_FWARP_PASSWORD_CANCEL); + open(); + } + } + } + + private void doWarmup(final String warp) { + WarmUpUtil.process(user, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, () -> { + Player player = Bukkit.getPlayer(user.getPlayer().getUniqueId()); + if (player != null) { + if (!faction.hasAccess(this.user, PermissibleAction.WARP)) { + user.msg(TL.COMMAND_FWARP_NOACCESS, faction.getTag(user)); + return; + } + FactionsPlugin.getInstance().teleport(player, faction.getWarp(warp).getLocation()).thenAccept(success -> { + if (success) { + user.msg(TL.COMMAND_FWARP_WARPED, warp); + } + }); + } + }, FactionsPlugin.getInstance().conf().commands().warp().getDelay()); + } + + private boolean transact() { + if (!user.isAdminBypassing()) { + return true; + } + + double cost = FactionsPlugin.getInstance().conf().economy().getCostWarp(); + + if (!Econ.shouldBeUsed() || this.user == null || cost == 0.0 || user.isAdminBypassing()) { + return true; + } + + if (FactionsPlugin.getInstance().conf().economy().isBankEnabled() && FactionsPlugin.getInstance().conf().economy().isBankFactionPaysCosts() && user.hasFaction() && user.getFaction().hasAccess(user, PermissibleAction.ECONOMY)) { + return Econ.modifyMoney(user.getFaction(), -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } else { + return Econ.modifyMoney(user, -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java b/Factions/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java new file mode 100644 index 0000000..74900f3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java @@ -0,0 +1,15 @@ +package com.massivecraft.factions.iface; + +import com.massivecraft.factions.util.TL; +import org.bukkit.OfflinePlayer; + +public interface EconomyParticipator extends RelationParticipator { + + String getAccountId(); + + OfflinePlayer getOfflinePlayer(); + + void msg(String str, Object... args); + + void msg(TL translation, Object... args); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java b/Factions/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java new file mode 100644 index 0000000..6a90853 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java @@ -0,0 +1,20 @@ +package com.massivecraft.factions.iface; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.perms.Relation; +import org.bukkit.ChatColor; + +public interface RelationParticipator { + + String describeTo(RelationParticipator that); + + String describeTo(RelationParticipator that, boolean ucfirst); + + Relation getRelationTo(RelationParticipator that); + + Relation getRelationTo(RelationParticipator that, boolean ignorePeaceful); + + Relation getRelationToLocation(FLocation fLocation); + + ChatColor getColorTo(RelationParticipator to); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/ClipPlaceholderAPIManager.java b/Factions/src/main/java/com/massivecraft/factions/integration/ClipPlaceholderAPIManager.java new file mode 100644 index 0000000..bc04da6 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/ClipPlaceholderAPIManager.java @@ -0,0 +1,242 @@ +package com.massivecraft.factions.integration; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.landraidcontrol.DTRControl; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.tag.FactionTag; +import com.massivecraft.factions.tag.Tag; +import com.massivecraft.factions.util.TL; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Relational; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.util.UUID; + +public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements Relational { + + // Identifier for this expansion + @Override + public String getIdentifier() { + return "factionsuuid"; + } + + @Override + public String getAuthor() { + return "drtshock"; + } + + // Since we are registering this expansion from the dependency, this can be null + @Override + public String getPlugin() { + return null; + } + + // Return the plugin version since this expansion is bundled with the dependency + @Override + public String getVersion() { + return FactionsPlugin.getInstance().getDescription().getVersion(); + } + + @Override + public boolean persist() { + return true; + } + + // Relational placeholders + @Override + public String onPlaceholderRequest(Player p1, Player p2, String placeholder) { + if (p1 == null || p2 == null || placeholder == null) { + return ""; + } + + FPlayer fp1 = FPlayers.getInstance().getByPlayer(p1); + FPlayer fp2 = FPlayers.getInstance().getByPlayer(p2); + if (fp1 == null || fp2 == null) { + return ""; + } + + switch (placeholder) { + case "relation": + String relationName = fp1.getRelationTo(fp2).nicename; + return relationName != null ? relationName : ""; + case "relation_color": + ChatColor color = fp1.getColorTo(fp2); + return color != null ? color.toString() : ""; + } + + return null; + } + + @Override + public String onPlaceholderRequest(Player player, String placeholder) { + if (player == null || placeholder == null) { + return ""; + } + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + Faction faction = fPlayer.getFaction(); + boolean territory = false; + if (placeholder.contains("faction_territory")) { + faction = Board.getInstance().getFactionAt(fPlayer.getLastStoodAt()); + placeholder = placeholder.replace("_territory", ""); + territory = true; + } + switch (placeholder) { + // First list player stuff + case "player_name": + return fPlayer.getName(); + case "player_lastseen": + String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fPlayer.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; + return fPlayer.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fPlayer.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); + case "player_group": + return FactionsPlugin.getInstance().getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fPlayer.getId()))); + case "player_balance": + return Econ.isSetup() ? Econ.getFriendlyBalance(fPlayer) : TL.ECON_OFF.format("balance"); + case "player_power": + return String.valueOf(fPlayer.getPowerRounded()); + case "player_maxpower": + return String.valueOf(fPlayer.getPowerMaxRounded()); + case "player_kills": + return String.valueOf(fPlayer.getKills()); + case "player_deaths": + return String.valueOf(fPlayer.getDeaths()); + case "player_role": + return fPlayer.hasFaction() ? fPlayer.getRole().getPrefix() : ""; + case "player_role_name": + return fPlayer.hasFaction() ? fPlayer.getRole().getTranslation().toString() : TL.PLACEHOLDER_ROLE_NAME.toString(); + // Then Faction stuff + case "faction_name": + return (fPlayer.hasFaction() || territory) ? faction.getTag() : TL.NOFACTION_PREFIX.toString(); + case "faction_name_custom": + return (fPlayer.hasFaction() || territory) ? Tag.parsePlain(fPlayer, TL.PLACEHOLDER_CUSTOM_FACTION.toString()) : ""; + case "faction_only_space": + return (fPlayer.hasFaction() || territory) ? " " : ""; + case "faction_power": + return String.valueOf(faction.getPowerRounded()); + case "faction_powermax": + return String.valueOf(faction.getPowerMaxRounded()); + case "faction_dtr": + return (fPlayer.hasFaction() || territory) ? DTRControl.round(faction.getDTR()) : ""; + case "faction_dtrmax": + if ((fPlayer.hasFaction() || territory) && FactionsPlugin.getInstance().getLandRaidControl() instanceof DTRControl) { + return DTRControl.round(((DTRControl) FactionsPlugin.getInstance().getLandRaidControl()).getMaxDTR(faction)); + } + return ""; + case "faction_dtr_frozen": + if ((fPlayer.hasFaction() || territory) && FactionsPlugin.getInstance().getLandRaidControl() instanceof DTRControl) { + return FactionTag.DTR_FROZEN.replace(FactionTag.DTR_FROZEN.getTag(), faction); + } + return ""; + case "faction_dtr_frozen_time": + if ((fPlayer.hasFaction() || territory) && FactionsPlugin.getInstance().getLandRaidControl() instanceof DTRControl) { + return FactionTag.DTR_FROZEN_TIME.replace(FactionTag.DTR_FROZEN_TIME.getTag(), faction); + } + return ""; + case "faction_maxclaims": + return (fPlayer.hasFaction() || territory) ? String.valueOf(FactionsPlugin.getInstance().getLandRaidControl().getLandLimit(faction)) : ""; + case "faction_description": + return faction.getDescription(); + case "faction_claims": + return String.valueOf(faction.getAllClaims().size()); + case "faction_founded": + return TL.sdf.format(faction.getFoundedDate()); + case "faction_joining": + return (faction.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString()); + case "faction_peaceful": + return faction.isPeaceful() ? FactionsPlugin.getInstance().conf().colors().relations().getNeutral() + TL.COMMAND_SHOW_PEACEFUL.toString() : ""; + case "faction_powerboost": + double powerBoost = faction.getPowerBoost(); + return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString()) + powerBoost + ")"; + case "faction_leader": + FPlayer fAdmin = faction.getFPlayerAdmin(); + return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); + case "faction_warps": + return String.valueOf(faction.getWarps().size()); + case "faction_raidable": + boolean raid = FactionsPlugin.getInstance().getLandRaidControl().isRaidable(faction); + return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); + case "faction_home_world": + return faction.hasHome() ? faction.getHome().getWorld().getName() : ""; + case "faction_home_x": + return faction.hasHome() ? String.valueOf(faction.getHome().getBlockX()) : ""; + case "faction_home_y": + return faction.hasHome() ? String.valueOf(faction.getHome().getBlockY()) : ""; + case "faction_home_z": + return faction.hasHome() ? String.valueOf(faction.getHome().getBlockZ()) : ""; + case "faction_land_value": + return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(faction.getLandRounded())) : TL.ECON_OFF.format("value"); + case "faction_land_refund": + return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(faction.getLandRounded())) : TL.ECON_OFF.format("refund"); + case "faction_bank_balance": + return Econ.shouldBeUsed() ? Econ.moneyString(Econ.getBalance(faction)) : TL.ECON_OFF.format("balance"); + case "faction_tnt_balance": + return FactionTag.TNT_BALANCE.replace(FactionTag.TNT_BALANCE.getTag(), faction); + case "faction_tnt_max_balance": + return FactionTag.TNT_MAX.replace(FactionTag.TNT_MAX.getTag(), faction); + case "faction_allies": + return String.valueOf(faction.getRelationCount(Relation.ALLY)); + case "faction_allies_players": + return String.valueOf(this.countOn(faction, Relation.ALLY, null, fPlayer)); + case "faction_allies_players_online": + return String.valueOf(this.countOn(faction, Relation.ALLY, true, fPlayer)); + case "faction_allies_players_offline": + return String.valueOf(this.countOn(faction, Relation.ALLY, false, fPlayer)); + case "faction_enemies": + return String.valueOf(faction.getRelationCount(Relation.ENEMY)); + case "faction_enemies_players": + return String.valueOf(this.countOn(faction, Relation.ENEMY, null, fPlayer)); + case "faction_enemies_players_online": + return String.valueOf(this.countOn(faction, Relation.ENEMY, true, fPlayer)); + case "faction_enemies_players_offline": + return String.valueOf(this.countOn(faction, Relation.ENEMY, false, fPlayer)); + case "faction_truces": + return String.valueOf(faction.getRelationCount(Relation.TRUCE)); + case "faction_truces_players": + return String.valueOf(this.countOn(faction, Relation.TRUCE, null, fPlayer)); + case "faction_truces_players_online": + return String.valueOf(this.countOn(faction, Relation.TRUCE, true, fPlayer)); + case "faction_truces_players_offline": + return String.valueOf(this.countOn(faction, Relation.TRUCE, false, fPlayer)); + case "faction_online": + return String.valueOf(faction.getOnlinePlayers().size()); + case "faction_offline": + return String.valueOf(faction.getFPlayers().size() - faction.getOnlinePlayers().size()); + case "faction_size": + return String.valueOf(faction.getFPlayers().size()); + case "faction_kills": + return String.valueOf(faction.getKills()); + case "faction_deaths": + return String.valueOf(faction.getDeaths()); + case "faction_maxvaults": + return String.valueOf(faction.getMaxVaults()); + case "faction_relation_color": + return fPlayer.getColorTo(faction).toString(); + } + + return null; + } + + private int countOn(Faction f, Relation relation, Boolean status, FPlayer player) { + int count = 0; + for (Faction faction : Factions.getInstance().getAllFactions()) { + if (faction.getRelationTo(f) == relation) { + if (status == null) { + count += faction.getFPlayers().size(); + } else if (status) { + count += faction.getFPlayersWhereOnline(true, player).size(); + } else { + count += faction.getFPlayersWhereOnline(false, player).size(); + } + } + } + return count; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/Econ.java b/Factions/src/main/java/com/massivecraft/factions/integration/Econ.java new file mode 100644 index 0000000..d71650e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/Econ.java @@ -0,0 +1,522 @@ +package com.massivecraft.factions.integration; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.RelationUtil; +import com.massivecraft.factions.util.TL; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.RegisteredServiceProvider; + +import java.text.NumberFormat; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Level; + +public class Econ { + + private static Economy econ = null; + + public static void setup() { + if (isSetup()) { + return; + } + + String integrationFail = "Economy integration is " + (FactionsPlugin.getInstance().conf().economy().isEnabled() ? "enabled, but" : "disabled, and") + " the plugin \"Vault\" "; + + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { + FactionsPlugin.getInstance().getLogger().info(integrationFail + "is not installed."); + return; + } + + RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (rsp == null) { + FactionsPlugin.getInstance().getLogger().info(integrationFail + "is not hooked into an economy plugin."); + return; + } + econ = rsp.getProvider(); + + FactionsPlugin.getInstance().getLogger().info("Found economy plugin through Vault: " + econ.getName()); + + if (!FactionsPlugin.getInstance().conf().economy().isEnabled()) { + FactionsPlugin.getInstance().getLogger().info("NOTE: Economy is disabled. You can enable it in config/main.conf"); + } + + //P.getInstance().cmdBase.cmdHelp.updateHelp(); + } + + public static boolean shouldBeUsed() { + return FactionsPlugin.getInstance().conf().economy().isEnabled() && econ != null && econ.isEnabled(); + } + + public static boolean isSetup() { + return econ != null; + } + + public static Economy getEcon() { + return econ; + } + + private static String getWorld(OfflinePlayer op) { + return (op instanceof Player) ? ((Player) op).getWorld().getName() : FactionsPlugin.getInstance().conf().economy().getDefaultWorld(); + } + + public static void modifyUniverseMoney(double delta) { + if (!shouldBeUsed()) { + return; + } + + if (FactionsPlugin.getInstance().conf().economy().getUniverseAccount() == null) { + return; + } + if (FactionsPlugin.getInstance().conf().economy().getUniverseAccount().length() == 0) { + return; + } + if (!hasAccount(FactionsPlugin.getInstance().conf().economy().getUniverseAccount())) { + return; + } + + modifyBalance(FactionsPlugin.getInstance().conf().economy().getUniverseAccount(), delta); + } + + public static void sendBalanceInfo(FPlayer to, EconomyParticipator about) { + if (!shouldBeUsed()) { + FactionsPlugin.getInstance().log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); + return; + } + to.msg(TL.ECON_BALANCE, about.describeTo(to, true), Econ.moneyString(getBalance(about))); + } + + public static void sendBalanceInfo(CommandSender to, Faction about) { + if (!shouldBeUsed()) { + FactionsPlugin.getInstance().log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); + return; + } + to.sendMessage(ChatColor.stripColor(String.format(TL.ECON_BALANCE.toString(), about.getTag(), Econ.moneyString(getBalance(about))))); + } + + public static boolean canIControlYou(EconomyParticipator i, EconomyParticipator you) { + Faction fI = RelationUtil.getFaction(i); + Faction fYou = RelationUtil.getFaction(you); + + // This is a system invoker. Accept it. + if (fI == null) { + return true; + } + + // Bypassing players can do any kind of transaction + if (i instanceof FPlayer && ((FPlayer) i).isAdminBypassing()) { + return true; + } + + // Players with the any withdraw can do. + if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer) i).getPlayer())) { + return true; + } + + // You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again. + if (i == you) { + return true; + } + + // A faction can always transfer away the money of it's members and its own money... + // This will however probably never happen as a faction does not have free will. + // Ohh by the way... Yes it could. For daily rent to the faction. + if (i == fI && fI == fYou) { + return true; + } + + // Factions can be controlled by members that are moderators... or any member if any member can withdraw. + if (you instanceof Faction && fI == fYou && (FactionsPlugin.getInstance().conf().economy().isBankMembersCanWithdraw() || ((FPlayer) i).getRole().value >= Role.MODERATOR.value)) { + return true; + } + + // Otherwise you may not! ;,,; + i.msg(TL.ECON_NOPERM, i.describeTo(i, true), you.describeTo(i)); + return false; + } + + public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) { + return transferMoney(invoker, from, to, amount, true); + } + + public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) { + if (!shouldBeUsed()) { + invoker.msg(TL.ECON_DISABLED); + return false; + } + + // The amount must be positive. + // If the amount is negative we must flip and multiply amount with -1. + if (amount < 0) { + amount *= -1; + EconomyParticipator temp = from; + from = to; + to = temp; + } + + // Check the rights + if (!canIControlYou(invoker, from)) { + return false; + } + + OfflinePlayer fromAcc = checkStatus(from.getOfflinePlayer()); + OfflinePlayer toAcc = checkStatus(to.getOfflinePlayer()); + + // Is there enough money for the transaction to happen? + if (!has(fromAcc, amount)) { + // There was not enough money to pay + if (invoker != null && notify) { + invoker.msg(TL.ECON_CANTAFFORD_TRANSFER, from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker)); + } + + return false; + } + + // Check if the new balance is over Essential's money cap. + if (Essentials.isOverBalCap(to, getBalance(toAcc) + amount)) { + invoker.msg(TL.ECON_OVER_BAL_CAP, amount); + return false; + } + + // Transfer money + + if (withdraw(fromAcc, amount)) { + if (deposit(toAcc, amount)) { + if (notify) { + sendTransferInfo(invoker, from, to, amount); + } + return true; + } else { + // transaction failed, refund account + deposit(fromAcc, amount); + } + } + + // if we get here something with the transaction failed + if (notify) { + invoker.msg(TL.ECON_TRANSFER_UNABLE, moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true)); + } + + return false; + } + + public static Set getFplayers(EconomyParticipator ep) { + Set fplayers = new HashSet<>(); + + if (ep != null) { + if (ep instanceof FPlayer) { + fplayers.add((FPlayer) ep); + } else if (ep instanceof Faction) { + fplayers.addAll(((Faction) ep).getFPlayers()); + } + } + + return fplayers; + } + + public static void sendTransferInfo(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) { + Set recipients = new HashSet<>(); + recipients.addAll(getFplayers(invoker)); + recipients.addAll(getFplayers(from)); + recipients.addAll(getFplayers(to)); + + if (invoker == null) { + for (FPlayer recipient : recipients) { + recipient.msg(TL.ECON_TRANSFER_NOINVOKER, moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); + } + } else if (invoker == from) { + for (FPlayer recipient : recipients) { + recipient.msg(TL.ECON_TRANSFER_GAVE, from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient)); + } + } else if (invoker == to) { + for (FPlayer recipient : recipients) { + recipient.msg(TL.ECON_TRANSFER_TOOK, to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient)); + } + } else { + for (FPlayer recipient : recipients) { + recipient.msg(TL.ECON_TRANSFER_TRANSFER, invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); + } + } + } + + public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis) { + if (!shouldBeUsed()) { + return true; + } + + boolean affordable = false; + double currentBalance = getBalance(ep); + + if (currentBalance >= delta) { + affordable = true; + } + + if (!affordable) { + if (toDoThis != null && !toDoThis.isEmpty()) { + ep.msg(TL.ECON_CANTAFFORD_AMOUNT, ep.describeTo(ep, true), moneyString(delta), toDoThis); + } + return false; + } + return true; + } + + public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) { + if (!shouldBeUsed()) { + return false; + } + + if (delta == 0) { + // no money actually transferred? +// ep.msg("%s didn't have to pay anything %s.", You, forDoingThis); // might be for gains, might be for losses + return true; + } + + OfflinePlayer acc = checkStatus(ep.getOfflinePlayer()); + + String You = ep.describeTo(ep, true); + + if (delta > 0) { + // The player should gain money + // The account might not have enough space + if (deposit(acc, delta)) { + modifyUniverseMoney(-delta); + if (forDoingThis != null && !forDoingThis.isEmpty()) { + ep.msg(TL.ECON_GAIN_SUCCESS, You, moneyString(delta), forDoingThis); + } + return true; + } else { + // transfer to account failed + if (forDoingThis != null && !forDoingThis.isEmpty()) { + ep.msg(TL.ECON_GAIN_FAILURE, You, moneyString(delta), forDoingThis); + } + return false; + } + } else { + // The player should loose money + // The player might not have enough. + + if (has(acc, -delta) && withdraw(acc, -delta)) { + // There is enough money to pay + modifyUniverseMoney(-delta); + if (forDoingThis != null && !forDoingThis.isEmpty()) { + ep.msg(TL.ECON_LOST_SUCCESS, You, moneyString(-delta), forDoingThis); + } + return true; + } else { + // There was not enough money to pay + if (toDoThis != null && !toDoThis.isEmpty()) { + ep.msg(TL.ECON_LOST_FAILURE, You, moneyString(-delta), toDoThis); + } + return false; + } + } + } + + public static String moneyString(double amount) { + return format.format(amount); + } + + // calculate the cost for claiming land + public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) { + if (!shouldBeUsed()) { + return 0d; + } + + // basic claim cost, plus land inflation cost, minus the potential bonus given for claiming from another faction + return FactionsPlugin.getInstance().conf().economy().getCostClaimWilderness() + (FactionsPlugin.getInstance().conf().economy().getCostClaimWilderness() * FactionsPlugin.getInstance().conf().economy().getClaimAdditionalMultiplier() * ownedLand) - (takingFromAnotherFaction ? FactionsPlugin.getInstance().conf().economy().getCostClaimFromFactionBonus() : 0); + } + + // calculate refund amount for unclaiming land + public static double calculateClaimRefund(int ownedLand) { + return calculateClaimCost(ownedLand - 1, false) * FactionsPlugin.getInstance().conf().economy().getClaimRefundMultiplier(); + } + + // calculate value of all owned land + public static double calculateTotalLandValue(int ownedLand) { + double amount = 0; + for (int x = 0; x < ownedLand; x++) { + amount += calculateClaimCost(x, false); + } + return amount; + } + + // calculate refund amount for all owned land + public static double calculateTotalLandRefund(int ownedLand) { + return calculateTotalLandValue(ownedLand) * FactionsPlugin.getInstance().conf().economy().getClaimRefundMultiplier(); + } + + + // -------------------------------------------- // + // Standard account management methods + // -------------------------------------------- // + + private static OfflinePlayer getOfflinePlayerForName(String name) { + try { + return Bukkit.getOfflinePlayer(UUID.fromString(name)); + } catch (IllegalArgumentException ex) { + return Bukkit.getOfflinePlayer(name); + } + } + + @Deprecated + public static boolean hasAccount(String name) { + return hasAccount(getOfflinePlayerForName(name)); + } + + public static boolean hasAccount(EconomyParticipator ep) { + return hasAccount(ep.getOfflinePlayer()); + } + + private static boolean hasAccount(OfflinePlayer op) { + return econ.hasAccount(op, getWorld(op)); + } + + @Deprecated + public static double getBalance(String account) { + return getBalance(getOfflinePlayerForName(account)); + } + + public static double getBalance(EconomyParticipator ep) { + return getBalance(ep.getOfflinePlayer()); + } + + private static double getBalance(OfflinePlayer op) { + return econ.getBalance(checkStatus(op), getWorld(op)); + } + + public static boolean has(EconomyParticipator ep, double amount) { + return has(ep.getOfflinePlayer(), amount); + } + + private static boolean has(OfflinePlayer op, double amount) { + return econ.has(checkStatus(op), getWorld(op), amount); + } + + private static final NumberFormat format = NumberFormat.getIntegerInstance(); + + @Deprecated + public static String getFriendlyBalance(UUID uuid) { + OfflinePlayer offline = Bukkit.getOfflinePlayer(uuid); + if (offline.getName() == null) { + return "0"; + } + return format.format(getBalance(offline)); + } + + public static String getFriendlyBalance(FPlayer player) { + OfflinePlayer p; + if ((p = player.getPlayer()) == null) { + return "0"; + } + return format.format(getBalance(p)); + } + + @Deprecated + public static boolean setBalance(String account, double amount) { + return setBalance(getOfflinePlayerForName(account), amount); + } + + public static boolean setBalance(EconomyParticipator ep, double amount) { + return setBalance(ep.getOfflinePlayer(), amount); + } + + private static boolean setBalance(OfflinePlayer op, double amount) { + double current = getBalance(op); // Already checks status + if (current > amount) { + return econ.withdrawPlayer(op, getWorld(op), current - amount).transactionSuccess(); + } else { + return econ.depositPlayer(op, getWorld(op), amount - current).transactionSuccess(); + } + } + + @Deprecated + public static boolean modifyBalance(String account, double amount) { + return modifyBalance(getOfflinePlayerForName(account), amount); + } + + public static boolean modifyBalance(EconomyParticipator ep, double amount) { + return modifyBalance(ep.getOfflinePlayer(), amount); + } + + private static boolean modifyBalance(OfflinePlayer op, double amount) { + if (amount < 0) { + return econ.withdrawPlayer(checkStatus(op), getWorld(op), -amount).transactionSuccess(); + } else { + return econ.depositPlayer(checkStatus(op), getWorld(op), amount).transactionSuccess(); + } + } + + @Deprecated + public static boolean deposit(String account, double amount) { + return deposit(getOfflinePlayerForName(account), amount); + } + + public static boolean deposit(EconomyParticipator ep, double amount) { + return deposit(ep.getOfflinePlayer(), amount); + } + + private static boolean deposit(OfflinePlayer op, double amount) { + return econ.depositPlayer(checkStatus(op), getWorld(op), amount).transactionSuccess(); + } + + @Deprecated + public static boolean withdraw(String account, double amount) { + return withdraw(getOfflinePlayerForName(account), amount); + } + + public static boolean withdraw(EconomyParticipator ep, double amount) { + return withdraw(ep.getOfflinePlayer(), amount); + } + + private static boolean withdraw(OfflinePlayer op, double amount) { + return econ.withdrawPlayer(checkStatus(op), getWorld(op), amount).transactionSuccess(); + } + + @Deprecated + public static void createAccount(String name) { + createAccount(getOfflinePlayerForName(name)); + } + + public static void createAccount(EconomyParticipator ep) { + createAccount(ep.getOfflinePlayer()); + } + + private static void createAccount(OfflinePlayer op) { + if (!econ.createPlayerAccount(op, getWorld(op))) { + FactionsPlugin.getInstance().getLogger().warning("FAILED TO CREATE ECONOMY ACCOUNT " + op.getName() + '/' + op.getUniqueId()); + } + } + + public static OfflinePlayer checkStatus(OfflinePlayer op) { + if (op.getName() == null || !op.getName().startsWith("faction-")) { + return op; + } + // We need to override the default money given to players. + String world = getWorld(op); + if (!hasAccount(op)) { + createAccount(op); + setBalance(op, 0); + } + return op; + } + + @Deprecated + public static boolean isUUID(String uuid) { + try { + UUID.fromString(uuid); + return true; + } catch (IllegalArgumentException ex) { + return false; + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/Essentials.java b/Factions/src/main/java/com/massivecraft/factions/integration/Essentials.java new file mode 100644 index 0000000..c7caf0e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/Essentials.java @@ -0,0 +1,106 @@ +package com.massivecraft.factions.integration; + +import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.Teleport; +import com.earth2me.essentials.Trade; +import com.earth2me.essentials.User; +import com.massivecraft.factions.*; +import com.massivecraft.factions.iface.EconomyParticipator; +import com.massivecraft.factions.listeners.EssentialsListener; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.struct.Permission; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; + +public class Essentials { + + private static IEssentials essentials; + + public static void setup(Plugin ess) { + essentials = (IEssentials) ess; + FactionsPlugin plugin = FactionsPlugin.getInstance(); + plugin.getLogger().info("Found and connected to Essentials"); + if (plugin.conf().factions().other().isDeleteEssentialsHomes()) { + plugin.getLogger().info("Based on main.conf will delete Essentials player homes in their old faction when they leave"); + plugin.getServer().getPluginManager().registerEvents(new EssentialsListener(essentials), plugin); + } + if (plugin.conf().factions().homes().isTeleportCommandEssentialsIntegration()) { + plugin.getLogger().info("Using Essentials for teleportation"); + } + } + + // return false if feature is disabled or Essentials isn't available + public static boolean handleTeleport(Player player, Location loc) { + if (!FactionsPlugin.getInstance().conf().factions().homes().isTeleportCommandEssentialsIntegration() || essentials == null) { + return false; + } + + Teleport teleport = essentials.getUser(player).getTeleport(); + Trade trade = new Trade(FactionsPlugin.getInstance().conf().economy().getCostHome(), essentials); + try { + teleport.teleport(loc, trade); + } catch (Exception e) { + player.sendMessage(ChatColor.RED.toString() + e.getMessage()); + } + return true; + } + + public static boolean handleDefaultTeleport(Player player, Location loc) { + if (!FactionsPlugin.getInstance().conf().factions().homes().isTeleportCommandEssentialsIntegration() || essentials == null) { + return true; + } + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + + if(fPlayer.isAdminBypassing() || Permission.BYPASS_REMOVAL.has(fPlayer.getPlayer()))return true; + + Faction factionAt = Board.getInstance().getFactionAt(new FLocation(loc)); + Relation to = fPlayer.getRelationTo(factionAt); + + boolean returnb = true; + + if((to.isNeutral() || to.isEnemy()) && !(factionAt.isWarZone() || factionAt.isSafeZone() || factionAt.isWilderness())){ + User user = essentials.getUser(player); + + //Clone list so we can modify the homes + for(String home : new ArrayList<>(user.getHomes())){ + try { + Location homeLoc = user.getHome(home); + + Faction facAtHome = Board.getInstance().getFactionAt(new FLocation(homeLoc)); + + Relation relationTo = fPlayer.getRelationTo(facAtHome); + if((relationTo.isNeutral() || relationTo.isEnemy()) && !(facAtHome.isWarZone() && facAtHome.isSafeZone() && facAtHome.isWilderness())){ + user.delHome(home); + + player.sendMessage(ChatColor.RED + "One of your homes was removed due to it being in an enemy or neutral claim!"); + returnb = false; + } + } catch (Exception e) { + player.sendMessage(ChatColor.RED.toString() + e.getMessage()); + } + } + } + return returnb; + } + + public static boolean isVanished(Player player) { + return essentials != null && player != null && essentials.getUser(player).isVanished(); + } + + public static boolean isOverBalCap(EconomyParticipator participator, double amount) { + if (essentials == null) { + return false; + } + + return amount > essentials.getSettings().getMaxMoney().doubleValue(); + } + + public static Plugin getEssentials() { + return essentials; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/IntegrationManager.java b/Factions/src/main/java/com/massivecraft/factions/integration/IntegrationManager.java new file mode 100644 index 0000000..cdca5c5 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/IntegrationManager.java @@ -0,0 +1,113 @@ +package com.massivecraft.factions.integration; + +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.SimplePluginManager; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; +import java.util.logging.Level; + +public class IntegrationManager implements Listener { + @SuppressWarnings("Convert2MethodRef") + private enum Integration { + ESS("Essentials", Essentials::setup), + LUCKPERMS("LuckPerms", (plugin) -> { + String[] version = plugin.getDescription().getVersion().split("\\."); + boolean notSupported = true; + try { + int major = Integer.parseInt(version[0]); + int minor = Integer.parseInt(version[1]); + if ((major == 5 && minor > 0) || major > 5) { + notSupported = false; + } + } catch (NumberFormatException ignored) { + } + if (notSupported) { + FactionsPlugin.getInstance().log("Found an outdated LuckPerms. With LuckPerms 5.1.0 and above, FactionsUUID supports permission contexts!"); + } else { + if (LuckPerms.init(FactionsPlugin.getInstance())) { + FactionsPlugin.getInstance().luckpermsEnabled(); + } + } + }), + PLACEHOLDERAPI("PlaceholderAPI", (p) -> FactionsPlugin.getInstance().setupPlaceholderAPI()), + PLACEHOLDERAPI_OTHER("MVdWPlaceholderAPI", (p) -> FactionsPlugin.getInstance().setupOtherPlaceholderAPI()), + WORLDGUARD("WorldGuard", (plugin) -> { + FactionsPlugin f = FactionsPlugin.getInstance(); + if (!f.conf().worldGuard().isChecking() && !f.conf().worldGuard().isBuildPriority()) { + return; + } + + String version = plugin.getDescription().getVersion(); + if (version.startsWith("6")) { + f.setWorldGuard(new Worldguard6(plugin)); + f.getLogger().info("Found support for WorldGuard version " + version); + } else if (version.startsWith("7")) { + f.setWorldGuard(new Worldguard7()); + f.getLogger().info("Found support for WorldGuard version " + version); + } else { + f.log(Level.WARNING, "Found WorldGuard but couldn't support this version: " + version); + } + }); + + private static final Map> STARTUP_MAP = new HashMap<>(); + + static { + for (Integration integration : values()) { + STARTUP_MAP.put(integration.pluginName, integration.startup); + } + } + + static Consumer getStartup(String pluginName) { + return STARTUP_MAP.getOrDefault(pluginName, Integration::omNomNom); + } + + private static void omNomNom(Plugin plugin) { + // NOOP + } + + private final String pluginName; + private final Consumer startup; + + Integration(String pluginName, Consumer startup) { + this.pluginName = pluginName; + this.startup = startup; + } + } + + public IntegrationManager(FactionsPlugin plugin) { + try { + Field depGraph = SimplePluginManager.class.getDeclaredField("dependencyGraph"); + depGraph.setAccessible(true); + Object graph = depGraph.get(plugin.getServer().getPluginManager()); + Method putEdge = graph.getClass().getDeclaredMethod("putEdge", Object.class, Object.class); + putEdge.setAccessible(true); + for (String depend : Integration.STARTUP_MAP.keySet()) { + putEdge.invoke(graph, plugin.getDescription().getName(), depend); + } + } catch (Exception ignored) { + } + for (Integration integration : Integration.values()) { + Plugin plug = plugin.getServer().getPluginManager().getPlugin(integration.pluginName); + if (plug != null && plug.isEnabled()) { + try { + integration.startup.accept(plug); + } catch (Exception e) { + plugin.getLogger().log(Level.WARNING, "Failed to start " + integration.pluginName + " integration", e); + } + } + } + } + + @EventHandler + public void onPluginEnabled(PluginEnableEvent event) { + Integration.getStartup(event.getPlugin().getName()).accept(event.getPlugin()); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/LuckPerms.java b/Factions/src/main/java/com/massivecraft/factions/integration/LuckPerms.java new file mode 100644 index 0000000..fc7bb03 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/LuckPerms.java @@ -0,0 +1,35 @@ +package com.massivecraft.factions.integration; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.integration.permcontext.LuckpermsContextCalculator; +import net.luckperms.api.LuckPermsProvider; + +import java.util.logging.Level; + +public class LuckPerms { + private static LuckpermsContextCalculator calculator; + + public static boolean init(FactionsPlugin plugin) { + calculator = new LuckpermsContextCalculator(); + try { + net.luckperms.api.LuckPerms api = LuckPermsProvider.get(); + api.getContextManager().registerCalculator(calculator); + } catch (Exception e) { + plugin.getLogger().log(Level.SEVERE, "Failed to connect to LuckPerms!", e); + return false; + } + plugin.log("Successfully hooked into LuckPerms for permission contexts!"); + return true; + } + + public static void shutdown(FactionsPlugin plugin) { + if (calculator != null) { + try { + net.luckperms.api.LuckPerms api = LuckPermsProvider.get(); + api.getContextManager().unregisterCalculator(calculator); + } catch (Exception e) { + plugin.getLogger().log(Level.SEVERE, "Failed to unregister contexts with LuckPerms!", e); + } + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/Worldguard7.java b/Factions/src/main/java/com/massivecraft/factions/integration/Worldguard7.java new file mode 100644 index 0000000..5cc7d15 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/Worldguard7.java @@ -0,0 +1,72 @@ +package com.massivecraft.factions.integration; + +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldguard.LocalPlayer; +import com.sk89q.worldguard.WorldGuard; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.flags.Flags; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import com.sk89q.worldguard.protection.regions.RegionContainer; +import com.sk89q.worldguard.protection.regions.RegionQuery; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; + +public class Worldguard7 implements IWorldguard { + + // PVP Flag check + // Returns: + // True: PVP is allowed + // False: PVP is disallowed + public boolean isPVP(Player player) { + LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player); + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = container.createQuery(); + + return query.testState(localPlayer.getLocation(), localPlayer, Flags.PVP); + } + + // Check if player can build at location by worldguards rules. + // Returns: + // True: Player can build in the region. + // False: Player can not build in the region. + public boolean playerCanBuild(Player player, Location loc) { + LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player); + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = container.createQuery(); + + return query.testBuild(localPlayer.getLocation(), localPlayer); + } + + public boolean checkForRegionsInChunk(Chunk chunk) { + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionManager regions = container.get(BukkitAdapter.adapt(chunk.getWorld())); + if (regions == null) { + return false; + } + + World world = chunk.getWorld(); + int minChunkX = chunk.getX() << 4; + int minChunkZ = chunk.getZ() << 4; + int maxChunkX = minChunkX + 15; + int maxChunkZ = minChunkZ + 15; + + int worldHeight = world.getMaxHeight(); // Allow for heights other than default + + BlockVector3 min = BlockVector3.at(minChunkX, 0, minChunkZ); + BlockVector3 max = BlockVector3.at(maxChunkX, worldHeight, maxChunkZ); + ProtectedRegion region = new ProtectedCuboidRegion("wgregionflagcheckforfactions", min, max); + ApplicableRegionSet set = regions.getApplicableRegions(region); + + return set.size() > 0; + } + + public String getVersion() { + return WorldGuardPlugin.inst().getDescription().getVersion(); + } +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/Context.java b/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/Context.java new file mode 100644 index 0000000..dce781c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/Context.java @@ -0,0 +1,53 @@ +package com.massivecraft.factions.integration.permcontext; + +import org.bukkit.entity.Player; + +import java.util.Set; + +/** + * A context that can be registered to the {@link ContextManager}. + * + * @see ContextManager#registerContext(Context) + */ +public interface Context { + /** + * Gets the context name, without any namespacing. Format should be + * lowercase words separated by hyphens ({@code -}). + * + * @return name + */ + String getName(); + + /** + * Gets the namespace for this context. Namespaces should be the plugin + * name, lowercased. Other plugins using this class should not use + * {@code factionsuuid} as their namespace. + * + * @return namespace + */ + String getNamespace(); + + /** + * Gets the context name with namespace. The format is {@code namespace:name}. + * + * @return namespaced name + */ + default String getNamespacedName() { + return this.getNamespace() + ':' + this.getName(); + } + + /** + * Gets known possible values for the context. + * + * @return immutable set of possible values + */ + Set getPossibleValues(); + + /** + * Gets the values for a given player at this moment in time. + * + * @param player player + * @return immutable set of current values + */ + Set getValues(Player player); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/ContextManager.java b/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/ContextManager.java new file mode 100644 index 0000000..e6fedc4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/ContextManager.java @@ -0,0 +1,89 @@ +package com.massivecraft.factions.integration.permcontext; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; +import com.google.common.collect.Multimaps; +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +/** + * Plugin-agnostic registration of contexts. Other plugins can hook into this. + */ +public class ContextManager implements Listener { + private static Multimap registeredContexts; + + /** + * Should be called by FactionsUUID only. + * + * @param plugin the plugin + */ + public static void init(FactionsPlugin plugin) { + registeredContexts = Multimaps.synchronizedMultimap(ArrayListMultimap.create()); + registeredContexts.putAll(plugin.getName(), Arrays.asList(Contexts.values())); + plugin.getServer().getPluginManager().registerEvents(new ContextManager(), plugin); + } + + /** + * Should be called by FactionsUUID only. + */ + public static void shutdown() { + registeredContexts = null; + } + + /** + * Gets currently registered contexts. + * + * @return immutable set of registered contexts + */ + public static Set getContexts() { + if (registeredContexts == null) { + return Collections.emptySet(); + } + return Collections.unmodifiableSet(new HashSet<>(registeredContexts.values())); + } + + /** + * Registers a context. Should be called after FactionsUUID is loaded or + * reloaded. Easiest strategy is to run in onEnable and on {@code PluginEnableEvent}. + * + * @param context context + */ + public static void registerContext(Context context) { + if (registeredContexts == null) { + throw new IllegalStateException("Cannot register contexts before FactionsUUID finishes loading!"); + } + Objects.requireNonNull(context); + if (context.getNamespacedName().indexOf(':') == -1) { + throw new IllegalArgumentException("Invalid namespaced name " + context.getNamespacedName()); + } + if (context.getNamespace().equalsIgnoreCase(Contexts.FACTIONSUUID_NAMESPACE) || + context.getNamespacedName().split(":")[0].equalsIgnoreCase(Contexts.FACTIONSUUID_NAMESPACE)) { + throw new IllegalArgumentException("Cannot register contexts using namespace 'factionsuuid'"); + } + + registeredContexts.put(JavaPlugin.getProvidingPlugin(context.getClass()).getName(), context); + } + + private ContextManager() { + // Honk! + } + + @EventHandler + public void onDisable(PluginDisableEvent event) { + if (event.getPlugin().equals(FactionsPlugin.getInstance())) { + return; + } + if (registeredContexts != null) { + registeredContexts.removeAll(event.getPlugin().getName()); + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/Contexts.java b/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/Contexts.java new file mode 100644 index 0000000..0f085d7 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/Contexts.java @@ -0,0 +1,79 @@ +package com.massivecraft.factions.integration.permcontext; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Default FactionsUUID contexts. + */ +public enum Contexts implements Context { + TERRITORY_RELATION((player) -> + FPlayers.getInstance().getByPlayer(player).getRelationTo(Board.getInstance().getFactionAt(new FLocation(player.getLocation()))).getNameInASet(), + Arrays.stream(Relation.values()).map(relation -> relation.name().toLowerCase()).collect(Collectors.toSet())), + ROLE_AT_LEAST((player) -> + { + FPlayer p = FPlayers.getInstance().getByPlayer(player); + return p.hasFaction() ? p.getRole().getRoleNamesAtOrBelow() : Collections.emptySet(); + }, + Arrays.stream(Role.values()).map(role -> role.name().toLowerCase()).collect(Collectors.toSet())), + ROLE_AT_MOST((player) -> + { + FPlayer p = FPlayers.getInstance().getByPlayer(player); + return p.hasFaction() ? p.getRole().getRoleNamesAtOrAbove() : Collections.emptySet(); + }, + Arrays.stream(Role.values()).map(role -> role.name().toLowerCase()).collect(Collectors.toSet())); + + + /** + * The FactionsUUID namespace. Should not be used by another plugin. + */ + public static final String FACTIONSUUID_NAMESPACE = "factionsuuid"; + + private final Function> function; + private final String name; + private final String namespacedName; + private final Set possibilities; + + Contexts(Function> function, Set possibilities) { + this.function = function; + this.name = this.name().toLowerCase().replace('_', '-'); + this.namespacedName = FACTIONSUUID_NAMESPACE + ':' + this.name; + this.possibilities = Collections.unmodifiableSet(possibilities); + } + + @Override + public String getName() { + return this.name; + } + + @Override + public String getNamespace() { + return FACTIONSUUID_NAMESPACE; + } + + @Override + public String getNamespacedName() { + return this.namespacedName; + } + + @Override + public Set getPossibleValues() { + return this.possibilities; + } + + @Override + public Set getValues(Player player) { + return this.function.apply(player); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/LuckpermsContextCalculator.java b/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/LuckpermsContextCalculator.java new file mode 100644 index 0000000..e7d92ca --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/integration/permcontext/LuckpermsContextCalculator.java @@ -0,0 +1,29 @@ +package com.massivecraft.factions.integration.permcontext; + +import net.luckperms.api.context.ContextCalculator; +import net.luckperms.api.context.ContextConsumer; +import net.luckperms.api.context.ContextSet; +import net.luckperms.api.context.ImmutableContextSet; +import org.bukkit.entity.Player; + +public class LuckpermsContextCalculator implements ContextCalculator { + @Override + public void calculate(Player player, ContextConsumer contextConsumer) { + for (Context context : ContextManager.getContexts()) { + for (String value : context.getValues(player)) { + contextConsumer.accept(context.getNamespacedName(), value); + } + } + } + + @Override + public ContextSet estimatePotentialContexts() { + ImmutableContextSet.Builder builder = ImmutableContextSet.builder(); + for (Context context : ContextManager.getContexts()) { + for (String value : context.getPossibleValues()) { + builder.add(context.getNamespacedName(), value); + } + } + return builder.build(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/DTRControl.java b/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/DTRControl.java new file mode 100644 index 0000000..b2d4938 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/DTRControl.java @@ -0,0 +1,149 @@ +package com.massivecraft.factions.landraidcontrol; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.event.DTRLossEvent; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public class DTRControl implements LandRaidControl { + private static FactionsPlugin plugin; + + public static String round(double dtr) { + return BigDecimal.valueOf(dtr).setScale(conf().getDecimalDigits(), RoundingMode.UP).toPlainString(); + } + + private static MainConfig.Factions.LandRaidControl.DTR conf() { + return plugin.conf().factions().landRaidControl().dtr(); + } + + public DTRControl() { + plugin = FactionsPlugin.getInstance(); + } + + @Override + public boolean isRaidable(Faction faction) { + return !faction.isPeaceful() && faction.getDTR() <= 0; + } + + @Override + public boolean hasLandInflation(Faction faction) { + return false; // fail all attempts at claiming + } + + @Override + public int getLandLimit(Faction faction) { + return conf().getLandStarting() + (faction.getFPlayers().size() * conf().getLandPerPlayer()); + } + + @Override + public boolean canJoinFaction(Faction faction, FPlayer player, CommandContext context) { + if (faction.isFrozenDTR() && conf().isFreezePreventsJoin()) { + context.msg(TL.DTR_CANNOT_FROZEN); + return false; + } + return true; + } + + @Override + public boolean canLeaveFaction(FPlayer player) { + if (player.getFaction().isFrozenDTR() && conf().isFreezePreventsLeave()) { + player.msg(TL.DTR_CANNOT_FROZEN); + return false; + } + return true; + } + + @Override + public boolean canDisbandFaction(Faction faction, CommandContext context) { + if (faction.isFrozenDTR() && conf().isFreezePreventsDisband()) { + context.msg(TL.DTR_CANNOT_FROZEN); + return false; + } + return true; + } + + @Override + public boolean canKick(FPlayer toKick, CommandContext context) { + if (toKick.getFaction().isNormal()) { + Faction faction = toKick.getFaction(); + if (faction.isFrozenDTR() && conf().getFreezeKickPenalty() > 0) { + faction.setDTR(Math.min(conf().getMinDTR(), faction.getDTR() - conf().getFreezeKickPenalty())); + context.msg(TL.DTR_KICK_PENALTY); + } + } + return true; + } + + @Override + public void onRespawn(FPlayer player) { + // Handled on death + } + + @Override + public void update(FPlayer player) { + if (player.getFaction().isNormal()) { + this.updateDTR(player.getFaction()); + } + } + + @Override + public void onDeath(Player player) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + Faction faction = fplayer.getFaction(); + if (!faction.isNormal()) { + return; + } + + DTRLossEvent dtrLossEvent = new DTRLossEvent(faction, fplayer); + + // call Event + Bukkit.getPluginManager().callEvent(dtrLossEvent); + + if (!dtrLossEvent.isCancelled()) { + faction.setDTR(Math.max(conf().getMinDTR(), faction.getDTR() - conf().getLossPerDeath(player.getWorld()))); + faction.setFrozenDTR(System.currentTimeMillis() + (conf().getFreezeTime() * 1000)); + } + } + + @Override + public void onQuit(FPlayer player) { + this.update(player); + } + + @Override + public void onJoin(FPlayer player) { + if (player.getFaction().isNormal()) { + this.updateDTR(player.getFaction(), 1); + } + } + + public void updateDTR(Faction faction) { + this.updateDTR(faction, 0); + } + + public void updateDTR(Faction faction, int minusPlayer) { + long now = System.currentTimeMillis(); + if (faction.getFrozenDTRUntilTime() > now) { + // Not yet time to regen + return; + } + long millisPassed = now - Math.max(faction.getLastDTRUpdateTime(), faction.getFrozenDTRUntilTime()); + long onlineInEnabledWorlds = faction.getOnlinePlayers().stream().filter(p -> plugin.worldUtil().isEnabled(p.getWorld())).count(); + double rate = Math.min(conf().getRegainPerMinuteMaxRate(), Math.max(0, onlineInEnabledWorlds - minusPlayer) * conf().getRegainPerMinutePerPlayer()); + double regain = (millisPassed / (60D * 1000D)) * rate; + faction.setDTR(Math.min(faction.getDTRWithoutUpdate() + regain, this.getMaxDTR(faction))); + } + + public double getMaxDTR(Faction faction) { + return Math.min(conf().getStartingDTR() + (conf().getPerPlayer() * faction.getFPlayers().size()), conf().getMaxDTR()); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/LandRaidControl.java b/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/LandRaidControl.java new file mode 100644 index 0000000..4bb65f0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/LandRaidControl.java @@ -0,0 +1,46 @@ +package com.massivecraft.factions.landraidcontrol; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.cmd.CommandContext; +import org.bukkit.entity.Player; + +public interface LandRaidControl { + static LandRaidControl getByName(String name) { + switch (name.toLowerCase()) { + case "dtr": + return new DTRControl(); + case "power": + default: + return new PowerControl(); + } + } + + boolean isRaidable(Faction faction); + + boolean hasLandInflation(Faction faction); + + int getLandLimit(Faction faction); + + default int getPossibleClaimCount(Faction faction) { + return this.getLandLimit(faction) - faction.getLandRounded(); + } + + boolean canJoinFaction(Faction faction, FPlayer player, CommandContext context); + + boolean canLeaveFaction(FPlayer player); + + boolean canDisbandFaction(Faction faction, CommandContext context); + + boolean canKick(FPlayer toKick, CommandContext context); + + void onRespawn(FPlayer player); + + void onDeath(Player player); + + void onQuit(FPlayer player); + + void onJoin(FPlayer player); + + void update(FPlayer player); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/PowerControl.java b/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/PowerControl.java new file mode 100644 index 0000000..f43062a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/landraidcontrol/PowerControl.java @@ -0,0 +1,127 @@ +package com.massivecraft.factions.landraidcontrol; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.event.PowerLossEvent; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +public class PowerControl implements LandRaidControl { + @Override + public boolean isRaidable(Faction faction) { + return FactionsPlugin.getInstance().conf().factions().landRaidControl().power().isRaidability() && faction.isNormal() && !faction.isPeaceful() && faction.getLandRounded() >= faction.getPowerRounded(); + } + + @Override + public boolean hasLandInflation(Faction faction) { + return !faction.isPeaceful() && faction.getLandRounded() > faction.getPowerRounded(); + } + + @Override + public int getLandLimit(Faction faction) { + return faction.getPowerRounded(); + } + + @Override + public boolean canJoinFaction(Faction faction, FPlayer player, CommandContext context) { + if (!FactionsPlugin.getInstance().conf().factions().landRaidControl().power().canLeaveWithNegativePower() && player.getPower() < 0) { + if (context != null) { + context.msg(TL.COMMAND_JOIN_NEGATIVEPOWER, player.describeTo(context.fPlayer, true)); + } + return false; + } + return true; + } + + @Override + public boolean canLeaveFaction(FPlayer player) { + if (!FactionsPlugin.getInstance().conf().factions().landRaidControl().power().canLeaveWithNegativePower() && player.getPower() < 0) { + player.msg(TL.LEAVE_NEGATIVEPOWER); + return false; + } + return true; + } + + @Override + public boolean canDisbandFaction(Faction faction, CommandContext context) { + return true; + } + + @Override + public boolean canKick(FPlayer toKick, CommandContext context) { + if (!FactionsPlugin.getInstance().conf().factions().landRaidControl().power().canLeaveWithNegativePower() && toKick.getPower() < 0) { + context.msg(TL.COMMAND_KICK_NEGATIVEPOWER); + return false; + } + return true; + } + + @Override + public void onRespawn(FPlayer player) { + this.update(player); // update power, so they won't have gained any while dead + } + + @Override + public void onQuit(FPlayer player) { + this.update(player); // Make sure player's power is up to date when they log off. + } + + @Override + public void update(FPlayer player) { + player.updatePower(); + } + + @Override + public void onJoin(FPlayer player) { + player.losePowerFromBeingOffline(); + } + + @Override + public void onDeath(Player player) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + Faction faction = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); + + PowerLossEvent powerLossEvent = new PowerLossEvent(faction, fplayer); + // Check for no power loss conditions + if (faction.isWarZone()) { + // war zones always override worldsNoPowerLoss either way, thus this layout + if (!FactionsPlugin.getInstance().conf().factions().landRaidControl().power().isWarZonePowerLoss()) { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WARZONE.toString()); + powerLossEvent.setCancelled(true); + } + if (FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getWorldsNoPowerLoss().contains(player.getWorld().getName())) { + powerLossEvent.setMessage(TL.PLAYER_POWER_LOSS_WARZONE.toString()); + } + } else if (faction.isWilderness() && !FactionsPlugin.getInstance().conf().factions().landRaidControl().power().isWildernessPowerLoss() && !FactionsPlugin.getInstance().conf().factions().protection().getWorldsNoWildernessProtection().contains(player.getWorld().getName())) { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WILDERNESS.toString()); + powerLossEvent.setCancelled(true); + } else if (FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getWorldsNoPowerLoss().contains(player.getWorld().getName())) { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WORLD.toString()); + powerLossEvent.setCancelled(true); + } else if (FactionsPlugin.getInstance().conf().factions().landRaidControl().power().isPeacefulMembersDisablePowerLoss() && fplayer.hasFaction() && fplayer.getFaction().isPeaceful()) { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_PEACEFUL.toString()); + powerLossEvent.setCancelled(true); + } else { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOW.toString()); + } + + // call Event + Bukkit.getPluginManager().callEvent(powerLossEvent); + + fplayer.onDeath(); + if (!powerLossEvent.isCancelled()) { + fplayer.alterPower(-FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getLossPerDeath()); + } + // Send the message from the powerLossEvent + final String msg = powerLossEvent.getMessage(); + if (msg != null && !msg.isEmpty()) { + fplayer.msg(msg, fplayer.getPowerRounded(), fplayer.getPowerMaxRounded()); + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/AbstractListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/AbstractListener.java new file mode 100644 index 0000000..d90200b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/AbstractListener.java @@ -0,0 +1,371 @@ +package com.massivecraft.factions.listeners; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.TextUtil; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.Player; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.entity.Wither; +import org.bukkit.entity.WitherSkull; +import org.bukkit.entity.minecart.ExplosiveMinecart; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Listener; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + + +public abstract class AbstractListener implements Listener { + public boolean playerCanInteractHere(Player player, Location location) { + return canInteractHere(player, location); + } + + public static boolean canInteractHere(Player player, Location location) { + String name = player.getName(); + if (FactionsPlugin.getInstance().conf().factions().protection().getPlayersWhoBypassAllProtection().contains(name)) { + return true; + } + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me.isAdminBypassing()) { + return true; + } + + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getInstance().getFactionAt(loc); + + if (FactionsPlugin.getInstance().getLandRaidControl().isRaidable(otherFaction)) { + return true; + } + + MainConfig.Factions.Protection protection = FactionsPlugin.getInstance().conf().factions().protection(); + if (otherFaction.isWilderness()) { + if (!protection.isWildernessDenyUsage() || protection.getWorldsNoWildernessProtection().contains(location.getWorld().getName())) { + return true; // This is not faction territory. Use whatever you like here. + } + me.msg(TL.PLAYER_USE_WILDERNESS, "this"); + return false; + } else if (otherFaction.isSafeZone()) { + if (!protection.isSafeZoneDenyUsage() || Permission.MANAGE_SAFE_ZONE.has(player)) { + return true; + } + me.msg(TL.PLAYER_USE_SAFEZONE, "this"); + return false; + } else if (otherFaction.isWarZone()) { + if (!protection.isWarZoneDenyUsage() || Permission.MANAGE_WAR_ZONE.has(player)) { + return true; + } + me.msg(TL.PLAYER_USE_WARZONE, "this"); + + return false; + } + + boolean access = otherFaction.hasAccess(me, PermissibleAction.ITEM); + + // Cancel if we are not in our own territory + if (!access) { + me.msg(TL.PLAYER_USE_TERRITORY, "this", otherFaction.getTag(me.getFaction())); + return false; + } + + // Also cancel if player doesn't have ownership rights for this claim + if (FactionsPlugin.getInstance().conf().factions().ownedArea().isEnabled() && FactionsPlugin.getInstance().conf().factions().ownedArea().isDenyUsage() && !otherFaction.playerHasOwnershipRights(me, loc)) { + me.msg(TL.PLAYER_USE_OWNED, "this", otherFaction.getOwnerListString(loc)); + return false; + } + + return true; + } + + protected void handleExplosion(Location loc, Entity boomer, Cancellable event, List blockList) { + if (!FactionsPlugin.getInstance().worldUtil().isEnabled(loc.getWorld())) { + return; + } + + if (explosionDisallowed(boomer, new FLocation(loc))) { + event.setCancelled(true); + return; + } + + List chunks = blockList.stream().map(Block::getChunk).distinct().collect(Collectors.toList()); + if (chunks.removeIf(chunk -> explosionDisallowed(boomer, new FLocation(chunk)))) { + blockList.removeIf(block -> !chunks.contains(block.getChunk())); + } + + if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && FactionsPlugin.getInstance().conf().exploits().isTntWaterlog()) { + // TNT in water/lava doesn't normally destroy any surrounding blocks, which is usually desired behavior, but... + // this change below provides workaround for waterwalling providing perfect protection, + // and makes cheap (non-obsidian) TNT cannons require minor maintenance between shots + Block center = loc.getBlock(); + if (center.isLiquid()) { + // a single surrounding block in all 6 directions is broken if the material is weak enough + List targets = new ArrayList<>(); + targets.add(center.getRelative(0, 0, 1)); + targets.add(center.getRelative(0, 0, -1)); + targets.add(center.getRelative(0, 1, 0)); + targets.add(center.getRelative(0, -1, 0)); + targets.add(center.getRelative(1, 0, 0)); + targets.add(center.getRelative(-1, 0, 0)); + for (Block target : targets) { + // TODO get resistance value via NMS for future-proofing + switch (target.getType()) { + case AIR: + case BEDROCK: + case WATER: + case LAVA: + case OBSIDIAN: + case NETHER_PORTAL: + case ENCHANTING_TABLE: + case ANVIL: + case CHIPPED_ANVIL: + case DAMAGED_ANVIL: + case END_PORTAL: + case END_PORTAL_FRAME: + case ENDER_CHEST: + continue; + } + if (!explosionDisallowed(boomer, new FLocation(target.getLocation()))) { + target.breakNaturally(); + } + } + } + } + } + + private boolean explosionDisallowed(Entity boomer, FLocation location) { + Faction faction = Board.getInstance().getFactionAt(location); + boolean online = !FactionsPlugin.getInstance().getConfigManager().getMainConfig().onlineChecks().doOnlineChecks() || faction.hasPlayersOnline(); + if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && FactionsPlugin.getInstance().conf().factions().specialCase().isPeacefulTerritoryDisableBoom())) { + // faction is peaceful and has explosions set to disabled + return true; + } + MainConfig.Factions.Protection protection = FactionsPlugin.getInstance().conf().factions().protection(); + if (boomer instanceof Creeper && ((faction.isWilderness() && protection.isWildernessBlockCreepers() && !protection.getWorldsNoWildernessProtection().contains(location.getWorldName())) || + (faction.isNormal() && (online ? protection.isTerritoryBlockCreepers() : protection.isTerritoryBlockCreepersWhenOffline())) || + (faction.isWarZone() && protection.isWarZoneBlockCreepers()) || + faction.isSafeZone())) { + // creeper which needs prevention + return true; + } else if ( + (boomer instanceof Fireball || boomer instanceof WitherSkull || boomer instanceof Wither) && ((faction.isWilderness() && protection.isWildernessBlockFireballs() && !protection.getWorldsNoWildernessProtection().contains(location.getWorldName())) || + (faction.isNormal() && (online ? protection.isTerritoryBlockFireballs() : protection.isTerritoryBlockFireballsWhenOffline())) || + (faction.isWarZone() && protection.isWarZoneBlockFireballs()) || + faction.isSafeZone())) { + // ghast fireball which needs prevention + // it's a bit crude just using fireball protection for Wither boss too, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever + return true; + } else if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && ((faction.isWilderness() && protection.isWildernessBlockTNT() && !protection.getWorldsNoWildernessProtection().contains(location.getWorldName())) || + (faction.isNormal() && (online ? protection.isTerritoryBlockTNT() : protection.isTerritoryBlockTNTWhenOffline())) || + (faction.isWarZone() && protection.isWarZoneBlockTNT()) || + (faction.isSafeZone() && protection.isSafeZoneBlockTNT()))) { + // TNT which needs prevention + return true; + } else if (((faction.isWilderness() && protection.isWildernessBlockOtherExplosions() && !protection.getWorldsNoWildernessProtection().contains(location.getWorldName())) || + (faction.isNormal() && (online ? protection.isTerritoryBlockOtherExplosions() : protection.isTerritoryBlockOtherExplosionsWhenOffline())) || + (faction.isWarZone() && protection.isWarZoneBlockOtherExplosions()) || + (faction.isSafeZone() && protection.isSafeZoneBlockOtherExplosions()))) { + return true; + } + return false; + } + + public boolean canPlayerUseBlock(Player player, Material material, Location location, boolean justCheck) { + return canUseBlock(player, material, location, justCheck); + } + + public static boolean canUseBlock(Player player, Material material, Location location, boolean justCheck) { + if (FactionsPlugin.getInstance().conf().factions().protection().getPlayersWhoBypassAllProtection().contains(player.getName())) { + return true; + } + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me.isAdminBypassing()) { + return true; + } + + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getInstance().getFactionAt(loc); + + // no door/chest/whatever protection in wilderness, war zones, or safe zones + if (!otherFaction.isNormal()) { + switch (material) { + case ITEM_FRAME: + case ARMOR_STAND: + return canInteractHere(player, location); + } + return true; + } + + if (FactionsPlugin.getInstance().getLandRaidControl().isRaidable(otherFaction)) { + return true; + } + + PermissibleAction action = null; + + if(!material.toString().contains("DIODE")){ + switch (material) { + case LEVER: + action = PermissibleAction.LEVER; + break; + case STONE_BUTTON: + case BIRCH_BUTTON: + case ACACIA_BUTTON: + case DARK_OAK_BUTTON: + case JUNGLE_BUTTON: + case OAK_BUTTON: + case SPRUCE_BUTTON: + action = PermissibleAction.BUTTON; + break; + case DARK_OAK_DOOR: + case ACACIA_DOOR: + case BIRCH_DOOR: + case IRON_DOOR: + case JUNGLE_DOOR: + case SPRUCE_DOOR: + case ACACIA_TRAPDOOR: + case OAK_DOOR: + case BIRCH_TRAPDOOR: + case DARK_OAK_TRAPDOOR: + case IRON_TRAPDOOR: + case JUNGLE_TRAPDOOR: + case OAK_TRAPDOOR: + case SPRUCE_TRAPDOOR: + action = PermissibleAction.DOOR; + break; + case CHEST: + case ENDER_CHEST: + case TRAPPED_CHEST: + case BARREL: + case FURNACE: + case DROPPER: + case DISPENSER: + case HOPPER: + case BLAST_FURNACE: + case CAULDRON: + case CAMPFIRE: + case BREWING_STAND: + case CARTOGRAPHY_TABLE: + case GRINDSTONE: + case SMOKER: + case STONECUTTER: + case LECTERN: + case ITEM_FRAME: + case JUKEBOX: + case ARMOR_STAND: + case REPEATER: + case ENCHANTING_TABLE: + case FARMLAND: + case BEACON: + case ANVIL: + case CHIPPED_ANVIL: + case DAMAGED_ANVIL: + case FLOWER_POT: + case BEE_NEST: + action = PermissibleAction.CONTAINER; + break; + default: + // Check for doors that might have diff material name in old version. + if (material.name().contains("DOOR") || material.name().contains("GATE")) { + action = PermissibleAction.DOOR; + } + if (material.name().contains("BUTTON")) { + action = PermissibleAction.BUTTON; + } + // Lazier than checking all the combinations + if (material.name().contains("SHULKER") || material.name().contains("ANVIL") || material.name().startsWith("POTTED")) { + action = PermissibleAction.CONTAINER; + } + if (material.name().endsWith("_PLATE")) { + action = PermissibleAction.PLATE; + } + if (material.name().contains("SIGN")) { + action = PermissibleAction.ITEM; + } + break; + } + }else{ + action = PermissibleAction.REPEATER; + } + + if (action == null) { + return true; + } + + // Ignored types + if (action == PermissibleAction.CONTAINER && FactionsPlugin.getInstance().conf().factions().protection().getContainerExceptions().contains(material)) { + return true; + } + + // F PERM check runs through before other checks. + if (!otherFaction.hasAccess(me, action)) { + if (action != PermissibleAction.PLATE) { + me.msg(TL.GENERIC_NOPERMISSION, action); + } + return false; + } + + // Dupe fix. + Faction myFaction = me.getFaction(); + Relation rel = myFaction.getRelationTo(otherFaction); + if (FactionsPlugin.getInstance().conf().exploits().doPreventDuping() && + (!rel.isMember() || !otherFaction.playerHasOwnershipRights(me, loc))) { + Material mainHand = player.getItemInHand().getType(); + + // Check if material is at risk for dupe in either hand. + if (isDupeMaterial(mainHand)) { + return false; + } + } + + // Also cancel if player doesn't have ownership rights for this claim + if (FactionsPlugin.getInstance().conf().factions().ownedArea().isEnabled() && FactionsPlugin.getInstance().conf().factions().ownedArea().isProtectMaterials() && !otherFaction.playerHasOwnershipRights(me, loc)) { + if (!justCheck) { + me.msg(TL.PLAYER_USE_OWNED, TextUtil.getMaterialName(material), otherFaction.getOwnerListString(loc)); + } + + return false; + } + + return true; + } + + private static boolean isDupeMaterial(Material material) { + if (material.name().toUpperCase().contains("SIGN")) { + return true; + } + + switch (material) { + case CHEST: + case TRAPPED_CHEST: + case DARK_OAK_DOOR: + case ACACIA_DOOR: + case BIRCH_DOOR: + case JUNGLE_DOOR: + case OAK_DOOR: + case SPRUCE_DOOR: + case IRON_DOOR: + return true; + default: + break; + } + + return false; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/EssentialsListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/EssentialsListener.java new file mode 100644 index 0000000..40cfb1d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/EssentialsListener.java @@ -0,0 +1,66 @@ +package com.massivecraft.factions.listeners; + +import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.User; +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.event.FPlayerLeaveEvent; +import net.ess3.api.InvalidWorldException; +import org.bukkit.Location; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +import java.util.List; +import java.util.UUID; +import java.util.logging.Level; + +public class EssentialsListener implements Listener { + + private final IEssentials ess; + + public EssentialsListener(IEssentials essentials) { + this.ess = essentials; + } + + @EventHandler + public void onLeave(FPlayerLeaveEvent event) throws Exception { + // Get the USER from their UUID. + Faction faction = event.getFaction(); + User user = ess.getUser(UUID.fromString(event.getfPlayer().getId())); + if (user == null) { + FactionsPlugin.getInstance().log(Level.WARNING, "Attempted to remove Essentials homes for " + event.getfPlayer().getName() + " " + + "but no Essentials data at all was found for this user. " + + "This may be a bug in Essentials, or may be that the player only played prior to adding Essentials to the server"); + return; + } + + List homes = user.getHomes(); + if (homes == null || homes.isEmpty()) { + return; + } + + // Not a great way to do this on essential's side. + for (String homeName : user.getHomes()) { + + Location loc; + try { + loc = user.getHome(homeName); + } catch (InvalidWorldException e) { + // This can throw an exception for some reason. + FactionsPlugin.getInstance().getLogger().warning("Tried to check on home \"" + homeName + "\" for user \"" + event.getfPlayer().getName() + "\" but Essentials said world \"" + e.getWorld() + "\" does not exist. Skipping it."); + continue; + } + FLocation floc = new FLocation(loc); + + Faction factionAt = Board.getInstance().getFactionAt(floc); + // We're only going to remove homes in territory that belongs to THEIR faction. + if (factionAt.equals(faction) && factionAt.isNormal()) { + user.delHome(homeName); + FactionsPlugin.getInstance().log(Level.INFO, "FactionLeaveEvent: Removing home %s, player %s, in territory of %s", + homeName, event.getfPlayer().getName(), faction.getTag()); + } + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java new file mode 100644 index 0000000..193d918 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java @@ -0,0 +1,379 @@ +package com.massivecraft.factions.listeners; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.UpgradeType; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.*; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +public class FactionsBlockListener implements Listener { + + public FactionsPlugin plugin; + + public FactionsBlockListener(FactionsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + if (!plugin.worldUtil().isEnabled(event.getBlock().getWorld())) { + return; + } + + if (!event.canBuild()) { + return; + } + + // special case for flint&steel, which should only be prevented by DenyUsage list + if (event.getBlockPlaced().getType() == Material.FIRE) { + return; + } + + Faction targetFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock().getLocation())); + if (targetFaction.isNormal() && !targetFaction.isPeaceful() && FactionsPlugin.getInstance().conf().factions().specialCase().getIgnoreBuildMaterials().contains(event.getBlock().getType())) { + return; + } + + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissibleAction.BUILD, false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockFromTo(BlockFromToEvent event) { + if (!plugin.worldUtil().isEnabled(event.getBlock().getWorld())) { + return; + } + + if(event.getToBlock().getLocation().getZ() == event.getBlock().getLocation().getZ() && + event.getToBlock().getLocation().getX() == event.getBlock().getLocation().getX())return; + + if (!FactionsPlugin.getInstance().conf().exploits().isLiquidFlow()) { + return; + } + if (event.getBlock().isLiquid()) { + if (event.getToBlock().isEmpty()) { + Faction from = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + Faction to = Board.getInstance().getFactionAt(new FLocation(event.getToBlock())); + if (from == to) { + // not concerned with inter-faction events + return; + } + // from faction != to faction + if (to.isNormal()) { + if (from.isNormal() && from.getRelationTo(to).isAlly()) { + return; + } + event.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + if (!plugin.worldUtil().isEnabled(event.getBlock().getWorld())) { + return; + } + + if (FactionsPlugin.getInstance().conf().factions().protection().getBreakExceptions().contains(event.getBlock().getType()) && + Board.getInstance().getFactionAt(new FLocation(event.getBlock().getLocation())).isNormal()) { + return; + } + + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissibleAction.DESTROY, false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockDamage(BlockDamageEvent event) { + if (!plugin.worldUtil().isEnabled(event.getBlock().getWorld())) { + return; + } + + if (FactionsPlugin.getInstance().conf().factions().protection().getBreakExceptions().contains(event.getBlock().getType()) && + Board.getInstance().getFactionAt(new FLocation(event.getBlock().getLocation())).isNormal()) { + return; + } + + if (event.getInstaBreak() && !playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), PermissibleAction.DESTROY, false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + if (!plugin.worldUtil().isEnabled(event.getBlock().getWorld())) { + return; + } + + if (!FactionsPlugin.getInstance().conf().factions().protection().isPistonProtectionThroughDenyBuild()) { + return; + } + + // if the pushed blocks list is empty, no worries + if (event.getBlocks().isEmpty()) { + return; + } + + Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + + if (!canPistonMoveBlock(pistonFaction, event.getBlocks(), event.getDirection())) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + if (!plugin.worldUtil().isEnabled(event.getBlock().getWorld())) { + return; + } + + // if not a sticky piston, retraction should be fine + if (!event.isSticky() || !FactionsPlugin.getInstance().conf().factions().protection().isPistonProtectionThroughDenyBuild()) { + return; + } + + List blocks; + if (FactionsPlugin.getMCVersion() < 800) { + blocks = Collections.singletonList(event.getBlock().getRelative(event.getDirection(), 2)); + } else { + blocks = event.getBlocks(); + } + + // if the retracted blocks list is empty, no worries + if (blocks.isEmpty()) { + return; + } + + Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + + if (!canPistonMoveBlock(pistonFaction, blocks, null)) { + event.setCancelled(true); + } + } + + private boolean canPistonMoveBlock(Faction pistonFaction, List blocks, BlockFace direction) { + String world = blocks.get(0).getWorld().getName(); + List factions = (direction == null ? blocks.stream() : blocks.stream().map(b -> b.getRelative(direction))) + .map(Block::getLocation) + .map(FLocation::new) + .distinct() + .map(Board.getInstance()::getFactionAt) + .distinct() + .collect(Collectors.toList()); + + boolean disableOverall = FactionsPlugin.getInstance().conf().factions().other().isDisablePistonsInTerritory(); + for (Faction otherFaction : factions) { + if (pistonFaction == otherFaction) { + continue; + } + // Check if the piston is moving in a faction's territory. This disables pistons entirely in faction territory. + if (disableOverall && otherFaction.isNormal()) { + return false; + } + if (otherFaction.isWilderness() && FactionsPlugin.getInstance().conf().factions().protection().isWildernessDenyBuild() && !FactionsPlugin.getInstance().conf().factions().protection().getWorldsNoWildernessProtection().contains(world)) { + return false; + } else if (otherFaction.isSafeZone() && FactionsPlugin.getInstance().conf().factions().protection().isSafeZoneDenyBuild()) { + return false; + } else if (otherFaction.isWarZone() && FactionsPlugin.getInstance().conf().factions().protection().isWarZoneDenyBuild()) { + return false; + } + Relation rel = pistonFaction.getRelationTo(otherFaction); + if (!otherFaction.hasAccess((!FactionsPlugin.getInstance().conf().onlineChecks().doOnlineChecks() || otherFaction.hasPlayersOnline()), rel, PermissibleAction.BUILD)) { + return false; + } + } + return true; + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onFrostWalker(EntityBlockFormEvent event) { + if (!plugin.worldUtil().isEnabled(event.getBlock().getWorld())) { + return; + } + + event.getEntity(); + if (event.getEntity().getType() != EntityType.PLAYER) { + return; + } + + Player player = (Player) event.getEntity(); + Location location = event.getBlock().getLocation(); + + // only notify every 10 seconds + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + boolean justCheck = fPlayer.getLastFrostwalkerMessage() + 10000 > System.currentTimeMillis(); + if (!justCheck) { + fPlayer.setLastFrostwalkerMessage(); + } + + // Check if they have build permissions here. If not, block this from happening. + if (!playerCanBuildDestroyBlock(player, location, PermissibleAction.FROSTWALK, justCheck)) { + event.setCancelled(true); + } + } + + private static Material SUGAR_CANE_BLOCK; + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onGrow(BlockGrowEvent e){ + if (SUGAR_CANE_BLOCK == null){ + SUGAR_CANE_BLOCK = Material.getMaterial("SUGAR_CANE_BLOCK"); + } + + if (!FactionsPlugin.getInstance().conf().upgrades().warpAmount().isEnabled())return; + + int i; + + for (i = 1; e.getBlock().getRelative(BlockFace.DOWN, i).getType() == SUGAR_CANE_BLOCK; ++i); + + if (i >= ((CraftWorld) e.getBlock().getWorld()).getHandle().paperSpigotConfig.reedMaxHeight) return; + + FLocation fLocation = new FLocation(e.getBlock()); + + Faction factionAt = Board.getInstance().getFactionAt(fLocation); + + if (factionAt.isWilderness()) return; + + int upgrade = factionAt.getUpgrade(UpgradeType.CROP_BOOST); + + //if(upgrade <= 0 && FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().getDefaultBoost() == 0.0D) return; + + double boost = FactionsPlugin.getInstance().conf().upgrades().warpAmount().getNumber(upgrade); + + float randomFloat = ThreadLocalRandom.current().nextFloat(); + + if (boost >= randomFloat){ + Block relative = e.getBlock().getRelative(BlockFace.UP); + + if(relative.getType() == Material.AIR){ + relative.setType(SUGAR_CANE_BLOCK, false); + } + } + } + + public static boolean playerCanBuildDestroyBlock(Player player, Location location, PermissibleAction permissibleAction, boolean justCheck) { + String name = player.getName(); + MainConfig conf = FactionsPlugin.getInstance().conf(); + if (conf.factions().protection().getPlayersWhoBypassAllProtection().contains(name)) { + return true; + } + + FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); + if (me.isAdminBypassing()) { + return true; + } + + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getInstance().getFactionAt(loc); + + if (otherFaction.isWilderness()) { + if (conf.worldGuard().isBuildPriority() && FactionsPlugin.getInstance().getWorldguard() != null && FactionsPlugin.getInstance().getWorldguard().playerCanBuild(player, location)) { + return true; + } + + if (!conf.factions().protection().isWildernessDenyBuild() || conf.factions().protection().getWorldsNoWildernessProtection().contains(location.getWorld().getName())) { + return true; // This is not faction territory. Use whatever you like here. + } + + if (!justCheck) { + me.msg(TL.PERM_DENIED_WILDERNESS, permissibleAction.getShortDescription()); + } + + return false; + } else if (otherFaction.isSafeZone()) { + if (conf.worldGuard().isBuildPriority() && FactionsPlugin.getInstance().getWorldguard() != null && FactionsPlugin.getInstance().getWorldguard().playerCanBuild(player, location)) { + return true; + } + + if (!conf.factions().protection().isSafeZoneDenyBuild() || Permission.MANAGE_SAFE_ZONE.has(player)) { + return true; + } + + if (!justCheck) { + me.msg(TL.PERM_DENIED_SAFEZONE, permissibleAction.getShortDescription()); + } + + return false; + } else if (otherFaction.isWarZone()) { + if (conf.worldGuard().isBuildPriority() && FactionsPlugin.getInstance().getWorldguard() != null && FactionsPlugin.getInstance().getWorldguard().playerCanBuild(player, location)) { + return true; + } + + if (!conf.factions().protection().isWarZoneDenyBuild() || Permission.MANAGE_WAR_ZONE.has(player)) { + return true; + } + + if (!justCheck) { + me.msg(TL.PERM_DENIED_WARZONE, permissibleAction.getShortDescription()); + } + + return false; + } + if (FactionsPlugin.getInstance().getLandRaidControl().isRaidable(otherFaction)) { + return true; + } + + Faction myFaction = me.getFaction(); + boolean pain = !justCheck && otherFaction.hasAccess(me, PermissibleAction.PAINBUILD); + + // If the faction hasn't: defined access or denied, fallback to config values + if (!otherFaction.hasAccess(me, permissibleAction)) { + if (pain && permissibleAction != PermissibleAction.FROSTWALK) { + player.damage(conf.factions().other().getActionDeniedPainAmount()); + me.msg(TL.PERM_DENIED_PAINTERRITORY, permissibleAction.getShortDescription(), otherFaction.getTag(myFaction)); + return true; + } else if (!justCheck) { + me.msg(TL.PERM_DENIED_TERRITORY, permissibleAction.getShortDescription(), otherFaction.getTag(myFaction)); + } + return false; + } + + // Also cancel and/or cause pain if player doesn't have ownership rights for this claim + if (conf.factions().ownedArea().isEnabled() && (conf.factions().ownedArea().isDenyBuild() || conf.factions().ownedArea().isPainBuild()) && !otherFaction.playerHasOwnershipRights(me, loc)) { + if (pain && conf.factions().ownedArea().isPainBuild()) { + player.damage(conf.factions().other().getActionDeniedPainAmount()); + + if (!conf.factions().ownedArea().isDenyBuild()) { + me.msg(TL.PERM_DENIED_PAINOWNED, permissibleAction.getShortDescription(), otherFaction.getOwnerListString(loc)); + } + } + if (conf.factions().ownedArea().isDenyBuild()) { + if (!justCheck) { + me.msg(TL.PERM_DENIED_OWNED, permissibleAction.getShortDescription(), otherFaction.getOwnerListString(loc)); + } + + return false; + } + } + + return true; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java new file mode 100644 index 0000000..b6cf1f0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java @@ -0,0 +1,215 @@ +package com.massivecraft.factions.listeners; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.struct.ChatMode; +import com.massivecraft.factions.util.CC; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; +import java.util.UnknownFormatConversionException; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class FactionsChatListener implements Listener { + + public FactionsPlugin plugin; + private final Pattern ipPattern = Pattern.compile("((? badWords = Arrays.asList("nigger", "jew", "kys", "demonicpvp", "jurassicpvp", "cursedpvp", "exoduspvp", "nig", "fag", "faggot", "ddos", "doss", "niggar", "hitler"); + public FactionsChatListener(FactionsPlugin plugin) { + this.plugin = plugin; + } + + // this is for handling slashless command usage and faction/alliance chat, set at lowest priority so Factions gets to them first + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerEarlyChat(AsyncPlayerChatEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + Player player = event.getPlayer(); + Matcher ipMatcher = ipPattern.matcher(event.getMessage()); + + if (ipMatcher.find() && !player.isOp()) { + player.sendMessage(CC.translate("&c&l(!)&c You are not allowed to send ip's in chat!")); + //CrankedCore.getInstance().getStaffChatManager().sendStaffMessage(CC.translate("&c" + player.getName() + " &ctried sending an ip in chat &7(" + event.getMessage() + "&7)")); + return; + } + + Matcher webMatcher = webpattern.matcher(event.getMessage()); + + if (webMatcher.find() && !player.isOp()) { + player.sendMessage(CC.translate("&c&l(!)&c You are not allowed to send links in chat!")); + //CrankedCore.getInstance().getStaffChatManager().sendStaffMessage(CC.translate("&c" + player.getName() + " &ctried sending a link in chat &7(" + event.getMessage() + "&7)")); + return; + } + + + Player talkingPlayer = event.getPlayer(); + String msg = event.getMessage(); + FPlayer me = FPlayers.getInstance().getByPlayer(talkingPlayer); + ChatMode chat = me.getChatMode(); + MainConfig.Factions.Chat chatConf = FactionsPlugin.getInstance().conf().factions().chat(); + //Is it a MOD chat + if (chat == ChatMode.MOD) { + Faction myFaction = me.getFaction(); + + String message = String.format(chatConf.getModChatFormat(), ChatColor.stripColor(me.getNameAndTag()), msg); + + //Send to all mods + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (myFaction == fplayer.getFaction() && fplayer.getRole().isAtLeast(Role.MODERATOR)) { + fplayer.sendMessage(message); + } else if (fplayer.isSpyingChat() && me != fplayer) { + fplayer.sendMessage("[MCspy]: " + message); + } + } + + FactionsPlugin.getInstance().log(Level.INFO, ChatColor.stripColor("ModChat " + myFaction.getTag() + ": " + message)); + + event.setCancelled(true); + } else if (chat == ChatMode.FACTION) { + Faction myFaction = me.getFaction(); + + String message = String.format(chatConf.getFactionChatFormat(), me.describeTo(myFaction), msg); + myFaction.sendMessage(message); + + FactionsPlugin.getInstance().log(Level.INFO, ChatColor.stripColor("FactionChat " + myFaction.getTag() + ": " + message)); + + //Send to any players who are spying chat + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fplayer.isSpyingChat() && fplayer.getFaction() != myFaction && me != fplayer) { + fplayer.sendMessage("[FCspy] " + myFaction.getTag() + ": " + message); + } + } + + event.setCancelled(true); + } else if (chat == ChatMode.ALLIANCE) { + Faction myFaction = me.getFaction(); + + String message = String.format(chatConf.getAllianceChatFormat(), ChatColor.stripColor(me.getNameAndTag()), msg); + + //Send message to our own faction + myFaction.sendMessage(message); + + //Send to all our allies + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (myFaction.getRelationTo(fplayer) == Relation.ALLY && !fplayer.isIgnoreAllianceChat()) { + fplayer.sendMessage(message); + } else if (fplayer.isSpyingChat() && me != fplayer) { + fplayer.sendMessage("[ACspy]: " + message); + } + } + + FactionsPlugin.getInstance().log(Level.INFO, ChatColor.stripColor("AllianceChat: " + message)); + + event.setCancelled(true); + } else if (chat == ChatMode.TRUCE) { + Faction myFaction = me.getFaction(); + + String message = String.format(chatConf.getTruceChatFormat(), ChatColor.stripColor(me.getNameAndTag()), msg); + + //Send message to our own faction + myFaction.sendMessage(message); + + //Send to all our truces + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (myFaction.getRelationTo(fplayer) == Relation.TRUCE) { + fplayer.sendMessage(message); + } else if (fplayer.isSpyingChat() && fplayer != me) { + fplayer.sendMessage("[TCspy]: " + message); + } + } + + FactionsPlugin.getInstance().log(Level.INFO, ChatColor.stripColor("TruceChat: " + message)); + event.setCancelled(true); + } + } + + // this is for handling insertion of the player's faction tag, set at highest priority to give other plugins a chance to modify chat first + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerChat(AsyncPlayerChatEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + // Are we to insert the Faction tag into the format? + // If we are not to insert it - we are done. + if (FactionsPlugin.getInstance().isAnotherPluginHandlingChat()) { + return; + } + + + Player talkingPlayer = event.getPlayer(); + String msg = event.getMessage(); + String eventFormat = event.getFormat(); + FPlayer me = FPlayers.getInstance().getByPlayer(talkingPlayer); + MainConfig.Factions.Chat chatConf = FactionsPlugin.getInstance().conf().factions().chat(); + int InsertIndex = chatConf.getTagInsertIndex(); + + boolean padBefore = chatConf.isTagPadBefore(); + boolean padAfter = chatConf.isTagPadAfter(); + + if (!chatConf.getTagReplaceString().isEmpty() && eventFormat.contains(chatConf.getTagReplaceString())) { + // we're using the "replace" method of inserting the faction tags + if (eventFormat.contains("[FACTION_TITLE]")) { + eventFormat = eventFormat.replace("[FACTION_TITLE]", me.getTitle()); + } + InsertIndex = eventFormat.indexOf(chatConf.getTagReplaceString()); + eventFormat = eventFormat.replace(chatConf.getTagReplaceString(), ""); + padBefore = false; + padAfter = false; + } else if (!chatConf.getTagInsertAfterString().isEmpty() && eventFormat.contains(chatConf.getTagInsertAfterString())) { + // we're using the "insert after string" method + InsertIndex = eventFormat.indexOf(chatConf.getTagInsertAfterString()) + chatConf.getTagInsertAfterString().length(); + } else if (!chatConf.getTagInsertBeforeString().isEmpty() && eventFormat.contains(chatConf.getTagInsertBeforeString())) { + // we're using the "insert before string" method + InsertIndex = eventFormat.indexOf(chatConf.getTagInsertBeforeString()); + } else if (!chatConf.isAlwaysShowChatTag()) { + return; + } + + String formatStart = eventFormat.substring(0, InsertIndex) + ((padBefore && !me.getChatTag().isEmpty()) ? " " : ""); + String formatEnd = ((padAfter && !me.getChatTag().isEmpty()) ? " " : "") + eventFormat.substring(InsertIndex); + + String nonColoredMsgFormat = formatStart + me.getChatTag().trim() + formatEnd; + + // Relation Colored? + if (chatConf.isTagRelationColored()) { + for (Player listeningPlayer : event.getRecipients()) { + FPlayer you = FPlayers.getInstance().getByPlayer(listeningPlayer); + String yourFormat = formatStart + me.getChatTag(you).trim() + formatEnd; + + try { + listeningPlayer.sendMessage(String.format(yourFormat, talkingPlayer.getDisplayName(), msg)); + } catch (UnknownFormatConversionException ex) { + + FactionsPlugin.getInstance().log(Level.SEVERE, "Critical error in chat message formatting!"); + FactionsPlugin.getInstance().log(Level.SEVERE, "NOTE: This can be fixed right now by setting chat tagInsertIndex to 0."); + return; + } + } + + // Messages are sent to players individually + // This still leaves a chance for other plugins to pick it up + event.getRecipients().clear(); + } + // Message with no relation color. + event.setFormat(nonColoredMsgFormat); + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java new file mode 100644 index 0000000..f1f1fd0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java @@ -0,0 +1,576 @@ +package com.massivecraft.factions.listeners; + +import com.massivecraft.factions.*; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.util.TL; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.*; +import org.bukkit.event.hanging.HangingBreakByEntityEvent; +import org.bukkit.event.hanging.HangingBreakEvent; +import org.bukkit.event.hanging.HangingBreakEvent.RemoveCause; +import org.bukkit.event.hanging.HangingPlaceEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.projectiles.ProjectileSource; + +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.UUID; + + +public class FactionsEntityListener extends AbstractListener { + + public FactionsPlugin plugin; + + public FactionsEntityListener(FactionsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onEntityDeath(EntityDeathEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + Entity entity = event.getEntity(); + if (entity instanceof Player) { + FactionsPlugin.getInstance().getLandRaidControl().onDeath((Player) entity); + } + } + + /** + * Who can I hurt? I can never hurt members or allies. I can always hurt enemies. I can hurt neutrals as long as + * they are outside their own territory. + */ + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityDamage(EntityDamageEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + if (event instanceof EntityDamageByEntityEvent) { + EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent) event; + if (!this.canDamagerHurtDamagee(sub, true)) { + event.setCancelled(true); + } + } else if (FactionsPlugin.getInstance().conf().factions().protection().isSafeZonePreventAllDamageToPlayers() && isPlayerInSafeZone(event.getEntity())) { + // Players can not take any damage in a Safe Zone + event.setCancelled(true); + } else if (event.getCause() == EntityDamageEvent.DamageCause.FALL && event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (fPlayer != null && !fPlayer.shouldTakeFallDamage()) { + event.setCancelled(true); // Falling after /f fly + } + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityDamageMonitor(EntityDamageEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + Entity damagee = event.getEntity(); + boolean playerHurt = damagee instanceof Player; + + if (event instanceof EntityDamageByEntityEvent) { + Entity damager = ((EntityDamageByEntityEvent) event).getDamager(); + + if (damager instanceof Projectile) { + Projectile projectile = (Projectile) damager; + + if (projectile.getShooter() instanceof Entity) { + damager = (Entity) projectile.getShooter(); + } + } + + if (playerHurt) { + cancelFStuckTeleport((Player) damagee); + if ((damager instanceof Player) || plugin.conf().commands().fly().isDisableOnHurtByMobs()) { + //cancelFFly((Player) damagee); + } + } + if (damager instanceof Player) { + cancelFStuckTeleport((Player) damager); + if ((playerHurt && plugin.conf().commands().fly().isDisableOnHurtingPlayers()) || + (!playerHurt && plugin.conf().commands().fly().isDisableOnHurtingMobs())) { + //cancelFFly((Player) damager); + } + } + } + + // entity took generic damage? + if (playerHurt) { + Player player = (Player) damagee; + FPlayer me = FPlayers.getInstance().getByPlayer(player); + cancelFStuckTeleport(player); + if (plugin.conf().commands().fly().isDisableOnGenericDamage()) { + //cancelFFly(player); + } + if (me.isWarmingUp()) { + me.clearWarmup(); + me.msg(TL.WARMUPS_CANCELLED); + } + } + } + + private void cancelFFly(Player player) { + if (player == null) { + return; + } + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + /*if (fPlayer.isFlying()) { + fPlayer.setFlying(false, true); + if (fPlayer.isAutoFlying()) { + fPlayer.setAutoFlying(false); + } + }*/ + } + + public void cancelFStuckTeleport(Player player) { + if (player == null) { + return; + } + UUID uuid = player.getUniqueId(); + if (FactionsPlugin.getInstance().getStuckMap().containsKey(uuid)) { + FPlayers.getInstance().getByPlayer(player).msg(TL.COMMAND_STUCK_CANCELLED); + FactionsPlugin.getInstance().getStuckMap().remove(uuid); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityExplode(EntityExplodeEvent event) { + this.handleExplosion(event.getLocation(), event.getEntity(), event, event.blockList()); + } + + // mainly for flaming arrows; don't want allies or people in safe zones to be ignited even after damage event is cancelled + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE, 0d); + if (!this.canDamagerHurtDamagee(sub, false)) { + event.setCancelled(true); + } + } + + private static final Set badPotionEffects = new LinkedHashSet<>(Arrays.asList(PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER, PotionEffectType.POISON, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS, PotionEffectType.WITHER)); + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPotionSplashEvent(PotionSplashEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + // see if the potion has a harmful effect + boolean badjuju = false; + for (PotionEffect effect : event.getPotion().getEffects()) { + if (badPotionEffects.contains(effect.getType())) { + badjuju = true; + break; + } + } + if (!badjuju) { + return; + } + + ProjectileSource thrower = event.getPotion().getShooter(); + if (!(thrower instanceof Entity)) { + return; + } + + if (thrower instanceof Player) { + Player player = (Player) thrower; + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (badjuju && fPlayer.getFaction().isPeaceful()) { + event.setCancelled(true); + return; + } + } + + // scan through affected entities to make sure they're all valid targets + for (LivingEntity target : event.getAffectedEntities()) { + EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent((Entity) thrower, target, EntityDamageEvent.DamageCause.CUSTOM, 0); + if (!this.canDamagerHurtDamagee(sub, true)) { + event.setIntensity(target, 0.0); // affected entity list doesn't accept modification (so no iter.remove()), but this works + } + } + } + + public boolean isPlayerInSafeZone(Entity damagee) { + if (!(damagee instanceof Player)) { + return false; + } + return Board.getInstance().getFactionAt(new FLocation(damagee.getLocation())).isSafeZone(); + } + + public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { + return canDamagerHurtDamagee(sub, true); + } + + public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) { + return canDamage(sub.getDamager(), sub.getEntity(), notify); + } + + public static boolean canDamage(Entity damager, Entity damagee, boolean notify) { + // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source + if (damager instanceof Projectile) { + Projectile projectile = (Projectile) damager; + + if (!(projectile.getShooter() instanceof Entity)) { + return true; + } + + damager = (Entity) projectile.getShooter(); + } + + if (damager instanceof Player) { + Player player = (Player) damager; + Material material = null; + switch (damagee.getType()) { + case ITEM_FRAME: + material = Material.ITEM_FRAME; + break; + case ARMOR_STAND: + material = Material.ARMOR_STAND; + break; + } + if (material != null && !canUseBlock(player, material, damagee.getLocation(), false)) { + return false; + } + } + + if (!(damagee instanceof Player)) { + return true; + } + + FPlayer defender = FPlayers.getInstance().getByPlayer((Player) damagee); + + if (defender == null || defender.getPlayer() == null) { + return true; + } + + Location defenderLoc = defender.getPlayer().getLocation(); + Faction defLocFaction = Board.getInstance().getFactionAt(new FLocation(defenderLoc)); + + if (damager == damagee) { // ender pearl usage and other self-inflicted damage + return true; + } + + // Players can not take attack damage in a SafeZone, or possibly peaceful territory + if (defLocFaction.noPvPInTerritory()) { + if (damager instanceof Player) { + if (notify) { + FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); + attacker.msg(TL.PLAYER_CANTHURT, (defLocFaction.isSafeZone() ? TL.REGION_SAFEZONE.toString() : TL.REGION_PEACEFUL.toString())); + } + return false; + } + return !defLocFaction.noMonstersInTerritory(); + } + + if (!(damager instanceof Player)) { + return true; + } + + FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); + + if (attacker == null || attacker.getPlayer() == null) { + return true; + } + + MainConfig.Factions facConf = FactionsPlugin.getInstance().conf().factions(); + if (facConf.protection().getPlayersWhoBypassAllProtection().contains(attacker.getName())) { + return true; + } + + if (attacker.hasLoginPvpDisabled()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_LOGIN, facConf.pvp().getNoPVPDamageToOthersForXSecondsAfterLogin()); + } + return false; + } + + Faction locFaction = Board.getInstance().getFactionAt(new FLocation(attacker)); + + // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? + if (locFaction.noPvPInTerritory()) { + if (notify) { + attacker.msg(TL.PLAYER_CANTHURT, (locFaction.isSafeZone() ? TL.REGION_SAFEZONE.toString() : TL.REGION_PEACEFUL.toString())); + } + return false; + } + + if (locFaction.isWarZone() && facConf.protection().isWarZoneFriendlyFire()) { + return true; + } + + if (facConf.pvp().getWorldsIgnorePvP().contains(defenderLoc.getWorld().getName())) { + return true; + } + + Faction defendFaction = defender.getFaction(); + Faction attackFaction = attacker.getFaction(); + + if (attackFaction.isWilderness() && facConf.pvp().isDisablePVPForFactionlessPlayers()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_REQUIREFACTION); + } + return false; + } else if (defendFaction.isWilderness()) { + if (defLocFaction == attackFaction && facConf.pvp().isEnablePVPAgainstFactionlessInAttackersLand()) { + // Allow PVP vs. Factionless in attacker's faction territory + return true; + } else if (facConf.pvp().isDisablePVPForFactionlessPlayers()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_FACTIONLESS); + } + return false; + } + } + + if (!defLocFaction.isWarZone() || facConf.pvp().isDisablePeacefulPVPInWarzone()) { + if (defendFaction.isPeaceful()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_PEACEFUL); + } + return false; + } else if (attackFaction.isPeaceful()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_PEACEFUL); + } + return false; + } + } + + Relation relation = defendFaction.getRelationTo(attackFaction); + + // You can not hurt neutral factions + if (facConf.pvp().isDisablePVPBetweenNeutralFactions() && relation.isNeutral()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_NEUTRAL); + } + return false; + } + + // Players without faction may be hurt anywhere + if (!defender.hasFaction()) { + return true; + } + + // You can never hurt faction members or allies + if (relation.isMember() || relation.isAlly() || relation.isTruce()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_CANTHURT, defender.describeTo(attacker)); + } + return false; + } + + boolean ownTerritory = defender.isInOwnTerritory(); + + // You can not hurt neutrals in their own territory. + if (ownTerritory && relation.isNeutral()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_NEUTRALFAIL, defender.describeTo(attacker)); + defender.msg(TL.PLAYER_PVP_TRIED, attacker.describeTo(defender, true)); + } + return false; + } + + // Damage will be dealt. However check if the damage should be reduced. + /* + if (damage > 0.0 && ownTerritory && Conf.territoryShieldFactor > 0) { + double newDamage = Math.ceil(damage * (1D - Conf.territoryShieldFactor)); + sub.setDamage(newDamage); + + // Send message + if (notify) { + String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly?? + defender.msg("Enemy damage reduced by %s.", perc); + } + } */ + + return true; + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onCreatureSpawn(CreatureSpawnEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + if (event.getLocation() == null) { // Just in case + return; + } + + Faction faction = Board.getInstance().getFactionAt(new FLocation(event.getLocation())); + CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); + EntityType type = event.getEntityType(); + MainConfig.Factions.Spawning spawning = FactionsPlugin.getInstance().conf().factions().spawning(); + + if (faction.isNormal()) { + if (faction.isPeaceful() && FactionsPlugin.getInstance().conf().factions().specialCase().isPeacefulTerritoryDisableMonsters()) { + if (event.getEntity() instanceof Monster) { + event.setCancelled(true); + } + } + if (spawning.getPreventInTerritory().contains(reason) && !spawning.getPreventInTerritoryExceptions().contains(type)) { + event.setCancelled(true); + } + } else if (faction.isSafeZone()) { + if (spawning.getPreventInSafezone().contains(reason) && !spawning.getPreventInSafezoneExceptions().contains(type)) { + event.setCancelled(true); + } + } else if (faction.isWarZone()) { + if (spawning.getPreventInWarzone().contains(reason) && !spawning.getPreventInWarzoneExceptions().contains(type)) { + event.setCancelled(true); + } + } else if (faction.isWilderness()) { + if (spawning.getPreventInWilderness().contains(reason) && !spawning.getPreventInWildernessExceptions().contains(type)) { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityTarget(EntityTargetEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + // if there is a target + Entity target = event.getTarget(); + if (target == null) { + return; + } + + if (event.getEntity() instanceof Monster && Board.getInstance().getFactionAt(new FLocation(target.getLocation())).noMonstersInTerritory()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPaintingBreak(HangingBreakEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + if (event.getCause() == RemoveCause.EXPLOSION) { + Location loc = event.getEntity().getLocation(); + Faction faction = Board.getInstance().getFactionAt(new FLocation(loc)); + if (faction.noExplosionsInTerritory()) { + // faction is peaceful and has explosions set to disabled + event.setCancelled(true); + return; + } + + boolean online = faction.hasPlayersOnline(); + MainConfig.Factions.Protection protection = FactionsPlugin.getInstance().conf().factions().protection(); + + if ((faction.isWilderness() && !protection.getWorldsNoWildernessProtection().contains(loc.getWorld().getName()) && (protection.isWildernessBlockCreepers() || protection.isWildernessBlockFireballs() || protection.isWildernessBlockTNT())) || + (faction.isNormal() && (online ? (protection.isTerritoryBlockCreepers() || protection.isTerritoryBlockFireballs() || protection.isTerritoryBlockTNT()) : (protection.isTerritoryBlockCreepersWhenOffline() || protection.isTerritoryBlockFireballsWhenOffline() || protection.isTerritoryBlockTNTWhenOffline()))) || + (faction.isWarZone() && (protection.isWarZoneBlockCreepers() || protection.isWarZoneBlockFireballs() || protection.isWarZoneBlockTNT())) || + faction.isSafeZone()) { + // explosion which needs prevention + event.setCancelled(true); + } + } + + if (!(event instanceof HangingBreakByEntityEvent)) { + return; + } + + Entity breaker = ((HangingBreakByEntityEvent) event).getRemover(); + if (!(breaker instanceof Player)) { + return; + } + + if (!FactionsBlockListener.playerCanBuildDestroyBlock((Player) breaker, event.getEntity().getLocation(), PermissibleAction.DESTROY, false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPaintingPlace(HangingPlaceEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getRelative(event.getBlockFace()).getLocation(), PermissibleAction.BUILD, false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityChangeBlock(EntityChangeBlockEvent event) { + if (!plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + Entity entity = event.getEntity(); + + // for now, only interested in Enderman and Wither boss tomfoolery + if (!(entity instanceof Enderman) && !(entity instanceof Wither)) { + return; + } + + Location loc = event.getBlock().getLocation(); + + if (entity instanceof Enderman) { + if (stopEndermanBlockManipulation(loc)) { + event.setCancelled(true); + } + } else if (entity instanceof Wither) { + Faction faction = Board.getInstance().getFactionAt(new FLocation(loc)); + MainConfig.Factions.Protection protection = FactionsPlugin.getInstance().conf().factions().protection(); + // it's a bit crude just using fireball protection, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever + if ((faction.isWilderness() && protection.isWildernessBlockFireballs() && !protection.getWorldsNoWildernessProtection().contains(loc.getWorld().getName())) || + (faction.isNormal() && (faction.hasPlayersOnline() ? protection.isTerritoryBlockFireballs() : protection.isTerritoryBlockFireballsWhenOffline())) || + (faction.isWarZone() && protection.isWarZoneBlockFireballs()) || + faction.isSafeZone()) { + event.setCancelled(true); + } + } + } + + private boolean stopEndermanBlockManipulation(Location loc) { + if (loc == null) { + return false; + } + // quick check to see if all Enderman deny options are enabled; if so, no need to check location + MainConfig.Factions.Protection protection = FactionsPlugin.getInstance().conf().factions().protection(); + if (protection.isWildernessDenyEndermanBlocks() && + protection.isTerritoryDenyEndermanBlocks() && + protection.isTerritoryDenyEndermanBlocksWhenOffline() && + protection.isSafeZoneDenyEndermanBlocks() && + protection.isWarZoneDenyEndermanBlocks()) { + return true; + } + + FLocation fLoc = new FLocation(loc); + Faction claimFaction = Board.getInstance().getFactionAt(fLoc); + + if (claimFaction.isWilderness()) { + return protection.isWildernessDenyEndermanBlocks(); + } else if (claimFaction.isNormal()) { + return claimFaction.hasPlayersOnline() ? protection.isTerritoryDenyEndermanBlocks() : protection.isTerritoryDenyEndermanBlocksWhenOffline(); + } else if (claimFaction.isSafeZone()) { + return protection.isSafeZoneDenyEndermanBlocks(); + } else if (claimFaction.isWarZone()) { + return protection.isWarZoneDenyEndermanBlocks(); + } + + return false; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java new file mode 100644 index 0000000..f922f7a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java @@ -0,0 +1,75 @@ +package com.massivecraft.factions.listeners; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + + +public class FactionsExploitListener implements Listener { + public FactionsPlugin plugin; + + public FactionsExploitListener(FactionsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void obsidianGenerator(BlockFromToEvent event) { + if (!plugin.worldUtil().isEnabled(event.getBlock().getWorld())) { + return; + } + + if (!FactionsPlugin.getInstance().conf().exploits().isObsidianGenerators()) { + return; + } + + // thanks to ObGenBlocker and WorldGuard for this method + Block block = event.getToBlock(); + Material source = event.getBlock().getType(); + Material target = block.getType(); + if ((target == Material.REDSTONE_WIRE || target == Material.TRIPWIRE) && (source == Material.AIR || source == Material.LAVA)) { + block.setType(Material.AIR); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void enderPearlTeleport(PlayerTeleportEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer())) { + return; + } + + if (!FactionsPlugin.getInstance().conf().exploits().isEnderPearlClipping()) { + return; + } + if (event.getCause() != PlayerTeleportEvent.TeleportCause.ENDER_PEARL) { + return; + } + + // this exploit works when the target location is within 0.31 blocks or so of a door or glass block or similar... + Location target = event.getTo(); + Location from = event.getFrom(); + + // blocks who occupy less than 1 block width or length wise need to be handled differently + Material mat = event.getTo().getBlock().getType(); + if (((mat == MaterialDb.get("GLASS_PANE") || mat == MaterialDb.get("IRON_BARS")) && clippingThrough(target, from, 0.65)) || ((mat.name().toLowerCase().contains("fence")) && clippingThrough(target, from, 0.45))) { + event.setTo(from); + return; + } + + // simple fix otherwise: ender pearl target locations are standardized to be in the center (X/Z) of the target block, not at the edges + target.setX(target.getBlockX() + 0.5); + target.setZ(target.getBlockZ() + 0.5); + event.setTo(target); + + } + + public static boolean clippingThrough(Location target, Location from, double thickness) { + return ((from.getX() > target.getX() && (from.getX() - target.getX() < thickness)) || (target.getX() > from.getX() && (target.getX() - from.getX() < thickness)) || (from.getZ() > target.getZ() && (from.getZ() - target.getZ() < thickness)) || (target.getZ() > from.getZ() && (target.getZ() - from.getZ() < thickness))); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java new file mode 100644 index 0000000..f8253ed --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java @@ -0,0 +1,942 @@ +package com.massivecraft.factions.listeners; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.cmd.CommandContext; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.data.MemoryFPlayer; +import com.massivecraft.factions.event.FPlayerJoinEvent; +import com.massivecraft.factions.event.FPlayerLeaveEvent; +import com.massivecraft.factions.gui.GUI; +import com.massivecraft.factions.integration.Essentials; +import com.massivecraft.factions.perms.PermissibleAction; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.scoreboards.FScoreboard; +import com.massivecraft.factions.scoreboards.FTeamWrapper; +import com.massivecraft.factions.scoreboards.sidebar.FDefaultSidebar; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.util.*; +import com.massivecraft.factions.util.material.MaterialDb; +import net.coreprotect.CoreProtect; +import net.coreprotect.CoreProtectAPI; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerBucketFillEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.NumberConversions; + +import java.util.*; +import java.util.logging.Level; + + +public class FactionsPlayerListener extends AbstractListener { + + private final FactionsPlugin plugin; + + public FactionsPlayerListener(FactionsPlugin plugin) { + this.plugin = plugin; + for (Player player : plugin.getServer().getOnlinePlayers()) { + initPlayer(player); + } + } + + private void toggleFlight(FPlayer fPlayer, final boolean toggle) { + // If false do nothing besides set + if (!toggle) { + //fPlayer.setFlying(false); + return; + } + // Do checks if true + if (!flyTest(fPlayer)) { + return; + } + //fPlayer.setFlying(true); + } + + private boolean flyTest(FPlayer fPlayer) { + if(fPlayer.isAdminBypassing())return true; + + fPlayer.canFlyAtLocation(); + return false; + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerJoin(PlayerJoinEvent event) { + FPlayer fPlayer = initPlayer(event.getPlayer()); + this.plugin.updatesOnJoin(event.getPlayer()); + + if (Permission.FLY_AUTO.has(event.getPlayer(), false)) { + //fPlayer.setAutoFlying(true); + //toggleFlight(fPlayer, true); + } + } + + private FPlayer initPlayer(Player player) { + // Make sure that all online players do have a fplayer. + final FPlayer me = FPlayers.getInstance().getByPlayer(player); + ((MemoryFPlayer) me).setName(player.getName()); + + this.plugin.getLandRaidControl().onJoin(me); + // Update the lastLoginTime for this fplayer + me.setLastLoginTime(System.currentTimeMillis()); + + // Store player's current FLocation and notify them where they are + me.setLastStoodAt(new FLocation(player.getLocation())); + + me.login(); // set kills / deaths + me.setOfflinePlayer(player); + + if (me.isSpyingChat() && !player.hasPermission(Permission.CHATSPY.node)) { + me.setSpyingChat(false); + FactionsPlugin.getInstance().log(Level.INFO, "Found %s spying chat without permission on login. Disabled their chat spying.", player.getName()); + } + + if (me.isAdminBypassing() && !player.hasPermission(Permission.BYPASS.node)) { + me.setIsAdminBypassing(false); + FactionsPlugin.getInstance().log(Level.INFO, "Found %s on admin Bypass without permission on login. Disabled it for them.", player.getName()); + } + + if (plugin.worldUtil().isEnabled(player.getWorld())) { + this.initFactionWorld(me); + } + return me; + } + + private void initFactionWorld(FPlayer me) { + // Check for Faction announcements. Let's delay this so they actually see it. + new BukkitRunnable() { + @Override + public void run() { + if (me.isOnline()) { + me.getFaction().sendUnreadAnnouncements(me); + } + } + }.runTaskLater(FactionsPlugin.getInstance(), 33L); // Don't ask me why. + + if (FactionsPlugin.getInstance().conf().scoreboard().constant().isEnabled()) { + FScoreboard.init(me); + FScoreboard.get(me).setDefaultSidebar(new FDefaultSidebar()); + FScoreboard.get(me).setSidebarVisibility(me.showScoreboard()); + } + + Faction myFaction = me.getFaction(); + if (!myFaction.isWilderness()) { + for (FPlayer other : myFaction.getFPlayersWhereOnline(true)) { + if (other != me && other.isMonitoringJoins()) { + other.msg(TL.FACTION_LOGIN, me.getName()); + } + } + } + + // If they have the permission, don't let them autoleave. Bad inverted setter :\ + me.setAutoLeave(!me.getPlayer().hasPermission(Permission.AUTO_LEAVE_BYPASS.node)); + me.setTakeFallDamage(true); + if (plugin.conf().commands().fly().isEnable() && me.isFlying()) { // TODO allow flight to continue + //me.setFlying(false); + } + + if (FactionsPlugin.getInstance().getSeeChunkUtil() != null) { + FactionsPlugin.getInstance().getSeeChunkUtil().updatePlayerInfo(UUID.fromString(me.getId()), me.isSeeingChunk()); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerQuit(PlayerQuitEvent event) { + FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer()); + + FactionsPlugin.getInstance().getLandRaidControl().onQuit(me); + // and update their last login time to point to when the logged off, for auto-remove routine + me.setLastLoginTime(System.currentTimeMillis()); + + me.logout(); // cache kills / deaths + + // if player is waiting for fstuck teleport but leaves, remove + if (FactionsPlugin.getInstance().getStuckMap().containsKey(me.getPlayer().getUniqueId())) { + FPlayers.getInstance().getByPlayer(me.getPlayer()).msg(TL.COMMAND_STUCK_CANCELLED); + FactionsPlugin.getInstance().getStuckMap().remove(me.getPlayer().getUniqueId()); + FactionsPlugin.getInstance().getTimers().remove(me.getPlayer().getUniqueId()); + } + + Faction myFaction = me.getFaction(); + if (!myFaction.isWilderness()) { + myFaction.memberLoggedOff(); + } + + if (!myFaction.isWilderness()) { + for (FPlayer player : myFaction.getFPlayersWhereOnline(true)) { + if (player != me && player.isMonitoringJoins()) { + player.msg(TL.FACTION_LOGOUT, me.getName()); + } + } + } + + FScoreboard.remove(me, event.getPlayer()); + + if (FactionsPlugin.getInstance().getSeeChunkUtil() != null) { + FactionsPlugin.getInstance().getSeeChunkUtil().updatePlayerInfo(UUID.fromString(me.getId()), false); + } + me.setOfflinePlayer(null); + } + + // Holds the next time a player can have a map shown. + private final HashMap showTimes = new HashMap<>(); + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerMove(PlayerMoveEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + + // clear visualization + if (event.getFrom().getBlockX() != event.getTo().getBlockX() || event.getFrom().getBlockY() != event.getTo().getBlockY() || event.getFrom().getBlockZ() != event.getTo().getBlockZ()) { + VisualizeUtil.clear(event.getPlayer()); + Player player = event.getPlayer(); + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me.isWarmingUp()) { + me.clearWarmup(); + me.msg(TL.WARMUPS_CANCELLED); + } + } + + // quick check to make sure player is moving between chunks; good performance boost + if (event.getFrom().getBlockX() >> 4 == event.getTo().getBlockX() >> 4 && event.getFrom().getBlockZ() >> 4 == event.getTo().getBlockZ() >> 4 && event.getFrom().getWorld() == event.getTo().getWorld()) { + return; + } + + // Did we change coord? + Player player = event.getPlayer(); + FPlayer me = FPlayers.getInstance().getByPlayer(player); + FLocation from = me.getLastStoodAt(); + FLocation to = new FLocation(event.getTo()); + + if (from.equals(to)) { + return; + } + + // Yes we did change coord (: + + me.setLastStoodAt(to); + + boolean canFlyPreClaim = me.canFlyAtLocation(); + + if (me.getAutoClaimFor() != null) { + me.attemptClaim(me.getAutoClaimFor(), event.getTo(), true); + } else if (me.isAutoSafeClaimEnabled()) { + if (!Permission.MANAGE_SAFE_ZONE.has(player)) { + me.setIsAutoSafeClaimEnabled(false); + } else { + if (!Board.getInstance().getFactionAt(to).isSafeZone()) { + Board.getInstance().setFactionAt(Factions.getInstance().getSafeZone(), to); + me.msg(TL.PLAYER_SAFEAUTO); + } + } + } else if (me.isAutoWarClaimEnabled()) { + if (!Permission.MANAGE_WAR_ZONE.has(player)) { + me.setIsAutoWarClaimEnabled(false); + } else { + if (!Board.getInstance().getFactionAt(to).isWarZone()) { + Board.getInstance().setFactionAt(Factions.getInstance().getWarZone(), to); + me.msg(TL.PLAYER_WARAUTO); + } + } + } + + // Did we change "host"(faction)? + Faction factionFrom = Board.getInstance().getFactionAt(from); + Faction factionTo = Board.getInstance().getFactionAt(to); + boolean changedFaction = (factionFrom != factionTo); + + free: if (plugin.conf().commands().fly().isEnable() && !me.isAdminBypassing() && !Permission.FLY_ANY.has(player)) { + boolean canFly = me.canFlyInFactionTerritory(factionTo); + if (!changedFaction){ + if (canFly && !canFlyPreClaim && me.isFlying() && plugin.conf().commands().fly().isDisableFlightDuringAutoclaim()) { + //me.setFlying(false); + } + break free; + } + if (me.isFlying() && !canFly) { + //me.setFlying(false); + } else if (me.isAutoFlying() && !me.isFlying() && canFly) { + //me.setFlying(true); + } + } + + if (me.isMapAutoUpdating()) { + if (!showTimes.containsKey(player.getUniqueId()) || (showTimes.get(player.getUniqueId()) < System.currentTimeMillis())) { + me.sendFancyMessage(Board.getInstance().getMap(me, to, player.getLocation().getYaw())); + showTimes.put(player.getUniqueId(), System.currentTimeMillis() + FactionsPlugin.getInstance().conf().commands().map().getCooldown()); + } + } else { + Faction myFaction = me.getFaction(); + String ownersTo = myFaction.getOwnerListString(to); + + if (changedFaction) { + me.sendFactionHereMessage(factionFrom); + if (FactionsPlugin.getInstance().conf().factions().ownedArea().isEnabled() && FactionsPlugin.getInstance().conf().factions().ownedArea().isMessageOnBorder() && myFaction == factionTo && !ownersTo.isEmpty()) { + me.sendMessage(TL.GENERIC_OWNERS.format(ownersTo)); + } + } else if (FactionsPlugin.getInstance().conf().factions().ownedArea().isEnabled() && FactionsPlugin.getInstance().conf().factions().ownedArea().isMessageInsideTerritory() && myFaction == factionTo && !myFaction.isWilderness()) { + String ownersFrom = myFaction.getOwnerListString(from); + if (FactionsPlugin.getInstance().conf().factions().ownedArea().isMessageByChunk() || !ownersFrom.equals(ownersTo)) { + if (!ownersTo.isEmpty()) { + me.sendMessage(TL.GENERIC_OWNERS.format(ownersTo)); + } else if (!TL.GENERIC_PUBLICLAND.toString().isEmpty()) { + me.sendMessage(TL.GENERIC_PUBLICLAND.toString()); + } + } + } + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerInteract(PlayerInteractEntityEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + switch (event.getRightClicked().getType()) { + case ITEM_FRAME: + if (!canPlayerUseBlock(event.getPlayer(), Material.ITEM_FRAME, event.getRightClicked().getLocation(), false)) { + event.setCancelled(true); + } + break; + case HORSE: + case SKELETON_HORSE: + case ZOMBIE_HORSE: + case DONKEY: + case MULE: + case LLAMA: + case TRADER_LLAMA: + case PIG: + case LEASH_HITCH: + case MINECART_CHEST: + case MINECART_FURNACE: + case MINECART_HOPPER: + if (!FactionsPlugin.getInstance().conf().factions().protection().getEntityInteractExceptions().contains(event.getRightClicked().getType().name()) && + !this.playerCanInteractHere(event.getPlayer(), event.getRightClicked().getLocation())) { + event.setCancelled(true); + } + break; + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerInteract(PlayerInteractEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + // only need to check right-clicks and physical as of MC 1.4+; good performance boost + if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) { + return; + } + + Block block = event.getClickedBlock(); + Player player = event.getPlayer(); + + if (block == null) { + return; // clicked in air, apparently + } + + if (!canPlayerUseBlock(player, block.getType(), block.getLocation(), false)) { + event.setCancelled(true); + if (block.getType().name().endsWith("_PLATE")) { + return; + } + if (FactionsPlugin.getInstance().conf().exploits().isInteractionSpam()) { + String name = player.getName(); + InteractAttemptSpam attempt = interactSpammers.get(name); + if (attempt == null) { + attempt = new InteractAttemptSpam(); + interactSpammers.put(name, attempt); + } + int count = attempt.increment(); + if (count >= 10) { + FPlayer me = FPlayers.getInstance().getByPlayer(player); + me.msg(TL.PLAYER_OUCH); + player.damage(NumberConversions.floor((double) count / 10)); + } + } + return; + } + + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { + return; // only interested on right-clicks for below + } + + ItemStack item; + if ((item = event.getItem()) != null) { + boolean ohNo = false; + switch (item.getType()) { + case ARMOR_STAND: + case END_CRYSTAL: + case MINECART: + case CHEST_MINECART: + case COMMAND_BLOCK_MINECART: + case FURNACE_MINECART: + case HOPPER_MINECART: + case TNT_MINECART: + ohNo = true; + } + if (ohNo && + !FactionsPlugin.getInstance().conf().factions().specialCase().getIgnoreBuildMaterials().contains(item.getType()) && + !FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getClickedBlock().getRelative(event.getBlockFace()).getLocation(), PermissibleAction.BUILD, false)) { + event.setCancelled(true); + } + } + + if (!playerCanUseItemHere(player, block.getLocation(), event.getMaterial(), false)) { + event.setCancelled(true); + } + } + + + // for handling people who repeatedly spam attempts to open a door (or similar) in another faction's territory + private final Map interactSpammers = new HashMap<>(); + + private static class InteractAttemptSpam { + private int attempts = 0; + private long lastAttempt = System.currentTimeMillis(); + + // returns the current attempt count + public int increment() { + long Now = System.currentTimeMillis(); + if (Now > lastAttempt + 2000) { + attempts = 1; + } else { + attempts++; + } + lastAttempt = Now; + return attempts; + } + } + + public boolean playerCanUseItemHere(Player player, Location location, Material material, boolean justCheck) { + String name = player.getName(); + MainConfig.Factions facConf = FactionsPlugin.getInstance().conf().factions(); + if (facConf.protection().getPlayersWhoBypassAllProtection().contains(name)) { + return true; + } + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me.isAdminBypassing()) { + return true; + } + + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getInstance().getFactionAt(loc); + + if (FactionsPlugin.getInstance().getLandRaidControl().isRaidable(otherFaction)) { + return true; + } + + if (otherFaction.hasPlayersOnline()) { + if (!facConf.protection().getTerritoryDenyUsageMaterials().contains(material)) { + return true; // Item isn't one we're preventing for online factions. + } + } else { + if (!facConf.protection().getTerritoryDenyUsageMaterialsWhenOffline().contains(material)) { + return true; // Item isn't one we're preventing for offline factions. + } + } + + if (otherFaction.isWilderness()) { + if (!facConf.protection().isWildernessDenyUsage() || facConf.protection().getWorldsNoWildernessProtection().contains(location.getWorld().getName())) { + return true; // This is not faction territory. Use whatever you like here. + } + + if (!justCheck) { + me.msg(TL.PLAYER_USE_WILDERNESS, TextUtil.getMaterialName(material)); + } + + return false; + } else if (otherFaction.isSafeZone()) { + if (!facConf.protection().isSafeZoneDenyUsage() || Permission.MANAGE_SAFE_ZONE.has(player)) { + return true; + } + + if (!justCheck) { + me.msg(TL.PLAYER_USE_SAFEZONE, TextUtil.getMaterialName(material)); + } + + return false; + } else if (otherFaction.isWarZone()) { + if (!facConf.protection().isWarZoneDenyUsage() || Permission.MANAGE_WAR_ZONE.has(player)) { + return true; + } + + if (!justCheck) { + me.msg(TL.PLAYER_USE_WARZONE, TextUtil.getMaterialName(material)); + } + + return false; + } + + if (!otherFaction.hasAccess(me, PermissibleAction.ITEM)) { + if (!justCheck) { + me.msg(TL.PLAYER_USE_TERRITORY, TextUtil.getMaterialName(material), otherFaction.getTag(me.getFaction())); + } + return false; + } + + // Also cancel if player doesn't have ownership rights for this claim + if (facConf.ownedArea().isEnabled() && facConf.ownedArea().isDenyUsage() && !otherFaction.playerHasOwnershipRights(me, loc)) { + if (!justCheck) { + me.msg(TL.PLAYER_USE_OWNED, TextUtil.getMaterialName(material), otherFaction.getOwnerListString(loc)); + } + + return false; + } + + return true; + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerRespawn(PlayerRespawnEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer()); + + FactionsPlugin.getInstance().getLandRaidControl().onRespawn(me); + + Location home = me.getFaction().getHome(); + MainConfig.Factions facConf = FactionsPlugin.getInstance().conf().factions(); + if (facConf.homes().isEnabled() && + facConf.homes().isTeleportToOnDeath() && + home != null && + (facConf.landRaidControl().power().isRespawnHomeFromNoPowerLossWorlds() || !facConf.landRaidControl().power().getWorldsNoPowerLoss().contains(event.getPlayer().getWorld().getName()))) { + event.setRespawnLocation(home); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onTeleport(PlayerTeleportEvent event) { + FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer()); + boolean isEnabled = plugin.worldUtil().isEnabled(event.getTo().getWorld()); + if(event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND || + event.getCause() == PlayerTeleportEvent.TeleportCause.UNKNOWN || + event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN){ + if(!Essentials.handleDefaultTeleport(event.getPlayer(), event.getTo())){ + event.setCancelled(true); + return; + } + } + if (!isEnabled) { + FScoreboard.remove(me, event.getPlayer()); + if (me.isFlying()) { + //me.setFlying(false); + } + return; + } + if (!event.getFrom().getWorld().equals(event.getTo().getWorld()) && !plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + FactionsPlugin.getInstance().getLandRaidControl().update(me); + this.initFactionWorld(me); + } + + FLocation to = new FLocation(event.getTo()); + me.setLastStoodAt(to); + + // Check the location they're teleporting to and check if they can fly there. + if (plugin.conf().commands().fly().isEnable() && !me.isAdminBypassing()) { + boolean canFly = me.canFlyAtLocation(to); + if (me.isFlying() && !canFly) { + //me.setFlying(false, false); + } else if (me.isAutoFlying() && !me.isFlying() && canFly) { + //me.setFlying(true); + } + } + + } + + // For some reason onPlayerInteract() sometimes misses bucket events depending on distance (something like 2-3 blocks away isn't detected), + // but these separate bucket events below always fire without fail + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + Block block = event.getBlockClicked(); + Player player = event.getPlayer(); + + if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerBucketFill(PlayerBucketFillEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + Block block = event.getBlockClicked(); + Player player = event.getPlayer(); + + if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { + event.setCancelled(true); + } + } + + public static boolean preventCommand(String fullCmd, Player player) { + MainConfig.Factions.Protection protection = FactionsPlugin.getInstance().conf().factions().protection(); + if ((protection.getTerritoryNeutralDenyCommands().isEmpty() && + protection.getTerritoryEnemyDenyCommands().isEmpty() && + protection.getPermanentFactionMemberDenyCommands().isEmpty() && + protection.getWildernessDenyCommands().isEmpty() && + protection.getTerritoryAllyDenyCommands().isEmpty() && + protection.getWarzoneDenyCommands().isEmpty())) { + return false; + } + + fullCmd = fullCmd.toLowerCase(); + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + + String shortCmd; // command without the slash at the beginning + if (fullCmd.startsWith("/")) { + shortCmd = fullCmd.substring(1); + } else { + shortCmd = fullCmd; + fullCmd = "/" + fullCmd; + } + + if (me.hasFaction() && + !me.isAdminBypassing() && + !protection.getPermanentFactionMemberDenyCommands().isEmpty() && + me.getFaction().isPermanent() && + isCommandInSet(fullCmd, shortCmd, protection.getPermanentFactionMemberDenyCommands())) { + me.msg(TL.PLAYER_COMMAND_PERMANENT, fullCmd); + return true; + } + + Faction at = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); + if (at.isWilderness() && !protection.getWildernessDenyCommands().isEmpty() && !me.isAdminBypassing() && isCommandInSet(fullCmd, shortCmd, protection.getWildernessDenyCommands())) { + me.msg(TL.PLAYER_COMMAND_WILDERNESS, fullCmd); + return true; + } + + Relation rel = at.getRelationTo(me); + if (at.isNormal() && rel.isAlly() && !protection.getTerritoryAllyDenyCommands().isEmpty() && !me.isAdminBypassing() && isCommandInSet(fullCmd, shortCmd, protection.getTerritoryAllyDenyCommands())) { + me.msg(TL.PLAYER_COMMAND_ALLY, fullCmd); + return true; + } + + if (at.isNormal() && rel.isNeutral() && !protection.getTerritoryNeutralDenyCommands().isEmpty() && !me.isAdminBypassing() && isCommandInSet(fullCmd, shortCmd, protection.getTerritoryNeutralDenyCommands())) { + me.msg(TL.PLAYER_COMMAND_NEUTRAL, fullCmd); + return true; + } + + if (at.isNormal() && rel.isEnemy() && !protection.getTerritoryEnemyDenyCommands().isEmpty() && !me.isAdminBypassing() && isCommandInSet(fullCmd, shortCmd, protection.getTerritoryEnemyDenyCommands())) { + me.msg(TL.PLAYER_COMMAND_ENEMY, fullCmd); + return true; + } + + if (at.isWarZone() && !protection.getWarzoneDenyCommands().isEmpty() && !me.isAdminBypassing() && isCommandInSet(fullCmd, shortCmd, protection.getWarzoneDenyCommands())) { + me.msg(TL.PLAYER_COMMAND_WARZONE, fullCmd); + return true; + } + + return false; + } + + private static boolean isCommandInSet(String fullCmd, String shortCmd, Set set) { + for (String string : set) { + if (string == null) { + continue; + } + string = string.toLowerCase(); + if (fullCmd.startsWith(string) || shortCmd.startsWith(string)) { + return true; + } + } + return false; + } + + public void handleChestClick(InventoryClickEvent event){ + if(event.getSlot() < 0)return; + FPlayer fPlayer = FPlayers.getInstance().getById(event.getWhoClicked().getUniqueId().toString()); + if(fPlayer != null && fPlayer.isAdminBypassing())return; + Inventory openInv = event.getWhoClicked().getOpenInventory().getTopInventory(); + + Inventory bottomInventory = event.getWhoClicked().getOpenInventory().getBottomInventory(); + + if(!(openInv.getHolder() instanceof FChestHolder))return; + + if(!FactionsPlugin.getInstance().getConfigManager().getMainConfig().upgrades().chest().preventSpawnersInChest())return; + + if(event.getClick() == ClickType.NUMBER_KEY){ + ItemStack keyedItem = event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); + + if(keyedItem != null && keyedItem.getType() == MaterialDb.get("MOB_SPAWNER")){ + event.setCancelled(true); + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + return; + } + + /*if(openInv.getSize() > event.getRawSlot()){ + ItemStack rawTop = openInv.getItem(event.getRawSlot()); + + if(rawTop != null && rawTop.getType().equals(MaterialDb.get("MOB_SPAWNER"))){ + event.setCancelled(true); + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + return; + } + } + + if(openInv.getSize() > event.getSlot()){ + ItemStack rawTop = openInv.getItem(event.getSlot()); + + if(rawTop != null && rawTop.getType().equals(MaterialDb.get("MOB_SPAWNER"))){ + event.setCancelled(true); + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + return; + } + } + + if(bottomInventory.getSize() > event.getRawSlot()){ + ItemStack rawTop = bottomInventory.getItem(event.getRawSlot()); + + if(rawTop != null && rawTop.getType().equals(MaterialDb.get("MOB_SPAWNER"))){ + event.setCancelled(true); + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + return; + } + } + + if(bottomInventory.getSize() > event.getSlot()){ + ItemStack rawTop = bottomInventory.getItem(event.getSlot()); + + if(rawTop != null && rawTop.getType().equals(MaterialDb.get("MOB_SPAWNER"))){ + event.setCancelled(true); + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + return; + } + }*/ + } + + if(event.getCurrentItem() != null && event.getCurrentItem().getType() == MaterialDb.get("MOB_SPAWNER")){ + event.setCancelled(true); + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + return; + } + + if(event.getCursor() != null && event.getCursor().getType() == MaterialDb.get("MOB_SPAWNER")){ + event.setCancelled(true); + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + return; + } + + if(openInv.getSize() > event.getSlot()){ + ItemStack rawTop = openInv.getItem(event.getSlot()); + + if(rawTop != null && rawTop.getType().equals(MaterialDb.get("MOB_SPAWNER"))){ + event.setCancelled(true); + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + return; + } + } + + if(bottomInventory.getSize() > event.getSlot()){ + ItemStack rawTop = bottomInventory.getItem(event.getSlot()); + + if(rawTop != null && rawTop.getType().equals(MaterialDb.get("MOB_SPAWNER"))){ + event.getWhoClicked().sendMessage(TextUtil.parseColor(TL.PLAYER_CANTADDTHATITEM.getDefault())); + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerInteractGUI(InventoryClickEvent event) { + if (!plugin.worldUtil().isEnabled(event.getWhoClicked().getWorld())) { + return; + } + + handleChestClick(event); + + Inventory clickedInventory = getClickedInventory(event); + if (clickedInventory == null) { + return; + } + if (clickedInventory.getHolder() instanceof GUI) { + event.setCancelled(true); + GUI ui = (GUI) clickedInventory.getHolder(); + ui.click(event.getRawSlot(), event.getClick()); + } + } + + private Inventory getClickedInventory(InventoryClickEvent event) { + int rawSlot = event.getRawSlot(); + InventoryView view = event.getView(); + if (rawSlot < 0 || rawSlot >= view.countSlots()) { // < 0 check also covers situation of InventoryView.OUTSIDE (-999) + return null; + } + if (rawSlot < view.getTopInventory().getSize()) { + return view.getTopInventory(); + } else { + return view.getBottomInventory(); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerMoveGUI(InventoryDragEvent event) { + if (!plugin.worldUtil().isEnabled(event.getWhoClicked().getWorld())) { + return; + } + + if (event.getInventory().getHolder() instanceof GUI) { + event.setCancelled(true); + } + } + + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerKick(PlayerKickEvent event) { + FPlayer badGuy = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (badGuy == null) { + return; + } + + // if player was banned (not just kicked), get rid of their stored info + if (FactionsPlugin.getInstance().conf().factions().other().isRemovePlayerDataWhenBanned() && event.getReason().equals("Banned by admin.")) { + if (badGuy.getRole() == Role.ADMIN) { + badGuy.getFaction().promoteNewLeader(); + } + + badGuy.leave(false); + badGuy.remove(); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + final public void onFactionJoin(FPlayerJoinEvent event) { + FTeamWrapper.applyUpdatesLater(event.getFaction()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onFactionLeave(FPlayerLeaveEvent event) { + FTeamWrapper.applyUpdatesLater(event.getFaction()); + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + if (FactionsPlayerListener.preventCommand(event.getMessage(), event.getPlayer())) { + if (plugin.logPlayerCommands()) { + plugin.getLogger().info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": " + event.getMessage()); + } + event.setCancelled(true); + }else if(FactionsPlugin.getInstance().conf().commands().fly().isInterceptFlyCommand() && + !event.getPlayer().hasPermission("essentials.fly") && + (event.getMessage().startsWith("/fly ") || event.getMessage().equalsIgnoreCase("/fly") || + event.getMessage().startsWith("/efly ") || event.getMessage().equalsIgnoreCase("/efly"))){ + event.setCancelled(true); + + event.getPlayer().performCommand("f fly"); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerPreLogin(PlayerLoginEvent event) { + FPlayers.getInstance().getByPlayer(event.getPlayer()); + } + + @EventHandler + public void onPlayerFallDamageInOwnClaims(EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (event.getCause() != EntityDamageEvent.DamageCause.FALL) return; + FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) event.getEntity()); + if (!fplayer.getRelationToLocation().isMember()) return; + event.setCancelled(true); + } + + // inspect + @EventHandler + public void onInspect(PlayerInteractEvent e) { + if (e.getAction().name().contains("BLOCK")) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(e.getPlayer()); + if (!fplayer.isInspectMode()) + return; + e.setCancelled(true); + + Player player = e.getPlayer(); + + if (Cooldown.isOnCooldown(player, "faction-inspect-mode")) { + return; + } else { + Cooldown.setCooldown(player, "faction-inspect-mode", 1); + } + + if (!fplayer.isAdminBypassing()) { + if (!fplayer.hasFaction()) { + fplayer.setInspectMode(false); + fplayer.msg(TL.COMMAND_INSPECT_DISABLED_NOFAC); + return; + } + if (fplayer.getFaction() != Board.getInstance() + .getFactionAt(new FLocation(e.getPlayer().getLocation()))) { + fplayer.msg(TL.COMMAND_INSPECT_NOTINCLAIM); + return; + } + } else + fplayer.msg(TL.COMMAND_INSPECT_BYPASS); + List info = CoreProtect.getInstance() .getAPI().blockLookup(e.getClickedBlock(), 0); + if (info.isEmpty()) { + e.getPlayer().sendMessage(TL.COMMAND_INSPECT_NODATA.toString()); + return; + } + CoreProtectAPI coAPI = CoreProtect.getInstance().getAPI(); + player.sendMessage(TL.COMMAND_INSPECT_HEADER.toString().replace("{x}", e.getClickedBlock().getX() + "") + .replace("{y}", e.getClickedBlock().getY() + "").replace("{z}", e.getClickedBlock().getZ() + "")); + String rowFormat = TL.COMMAND_INSPECT_ROW.toString(); + for (String[] strings : info) { + CoreProtectAPI.ParseResult row = coAPI.parseResult(strings); + player.sendMessage(rowFormat.replace("{time}", convertTime(row.getTime())) + .replace("{action}", row.getActionString()).replace("{player}", row.getPlayer()) + .replace("{block-type}", row.getType().toString().toLowerCase())); + } + } + } + + private String convertTime(int time) { + String result = String.valueOf(Math.round((System.currentTimeMillis() / 1000L - time) / 36.0D) / 100.0D); + return (result.length() == 3 ? result + "0" : result) + "/hrs ago"; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsSpawnerBoostListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsSpawnerBoostListener.java new file mode 100644 index 0000000..5c8a86d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/FactionsSpawnerBoostListener.java @@ -0,0 +1,68 @@ +package com.massivecraft.factions.listeners; + +public class FactionsSpawnerBoostListener extends AbstractListener{ + +/* public FactionsPlugin plugin; + + public FactionsSpawnerBoostListener(FactionsPlugin plugin) { + this.plugin = plugin; + } + + private static Field spawnDelay; + + private static Method getTileEntity; + + private static Method getSpawner; + + private static boolean doSpawnerUpgrade; + + static{ + try{ + Class mobSpawnerAbstractClass = Class.forName("net.minecraft.server." + FactionsPlugin.version() + ".MobSpawnerAbstract"); + + getTileEntity = Class.forName("org.bukkit.craftbukkit." + FactionsPlugin.version() + ".block.CraftCreatureSpawner").getMethod("getTileEntity"); + + getSpawner = Class.forName("net.minecraft.server." + FactionsPlugin.version() + ".TileEntityMobSpawner").getMethod("getSpawner"); + + spawnDelay = mobSpawnerAbstractClass.getField("spawnDelay"); + }catch(ClassNotFoundException | NoSuchMethodException | NoSuchFieldException e){ + e.printStackTrace(); + + Bukkit.getLogger().severe("[Factions] - There was an error while setting up the spawner upgrade!"); + + doSpawnerUpgrade = false; + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onSpawn(SpawnerPreSpawnEvent e) throws InvocationTargetException, IllegalAccessException { + if(!doSpawnerUpgrade || !FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().isEnabled())return; + + FLocation fLocation = new FLocation(e.getLocation()); + + Faction factionAt = Board.getInstance().getFactionAt(fLocation); + + if(factionAt.isWilderness())return; + + int upgrade = factionAt.getUpgrade(UpgradeType.SPAWNER_BOOST); + + if(upgrade <= 0 && FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().getDefaultBoost() == 1.0D)return; + + double boost = FactionsPlugin.getInstance().conf().upgrades().spawnerBoost().getNumber(upgrade); + + CreatureSpawner creatureSpawner = (CreatureSpawner) e.getLocation().getBlock().getState(); + + Object tileEntityMobSpawner = getSpawner.invoke(getTileEntity.invoke(creatureSpawner)); + + new BukkitRunnable() { + @Override + public void run() { + try { + spawnDelay.set(tileEntityMobSpawner, (int) Math.floor((int) spawnDelay.get(tileEntityMobSpawner) * boost)); + } catch (IllegalAccessException ex) { + ex.printStackTrace(); + } + } + }.runTaskLaterAsynchronously(FactionsPlugin.getInstance(), 1); + }*/ +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/OneEightPlusListener.java b/Factions/src/main/java/com/massivecraft/factions/listeners/OneEightPlusListener.java new file mode 100644 index 0000000..abb746d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/OneEightPlusListener.java @@ -0,0 +1,32 @@ +package com.massivecraft.factions.listeners; + +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.player.PlayerArmorStandManipulateEvent; + +public class OneEightPlusListener extends AbstractListener { + private final FactionsPlugin plugin; + + public OneEightPlusListener(FactionsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerInteract(PlayerArmorStandManipulateEvent event) { + if (!plugin.worldUtil().isEnabled(event.getPlayer().getWorld())) { + return; + } + + if (!canPlayerUseBlock(event.getPlayer(), Material.ARMOR_STAND, event.getRightClicked().getLocation(), false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockExplode(BlockExplodeEvent event) { + this.handleExplosion(event.getBlock().getLocation(), null, event, event.blockList()); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalHandler.java b/Factions/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalHandler.java new file mode 100644 index 0000000..1e166c0 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalHandler.java @@ -0,0 +1,36 @@ +package com.massivecraft.factions.listeners.versionspecific; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Relation; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public class PortalHandler implements PortalListenerBase { + @Override + public boolean shouldCancel(Location location, Player player) { + if (!FactionsPlugin.getInstance().worldUtil().isEnabled(player.getWorld())) { + return true; + } + + if (!FactionsPlugin.getInstance().conf().factions().portals().isLimit()) { + return false; // Don't do anything if they don't want us to. + } + FLocation loc = new FLocation(location); + Faction faction = Board.getInstance().getFactionAt(loc); + if (faction.isWilderness()) { + return false; // We don't care about wilderness. + } else if (!faction.isNormal() && !player.isOp()) { + // Don't let non ops make portals in safezone or warzone. + return true; + } + + FPlayer fp = FPlayers.getInstance().getByPlayer(player); + String mininumRelation = FactionsPlugin.getInstance().conf().factions().portals().getMinimumRelation(); // Defaults to Neutral if typed wrong. + return !fp.getFaction().getRelationTo(faction).isAtLeast(Relation.fromString(mininumRelation)); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListener_114.java b/Factions/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListener_114.java new file mode 100644 index 0000000..fa377c7 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/listeners/versionspecific/PortalListener_114.java @@ -0,0 +1,68 @@ +package com.massivecraft.factions.listeners.versionspecific; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.util.TL; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.world.PortalCreateEvent; + +/* + Blocking all portal creation not in wilderness because we can't properly check if the creator has permission + to create at the target destination. + */ +public class PortalListener_114 implements Listener { + public FactionsPlugin plugin; + + public PortalListener_114(FactionsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onPortalCreate(PortalCreateEvent event) { + Entity entity = event.getEntity(); + + if (!FactionsPlugin.getInstance().conf().factions().portals().isLimit()) { + return; // Don't do anything if they don't want us to. + } + + if (!(entity instanceof Player) || !plugin.worldUtil().isEnabled(event.getEntity().getWorld())) { + return; + } + + Player player = (Player) entity; + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + + // Only 8 blocks so a loop should be fine. + for (BlockState block : event.getBlocks()) { + FLocation loc = new FLocation(block.getLocation()); + Faction faction = Board.getInstance().getFactionAt(loc); + + if (faction.isWilderness()) { + continue; // We don't care about wilderness. + } else if (!faction.isNormal() && !player.isOp()) { + // Don't let non ops make portals in safezone or warzone. + event.setCancelled(true); + return; + } + + String mininumRelation = FactionsPlugin.getInstance().conf().factions().portals().getMinimumRelation(); + + // Don't let people portal into nether bases if server owners don't want that. + if (!fPlayer.getFaction().getRelationTo(faction).isAtLeast(Relation.fromString(mininumRelation))) { + event.setCancelled(true); + player.sendMessage(TL.PLAYER_PORTAL_NOTALLOWED.toString()); + return; + } + } + + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/perms/Permissible.java b/Factions/src/main/java/com/massivecraft/factions/perms/Permissible.java new file mode 100644 index 0000000..ef77e68 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/perms/Permissible.java @@ -0,0 +1,9 @@ +package com.massivecraft.factions.perms; + +import org.bukkit.ChatColor; + +public interface Permissible { + String name(); + + ChatColor getColor(); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/perms/PermissibleAction.java b/Factions/src/main/java/com/massivecraft/factions/perms/PermissibleAction.java new file mode 100644 index 0000000..192f2e6 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/perms/PermissibleAction.java @@ -0,0 +1,123 @@ +package com.massivecraft.factions.perms; + +import com.massivecraft.factions.config.file.DefaultPermissionsConfig; +import com.massivecraft.factions.util.TL; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.Material; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +public enum PermissibleAction { + BUILD(DefaultPermissionsConfig.Permissions::getBuild, TL.PERM_BUILD, TL.PERM_SHORT_BUILD, "STONE"), + DESTROY(DefaultPermissionsConfig.Permissions::getDestroy, TL.PERM_DESTROY, TL.PERM_SHORT_DESTROY, "WOODEN_PICKAXE"), + PAINBUILD(DefaultPermissionsConfig.Permissions::getPainBuild, TL.PERM_PAINBUILD, TL.PERM_SHORT_PAINBUILD, "WOODEN_SWORD"), + ITEM(DefaultPermissionsConfig.Permissions::getItem, TL.PERM_ITEM, TL.PERM_SHORT_ITEM, "ITEM_FRAME"), + CONTAINER(DefaultPermissionsConfig.Permissions::getContainer, TL.PERM_CONTAINER, TL.PERM_SHORT_CONTAINER, "CHEST_MINECART"), + BUTTON(DefaultPermissionsConfig.Permissions::getButton, TL.PERM_BUTTON, TL.PERM_SHORT_BUTTON, "STONE_BUTTON"), + DOOR(DefaultPermissionsConfig.Permissions::getDoor, TL.PERM_DOOR, TL.PERM_SHORT_DOOR, "IRON_DOOR"), + LEVER(DefaultPermissionsConfig.Permissions::getLever, TL.PERM_LEVER, TL.PERM_SHORT_LEVER, "LEVER"), + PLATE(DefaultPermissionsConfig.Permissions::getPlate, TL.PERM_PLATE, TL.PERM_SHORT_PLATE, "STONE_PRESSURE_PLATE"), + FROSTWALK(DefaultPermissionsConfig.Permissions::getFrostWalk, TL.PERM_FROSTWALK, TL.PERM_SHORT_FROSTWALK, "ICE"), + INVITE(true, DefaultPermissionsConfig.Permissions::getInvite, TL.PERM_INVITE, TL.PERM_SHORT_INVITE, "FISHING_ROD"), + KICK(true, DefaultPermissionsConfig.Permissions::getKick, TL.PERM_KICK, TL.PERM_SHORT_KICK, "LEATHER_BOOTS"), + BAN(true, DefaultPermissionsConfig.Permissions::getBan, TL.PERM_BAN, TL.PERM_SHORT_BAN, "BARRIER"), + PROMOTE(true, DefaultPermissionsConfig.Permissions::getPromote, TL.PERM_PROMOTE, TL.PERM_SHORT_PROMOTE, "ANVIL"), + DISBAND(true, DefaultPermissionsConfig.Permissions::getDisband, TL.PERM_DISBAND, TL.PERM_SHORT_DISBAND, "BONE"), + ECONOMY(true, DefaultPermissionsConfig.Permissions::getEconomy, TL.PERM_ECONOMY, TL.PERM_SHORT_ECONOMY, "GOLD_INGOT"), + TERRITORY(true, DefaultPermissionsConfig.Permissions::getTerritory, TL.PERM_TERRITORY, TL.PERM_SHORT_TERRITORY, "GRASS_BLOCK"), + OWNER(true, DefaultPermissionsConfig.Permissions::getOwner, TL.PERM_OWNER, TL.PERM_SHORT_OWNER, "FENCE_GATE"), + HOME(DefaultPermissionsConfig.Permissions::getHome, TL.PERM_HOME, TL.PERM_SHORT_HOME, "TORCH"), + REPEATER(DefaultPermissionsConfig.Permissions::getRepeater, TL.PERM_REPEATER, TL.PERM_SHORT_REPEATER, "DIODE"), + SETHOME(true, DefaultPermissionsConfig.Permissions::getSetHome, TL.PERM_SETHOME, TL.PERM_SHORT_SETHOME, "COMPASS"), + LISTCLAIMS(true, DefaultPermissionsConfig.Permissions::getListClaims, TL.PERM_LISTCLAIMS, TL.PERM_SHORT_LISTCLAIMS, "MAP"), + SETWARP(true, DefaultPermissionsConfig.Permissions::getSetWarp, TL.PERM_SETWARP, TL.PERM_SHORT_SETWARP, "END_PORTAL_FRAME"), + TNTDEPOSIT(true, DefaultPermissionsConfig.Permissions::getTNTDeposit, TL.PERM_TNTDEPOSIT, TL.PERM_SHORT_TNTDEPOSIT, "TNT"), + TNTWITHDRAW(true, DefaultPermissionsConfig.Permissions::getTNTWithdraw, TL.PERM_TNTWITHDRAW, TL.PERM_SHORT_TNTWITHDRAW, "TNT"), + WARP(DefaultPermissionsConfig.Permissions::getWarp, TL.PERM_WARP, TL.PERM_SHORT_WARP, "ENDER_PEARL"), + FLY(DefaultPermissionsConfig.Permissions::getFly, TL.PERM_FLY, TL.PERM_SHORT_FLY, "FEATHER"), + ROSTERCONTROL(true, DefaultPermissionsConfig.Permissions::getRosterControl, TL.PERM_ROSTERCONTROL, TL.PERM_SHORT_ROSTERCONTROL, "ANVIL"), + CLAIM_CORNER(true, DefaultPermissionsConfig.Permissions::getCorner, TL.PERM_CLAIMCORNER, TL.PERM_SHORT_CLAIMCORNER, "MAP"), + COLLECTOR_ACCESS(true, DefaultPermissionsConfig.Permissions::getCollectorAccess, TL.PERM_COLLECTOR_ACCESS, TL.PERM_SHORT_COLLECTOR_ACCESS, "BEACON"), + ; + + private final boolean factionOnly; + private final String materialName; + private final TL desc; + private final TL shortDesc; + private Material material; + private Function fullFunction; + private Function factionOnlyFunction; + + PermissibleAction(Function fullFunction, TL desc, TL shortDesc, String materialName) { + this.factionOnly = false; + this.fullFunction = fullFunction; + this.desc = desc; + this.shortDesc = shortDesc; + this.materialName = materialName; + } + + PermissibleAction(boolean factionOnly, Function factionOnlyFunction, TL desc, TL shortDesc, String materialName) { + this.factionOnly = factionOnly; + if (this.factionOnly) { + this.factionOnlyFunction = factionOnlyFunction; + } else { + throw new AssertionError("May only set factionOnly actions in this constructor"); + } + this.desc = desc; + this.shortDesc = shortDesc; + this.materialName = materialName; + } + + private static final Map map = new HashMap<>(); + + static { + for (PermissibleAction action : values()) { + map.put(action.name().toLowerCase(), action); + } + } + + public boolean isFactionOnly() { + return this.factionOnly; + } + + public DefaultPermissionsConfig.Permissions.FullPermInfo getFullPerm(DefaultPermissionsConfig.Permissions permissions) { + return this.fullFunction.apply(permissions); + } + + public DefaultPermissionsConfig.Permissions.FactionOnlyPermInfo getFactionOnly(DefaultPermissionsConfig.Permissions permissions) { + return this.factionOnlyFunction.apply(permissions); + } + + public Material getMaterial() { + if (this.material == null) { + this.material = MaterialDb.get(this.materialName, Material.STONE); + } + return this.material; + } + + /** + * Case insensitive check for action. + * + * @param check check + * @return permissible + */ + public static PermissibleAction fromString(String check) { + return check == null ? null : map.get(check.toLowerCase()); + } + + public String getDescription() { + return this.desc.toString(); + } + + public String getShortDescription() { + return this.shortDesc.toString(); + } + + @Override + public String toString() { + return name(); + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/perms/PermissionsMapTypeAdapter.java b/Factions/src/main/java/com/massivecraft/factions/perms/PermissionsMapTypeAdapter.java new file mode 100644 index 0000000..0e5c2b8 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/perms/PermissionsMapTypeAdapter.java @@ -0,0 +1,89 @@ +package com.massivecraft.factions.perms; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.util.TL; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + +public class PermissionsMapTypeAdapter implements JsonDeserializer>> { + + @Override + public Map> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { + + try { + JsonObject obj = json.getAsJsonObject(); + if (obj == null) { + return null; + } + + Map> permissionsMap = new ConcurrentHashMap<>(); + + // Top level is Relation + for (Map.Entry entry : obj.entrySet()) { + Permissible permissible = getPermissible(entry.getKey()); + + if (permissible == null) { + continue; + } + + // Second level is the map between action -> access + Map accessMap = new HashMap<>(); + for (Map.Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) { + PermissibleAction permissibleAction = PermissibleAction.fromString(entry2.getKey()); + boolean bool; + try { + bool = entry2.getValue().getAsBoolean(); + } catch (Exception e) { + continue; + } + accessMap.put(permissibleAction, bool); + } + permissionsMap.put(permissible, accessMap); + } + + return permissionsMap; + + } catch (Exception ex) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Error encountered while deserializing a PermissionsMap.", ex); + return null; + } + } + + private Permissible getPermissible(String name) { + // If name is uppercase then it is (probably, no way to completely know) valid if not begin conversion + if (name.equals(name.toUpperCase())) { + if (Role.fromString(name.toUpperCase()) != null) { + return Role.fromString(name.toUpperCase()); + } else if (Relation.fromString(name.toUpperCase()) != null) { + return Relation.fromString(name.toUpperCase()); + } else { + return null; + } + } else { + if(name.equals(TL.ROLE_ALT.toString())){ + return Role.ALT; + } else if (name.equals(TL.ROLE_RECRUIT.toString())) { + return Role.RECRUIT; + } else if (name.equals(TL.ROLE_NORMAL.toString())) { + return Role.NORMAL; + } else if (name.equals(TL.ROLE_MODERATOR.toString())) { + return Role.MODERATOR; + } else { + // If it is explicitly member and its old data then it refers to relation member not role, skip it + if (name.equals("member")) { + return null; + } + return Relation.fromString(name); + } + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/perms/Relation.java b/Factions/src/main/java/com/massivecraft/factions/perms/Relation.java new file mode 100644 index 0000000..df9d1f3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/perms/Relation.java @@ -0,0 +1,158 @@ +package com.massivecraft.factions.perms; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + +import java.util.Collections; +import java.util.Set; + +public enum Relation implements Permissible { + MEMBER(4, TL.RELATION_MEMBER_SINGULAR.toString()), + ALLY(3, TL.RELATION_ALLY_SINGULAR.toString()), + TRUCE(2, TL.RELATION_TRUCE_SINGULAR.toString()), + NEUTRAL(1, TL.RELATION_NEUTRAL_SINGULAR.toString()), + ENEMY(0, TL.RELATION_ENEMY_SINGULAR.toString()); + + public final int value; + public final String nicename; + private Set justMyNameInASet; + + Relation(final int value, final String nicename) { + this.value = value; + this.nicename = nicename; + } + + public static Relation fromString(String s) { + if (s == null) { + return NEUTRAL; + } + if (s.equalsIgnoreCase(MEMBER.nicename)) { + return MEMBER; + } else if (s.equalsIgnoreCase(ALLY.nicename)) { + return ALLY; + } else if (s.equalsIgnoreCase(TRUCE.nicename)) { + return TRUCE; + } else if (s.equalsIgnoreCase(ENEMY.nicename)) { + return ENEMY; + } else { + switch (s.toUpperCase()) { + case "MEMBER": + return MEMBER; + case "ALLY": + return ALLY; + case "TRUCE": + return TRUCE; + case "ENEMY": + return ENEMY; + case "NEUTRAL": + default: // If they somehow mess things up, go back to default behavior. + return NEUTRAL; + } + } + } + + @Override + public String toString() { + return this.nicename; + } + + public String getTranslation() { + try { + return TL.valueOf("RELATION_" + name() + "_SINGULAR").toString(); + } catch (IllegalArgumentException e) { + return toString(); + } + } + + public String getPluralTranslation() { + for (TL t : TL.values()) { + if (t.name().equalsIgnoreCase("RELATION_" + name() + "_PLURAL")) { + return t.toString(); + } + } + return toString(); + } + + public boolean isMember() { + return this == MEMBER; + } + + public boolean isAlly() { + return this == ALLY; + } + + public boolean isTruce() { + return this == TRUCE; + } + + public boolean isNeutral() { + return this == NEUTRAL; + } + + public boolean isEnemy() { + return this == ENEMY; + } + + public boolean isAtLeast(Relation relation) { + return this.value >= relation.value; + } + + public boolean isAtMost(Relation relation) { + return this.value <= relation.value; + } + + public ChatColor getColor() { + switch (this) { + case MEMBER: + return FactionsPlugin.getInstance().conf().colors().relations().getMember(); + case ALLY: + return FactionsPlugin.getInstance().conf().colors().relations().getAlly(); + case NEUTRAL: + return FactionsPlugin.getInstance().conf().colors().relations().getNeutral(); + case TRUCE: + return FactionsPlugin.getInstance().conf().colors().relations().getTruce(); + default: + return FactionsPlugin.getInstance().conf().colors().relations().getEnemy(); + } + } + + public int getMax() { + switch (this) { + case ALLY: + return FactionsPlugin.getInstance().conf().factions().maxRelations().getAlly(); + case ENEMY: + return FactionsPlugin.getInstance().conf().factions().maxRelations().getEnemy(); + case TRUCE: + return FactionsPlugin.getInstance().conf().factions().maxRelations().getTruce(); + case NEUTRAL: + default: + return FactionsPlugin.getInstance().conf().factions().maxRelations().getNeutral(); + } + } + + public double getRelationCost() { + if (isEnemy()) { + return FactionsPlugin.getInstance().conf().economy().getCostEnemy(); + } else if (isAlly()) { + return FactionsPlugin.getInstance().conf().economy().getCostAlly(); + } else if (isTruce()) { + return FactionsPlugin.getInstance().conf().economy().getCostTruce(); + } else { + return FactionsPlugin.getInstance().conf().economy().getCostNeutral(); + } + } + + /** + * Gets this enum name, in lower case, for fastest possible access for + * {@link com.massivecraft.factions.integration.permcontext.Contexts#TERRITORY_RELATION} + * + * @return an immutable set of just this name + */ + public Set getNameInASet() { + if (this.justMyNameInASet == null) { + this.justMyNameInASet = Collections.singleton(this.name().toLowerCase()); + } + return this.justMyNameInASet; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/perms/Role.java b/Factions/src/main/java/com/massivecraft/factions/perms/Role.java new file mode 100644 index 0000000..93bdbee --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/perms/Role.java @@ -0,0 +1,164 @@ +package com.massivecraft.factions.perms; + +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.util.TL; +import org.bukkit.ChatColor; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public enum Role implements Permissible { + ADMIN(4, TL.ROLE_ADMIN), + COLEADER(3, TL.ROLE_COLEADER), + MODERATOR(2, TL.ROLE_MODERATOR), + NORMAL(1, TL.ROLE_NORMAL), + RECRUIT(0, TL.ROLE_RECRUIT), + ALT(-1, TL.ROLE_ALT); + + public final int value; + public final String nicename; + public final TL translation; + private Set roleNamesAtOrBelow; + private Set roleNamesAtOrAbove; + + Role(final int value, final TL translation) { + this.value = value; + this.nicename = translation.toString(); + this.translation = translation; + } + + public boolean isAtLeast(Role role) { + return this.value >= role.value; + } + + public boolean isAtMost(Role role) { + return this.value <= role.value; + } + + public static Role getRelative(Role role, int relative) { + return Role.getByValue(role.value + relative); + } + + public static Role getByValue(int value) { + switch (value) { + case -1: + return ALT; + case 0: + return RECRUIT; + case 1: + return NORMAL; + case 2: + return MODERATOR; + case 3: + return COLEADER; + case 4: + return ADMIN; + } + + return null; + } + + public static Role fromString(String check) { + switch (check.toLowerCase()) { + case "admin": + return ADMIN; + case "coleader": + case "coowner": + return COLEADER; + case "mod": + case "moderator": + return MODERATOR; + case "normal": + case "member": + return NORMAL; + case "recruit": + case "rec": + return RECRUIT; + case "alt": + return ALT; + } + + return null; + } + + @Override + public String toString() { + return this.nicename; + } + + public TL getTranslation() { + return translation; + } + + public String getPrefix() { + if (this == Role.ADMIN) { + return FactionsPlugin.getInstance().conf().factions().prefixes().getAdmin(); + } + + if (this == Role.COLEADER) { + return FactionsPlugin.getInstance().conf().factions().prefixes().getColeader(); + } + + if (this == Role.MODERATOR) { + return FactionsPlugin.getInstance().conf().factions().prefixes().getMod(); + } + + if (this == Role.NORMAL) { + return FactionsPlugin.getInstance().conf().factions().prefixes().getNormal(); + } + + if (this == Role.RECRUIT) { + return FactionsPlugin.getInstance().conf().factions().prefixes().getRecruit(); + } + + if(this == Role.ALT){ + return FactionsPlugin.getInstance().conf().factions().prefixes().getAlt(); + } + + return ""; + } + + @Override + public ChatColor getColor() { + return Relation.MEMBER.getColor(); + } + + /** + * Gets this role name and roles above it in priority. These names are + * not localized and will always match the enum values. + * + * @return an immutable set of role names + */ + public Set getRoleNamesAtOrAbove() { + if (this.roleNamesAtOrAbove == null) { + Set set = new HashSet<>(); + for (Role role : values()) { + if (this.isAtMost(role)) { + set.add(role.name().toLowerCase()); + } + } + this.roleNamesAtOrAbove = Collections.unmodifiableSet(set); + } + return this.roleNamesAtOrAbove; + } + + /** + * Gets this role name and roles below it in priority. These names are + * not localized and will always match the enum values. + * + * @return an immutable set of role names + */ + public Set getRoleNamesAtOrBelow() { + if (this.roleNamesAtOrBelow == null) { + Set set = new HashSet<>(); + for (Role role : values()) { + if (this.isAtLeast(role)) { + set.add(role.name().toLowerCase()); + } + } + this.roleNamesAtOrBelow = Collections.unmodifiableSet(set); + } + return this.roleNamesAtOrBelow; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java b/Factions/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java new file mode 100644 index 0000000..f6b20e3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java @@ -0,0 +1,233 @@ +package com.massivecraft.factions.scoreboards; + +import org.bukkit.ChatColor; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class BufferedObjective { + private static final Method addEntryMethod; + private static final int MAX_LINE_LENGTH; + private static final Pattern PATTERN = Pattern.compile("(\u00A7[0-9a-fk-r])|(.)"); + + private final Scoreboard scoreboard; + private final String baseName; + + private Objective current; + private List currentTeams = new ArrayList<>(); + private String title; + private DisplaySlot displaySlot; + + private int objPtr; + private int teamPtr; + private boolean requiresUpdate = false; + + private final Map contents = new HashMap<>(); + + static { + // Check for long line support. + // We require use of Spigot's `addEntry(String)` method on + // Teams, as adding OfflinePlayers to a team is far too slow. + + Method addEntryMethodLookup = null; + try { + addEntryMethodLookup = Team.class.getMethod("addEntry", String.class); + } catch (NoSuchMethodException ignored) { + } + + addEntryMethod = addEntryMethodLookup; + + if (addEntryMethod != null) { + MAX_LINE_LENGTH = 48; + } else { + MAX_LINE_LENGTH = 16; + } + } + + public BufferedObjective(Scoreboard scoreboard) { + this.scoreboard = scoreboard; + this.baseName = createBaseName(); + + current = scoreboard.registerNewObjective(getNextObjectiveName(), "dummy"); + } + + private String createBaseName() { + Random random = new Random(); + StringBuilder builder = new StringBuilder(); + while (builder.length() < 14) { + builder.append(Integer.toHexString(random.nextInt())); + } + return builder.toString().substring(0, 14); + } + + public void setTitle(String title) { + if (this.title == null || !this.title.equals(title)) { + this.title = title; + requiresUpdate = true; + } + } + + public void setDisplaySlot(DisplaySlot slot) { + this.displaySlot = slot; + current.setDisplaySlot(slot); + } + + public void setAllLines(List lines) { + if (lines.size() != contents.size()) { + contents.clear(); + } + for (int i = 0; i < lines.size(); i++) { + setLine(lines.size() - i, lines.get(i)); + } + } + + public void setLine(int lineNumber, String content) { + if (content.length() > MAX_LINE_LENGTH) { + content = content.substring(0, MAX_LINE_LENGTH); + } + content = ChatColor.translateAlternateColorCodes('&', content); + + if (contents.get(lineNumber) == null || !contents.get(lineNumber).equals(content)) { + contents.put(lineNumber, content); + requiresUpdate = true; + } + } + + // Hides the objective from the display slot until flip() is called + public void hide() { + if (displaySlot != null) { + scoreboard.clearSlot(displaySlot); + } + } + + public void flip() { + if (!requiresUpdate) { + return; + } + requiresUpdate = false; + + Objective buffer = scoreboard.registerNewObjective(getNextObjectiveName(), "dummy"); + buffer.setDisplayName(title); + + List bufferTeams = new ArrayList<>(); + + for (Map.Entry entry : contents.entrySet()) { + if (entry.getValue().length() > 16) { + Team team = scoreboard.registerNewTeam(getNextTeamName()); + bufferTeams.add(team); + + String name, prefix = null, suffix = null; + + String value = entry.getValue(); + if (value.length() > 16) { + String[] arrImAPirate = new String[3]; + Matcher matcherrr = PATTERN.matcher(value); + StringBuilder builderrr = new StringBuilder(); + int sCURvy = 0; + char currrentColorrr = 'r'; + char currrentFormat = 'r'; + while (sCURvy < 3 && matcherrr.find()) { + String tharSheBlows = matcherrr.group(); + boolean hoist = false; + if (tharSheBlows.length() == 1) { + builderrr.append(tharSheBlows); + if (builderrr.length() == 16) { + hoist = true; + } + } else { + char c = tharSheBlows.charAt(1); + if (c >= 'k' && c <= 'r') { // format! + currrentFormat = c; + if (c == 'r') { + currrentColorrr = 'r'; + } + } else { + currrentColorrr = c; + currrentFormat = 'r'; + } + if (builderrr.length() < 14) { + builderrr.append(tharSheBlows); + } else { + hoist = true; + } + } + if (hoist) { + arrImAPirate[sCURvy++] = builderrr.toString(); + builderrr = new StringBuilder(); + if (currrentColorrr != 'r') { + builderrr.append('\u00A7').append(currrentColorrr); + } + if (currrentFormat != 'r') { + builderrr.append('\u00A7').append(currrentFormat); + } + } + } + if (sCURvy < 3 && builderrr.length() > 0) { + arrImAPirate[sCURvy] = builderrr.toString(); + } + if (arrImAPirate[2] == null) { + name = arrImAPirate[0]; + suffix = arrImAPirate[1]; + } else { + prefix = arrImAPirate[0]; + name = arrImAPirate[1]; + suffix = arrImAPirate[2]; + } + } else { + name = value; + } + + if (prefix != null) { + team.setPrefix(prefix); + } + if (suffix != null) { + team.setSuffix(suffix); + } + + + try { + addEntryMethod.invoke(team, name); + } catch (ReflectiveOperationException ignored) { + } + buffer.getScore(name).setScore(entry.getKey()); + } else { + buffer.getScore(entry.getValue()).setScore(entry.getKey()); + } + } + + if (displaySlot != null) { + buffer.setDisplaySlot(displaySlot); + } + + // Unregister _ALL_ the old things + current.unregister(); + + Iterator it = currentTeams.iterator(); + while (it.hasNext()) { + it.next().unregister(); + it.remove(); + } + + current = buffer; + currentTeams = bufferTeams; + } + + private String getNextObjectiveName() { + return baseName + "_" + ((objPtr++) % 2); + } + + private String getNextTeamName() { + return baseName.substring(0, 10) + "_" + ((teamPtr++) % 999999); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/scoreboards/FScoreboard.java b/Factions/src/main/java/com/massivecraft/factions/scoreboards/FScoreboard.java new file mode 100644 index 0000000..2d139ae --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/scoreboards/FScoreboard.java @@ -0,0 +1,152 @@ +package com.massivecraft.factions.scoreboards; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Scoreboard; + +import java.util.HashMap; +import java.util.Map; + +public class FScoreboard { + private static final Map fscoreboards = new HashMap<>(); + + private final Scoreboard scoreboard; + private final FPlayer fplayer; + private final BufferedObjective bufferedObjective; + private FSidebarProvider defaultProvider; + private FSidebarProvider temporaryProvider; + private boolean removed = false; + + // Glowstone doesn't support scoreboards. + // All references to this and related workarounds can be safely + // removed when scoreboards are supported. + public static boolean isSupportedByServer() { + return Bukkit.getScoreboardManager() != null; + } + + public static void init(FPlayer fplayer) { + FScoreboard fboard = new FScoreboard(fplayer); + fscoreboards.put(fplayer, fboard); + + if (fplayer.hasFaction()) { + FTeamWrapper.applyUpdates(fplayer.getFaction()); + } + FTeamWrapper.track(fboard); + } + + public static void remove(FPlayer fplayer, Player player) { + FScoreboard fboard = fscoreboards.remove(fplayer); + + if (fboard != null) { + if (fboard.scoreboard == player.getScoreboard()) { // No equals method implemented, so may as well skip a nullcheck + player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard()); + } + fboard.removed = true; + FTeamWrapper.untrack(fboard); + } + } + + public static FScoreboard get(FPlayer fplayer) { + return fscoreboards.get(fplayer); + } + + public static FScoreboard get(Player player) { + return fscoreboards.get(FPlayers.getInstance().getByPlayer(player)); + } + + private FScoreboard(FPlayer fplayer) { + this.fplayer = fplayer; + + if (isSupportedByServer()) { + this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); + this.bufferedObjective = new BufferedObjective(scoreboard); + + fplayer.getPlayer().setScoreboard(scoreboard); + } else { + this.scoreboard = null; + this.bufferedObjective = null; + } + } + + protected FPlayer getFPlayer() { + return fplayer; + } + + protected Scoreboard getScoreboard() { + return scoreboard; + } + + public void setSidebarVisibility(boolean visible) { + if (!isSupportedByServer()) { + return; + } + + bufferedObjective.setDisplaySlot(visible ? DisplaySlot.SIDEBAR : null); + } + + public void setDefaultSidebar(final FSidebarProvider provider) { + if (!isSupportedByServer()) { + return; + } + + defaultProvider = provider; + if (temporaryProvider == null) { + // We have no temporary provider; update the BufferedObjective! + updateObjective(); + } + + new BukkitRunnable() { + @Override + public void run() { + if (removed || provider != defaultProvider) { + cancel(); + return; + } + + if (temporaryProvider == null) { + updateObjective(); + } + } + }.runTaskTimer(FactionsPlugin.getInstance(), 20, 20); + } + + public void setTemporarySidebar(final FSidebarProvider provider) { + if (!isSupportedByServer()) { + return; + } + + temporaryProvider = provider; + updateObjective(); + + new BukkitRunnable() { + @Override + public void run() { + if (removed) { + return; + } + + if (temporaryProvider == provider) { + temporaryProvider = null; + updateObjective(); + } + } + }.runTaskLater(FactionsPlugin.getInstance(), FactionsPlugin.getInstance().conf().scoreboard().info().getExpiration() * 20); + } + + private void updateObjective() { + FSidebarProvider provider = temporaryProvider != null ? temporaryProvider : defaultProvider; + + if (provider == null) { + bufferedObjective.hide(); + } else { + bufferedObjective.setTitle(provider.getTitle(fplayer)); + bufferedObjective.setAllLines(provider.getLines(fplayer)); + bufferedObjective.flip(); + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java b/Factions/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java new file mode 100644 index 0000000..39e41f4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java @@ -0,0 +1,41 @@ +package com.massivecraft.factions.scoreboards; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.tag.Tag; +import com.massivecraft.factions.util.TL; + +import java.util.List; + +public abstract class FSidebarProvider { + + public abstract String getTitle(FPlayer fplayer); + + public abstract List getLines(FPlayer fplayer); + + public String replaceTags(FPlayer fPlayer, String s) { + s = Tag.parsePlaceholders(fPlayer.getPlayer(), s); + + return qualityAssure(Tag.parsePlain(fPlayer, s)); + } + + public String replaceTags(Faction faction, FPlayer fPlayer, String s) { + // Run through Placeholder API first + s = Tag.parsePlaceholders(fPlayer.getPlayer(), s); + + return qualityAssure(Tag.parsePlain(faction, fPlayer, s)); + } + + private String qualityAssure(String line) { + if (line.contains("{notFrozen}") || line.contains("{notPermanent}")) { + return "n/a"; // we dont support support these error variables in scoreboards + } + if (line.contains("{ig}")) { + // since you can't really fit a whole "Faction Home: world, x, y, z" on one line + // we assume it's broken up into two lines, so returning our tl will suffice. + return TL.COMMAND_SHOW_NOHOME.toString(); + } + return FactionsPlugin.getInstance().txt().parse(line); // finally add color :) + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java b/Factions/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java new file mode 100644 index 0000000..a9a7b33 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java @@ -0,0 +1,237 @@ +package com.massivecraft.factions.scoreboards; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.config.file.MainConfig; +import com.massivecraft.factions.tag.Tag; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class FTeamWrapper { + private static final Map wrappers = new HashMap<>(); + private static final List tracking = new ArrayList<>(); + private static int factionTeamPtr; + private static final Set updating = new HashSet<>(); + + private final Map teams = new HashMap<>(); + private final String teamName; + private final Faction faction; + private final Set members = new HashSet<>(); + + public static void applyUpdatesLater(final Faction faction) { + if (!FScoreboard.isSupportedByServer()) { + return; + } + + if (faction.isWilderness()) { + return; + } + + if (!FactionsPlugin.getInstance().conf().scoreboard().constant().isPrefixes() && !FactionsPlugin.getInstance().conf().scoreboard().constant().isSuffixes()) { + return; + } + + + if (updating.add(faction)) { + new BukkitRunnable() { + @Override + public void run() { + updating.remove(faction); + applyUpdates(faction); + } + }.runTask(FactionsPlugin.getInstance()); + } + } + + public static void applyUpdates(Faction faction) { + if (!FScoreboard.isSupportedByServer()) { + return; + } + + if (faction.isWilderness()) { + return; + } + + if (!FactionsPlugin.getInstance().conf().scoreboard().constant().isPrefixes() && !FactionsPlugin.getInstance().conf().scoreboard().constant().isSuffixes()) { + return; + } + + if (updating.contains(faction)) { + // Faction will be updated soon. + return; + } + + FTeamWrapper wrapper = wrappers.get(faction); + Set factionMembers = faction.getFPlayers(); + + if (wrapper != null && Factions.getInstance().getFactionById(faction.getId()) == null) { + // Faction was disbanded + wrapper.unregister(); + wrappers.remove(faction); + return; + } + + if (wrapper == null) { + wrapper = new FTeamWrapper(faction); + wrappers.put(faction, wrapper); + } + + for (OfflinePlayer player : wrapper.getPlayers()) { + if (!player.isOnline() || !factionMembers.contains(FPlayers.getInstance().getByOfflinePlayer(player))) { + // Player is offline or no longer in faction + wrapper.removePlayer(player); + } + } + + for (FPlayer fmember : factionMembers) { + if (!fmember.isOnline()) { + continue; + } + + // Scoreboard might not have player; add him/her + wrapper.addPlayer(fmember.getPlayer()); + } + + wrapper.updatePrefixesAndSuffixes(); + } + + public static void updatePrefixes(Faction faction) { + if (!FScoreboard.isSupportedByServer()) { + return; + } + + if (!wrappers.containsKey(faction)) { + applyUpdates(faction); + } else { + wrappers.get(faction).updatePrefixesAndSuffixes(); + } + } + + protected static void track(FScoreboard fboard) { + if (!FScoreboard.isSupportedByServer()) { + return; + } + tracking.add(fboard); + for (FTeamWrapper wrapper : wrappers.values()) { + wrapper.add(fboard); + } + } + + protected static void untrack(FScoreboard fboard) { + if (!FScoreboard.isSupportedByServer()) { + return; + } + tracking.remove(fboard); + for (FTeamWrapper wrapper : wrappers.values()) { + wrapper.remove(fboard); + } + } + + + private FTeamWrapper(Faction faction) { + this.teamName = "faction_" + (factionTeamPtr++); + this.faction = faction; + + for (FScoreboard fboard : tracking) { + add(fboard); + } + } + + private void add(FScoreboard fboard) { + Scoreboard board = fboard.getScoreboard(); + Team team = board.registerNewTeam(teamName); + teams.put(fboard, team); + + for (OfflinePlayer player : getPlayers()) { + team.addPlayer(player); + } + + updatePrefixAndSuffix(fboard); + } + + private void remove(FScoreboard fboard) { + teams.remove(fboard).unregister(); + } + + private void updatePrefixesAndSuffixes() { + if (FactionsPlugin.getInstance().conf().scoreboard().constant().isPrefixes() || FactionsPlugin.getInstance().conf().scoreboard().constant().isSuffixes()) { + for (FScoreboard fboard : teams.keySet()) { + updatePrefixAndSuffix(fboard); + } + } + } + + private void updatePrefixAndSuffix(FScoreboard fboard) { + MainConfig.Scoreboard.Constant conf = FactionsPlugin.getInstance().conf().scoreboard().constant(); + if (conf.isPrefixes()) { + Team team = teams.get(fboard); + String prefix = this.apply(conf.getPrefixTemplate(), fboard.getFPlayer(), conf.getPrefixLength()); + + if (!prefix.equals(team.getPrefix())) { + team.setPrefix(prefix); + } + } + if (conf.isSuffixes()) { + Team team = teams.get(fboard); + String suffix = this.apply(conf.getSuffixTemplate(), fboard.getFPlayer(), conf.getSuffixLength()); + + if (!suffix.equals(team.getSuffix())) { + team.setSuffix(suffix); + } + } + } + + private String apply(String prefixOrSuffix, FPlayer fplayer, int maxLength) { + prefixOrSuffix = Tag.parsePlaceholders(fplayer.getPlayer(), prefixOrSuffix); + prefixOrSuffix = prefixOrSuffix.replace("{relationcolor}", faction.getRelationTo(fplayer).getColor().toString()); + int remaining = Math.min("{faction}".length() + maxLength - prefixOrSuffix.length(), faction.getTag().length()); + prefixOrSuffix = prefixOrSuffix.replace("{faction}", remaining > 0 ? faction.getTag().substring(0, remaining) : ""); + prefixOrSuffix = Tag.parsePlain(fplayer, prefixOrSuffix); + prefixOrSuffix = ChatColor.translateAlternateColorCodes('&', prefixOrSuffix); + + if (prefixOrSuffix.length() > maxLength) { + prefixOrSuffix = prefixOrSuffix.substring(0, maxLength); + } + return prefixOrSuffix; + } + + private void addPlayer(OfflinePlayer player) { + if (members.add(player)) { + for (Team team : teams.values()) { + team.addPlayer(player); + } + } + } + + private void removePlayer(OfflinePlayer player) { + if (members.remove(player)) { + for (Team team : teams.values()) { + team.removePlayer(player); + } + } + } + + private Set getPlayers() { + return new HashSet<>(this.members); + } + + private void unregister() { + for (Team team : teams.values()) { + team.unregister(); + } + teams.clear(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java b/Factions/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java new file mode 100644 index 0000000..5d3eb93 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java @@ -0,0 +1,52 @@ +package com.massivecraft.factions.scoreboards.sidebar; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.scoreboards.FSidebarProvider; + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +public class FDefaultSidebar extends FSidebarProvider { + + @Override + public String getTitle(FPlayer fplayer) { + if (FactionsPlugin.getInstance().conf().scoreboard().constant().isFactionlessEnabled() && !fplayer.hasFaction()) { + return replaceTags(fplayer, FactionsPlugin.getInstance().conf().scoreboard().constant().getFactionlessTitle()); + } + return replaceTags(fplayer, FactionsPlugin.getInstance().conf().scoreboard().constant().getTitle()); + } + + @Override + public List getLines(FPlayer fplayer) { + if (FactionsPlugin.getInstance().conf().scoreboard().constant().isFactionlessEnabled() && !fplayer.hasFaction()) { + return getOutput(fplayer, FactionsPlugin.getInstance().conf().scoreboard().constant().getFactionlessContent()); + } + return getOutput(fplayer, FactionsPlugin.getInstance().conf().scoreboard().constant().getContent()); + } + + public List getOutput(FPlayer fplayer, List lines) { + if (lines == null || lines.isEmpty()) { + return new ArrayList<>(); + } + + lines = new ArrayList<>(lines); + + ListIterator it = lines.listIterator(); + while (it.hasNext()) { + String next = it.next(); + if (next == null) { + it.remove(); + continue; + } + String replaced = replaceTags(fplayer, next); + if (replaced == null) { + it.remove(); + } else { + it.set(replaced); + } + } + return lines; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java b/Factions/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java new file mode 100644 index 0000000..a4b633e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java @@ -0,0 +1,44 @@ +package com.massivecraft.factions.scoreboards.sidebar; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.scoreboards.FSidebarProvider; + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +public class FInfoSidebar extends FSidebarProvider { + private final Faction faction; + + public FInfoSidebar(Faction faction) { + this.faction = faction; + } + + @Override + public String getTitle(FPlayer fplayer) { + return replaceTags(this.faction, fplayer, FactionsPlugin.getInstance().conf().scoreboard().info().getTitle()); + } + + @Override + public List getLines(FPlayer fplayer) { + List lines = new ArrayList<>(FactionsPlugin.getInstance().conf().scoreboard().info().getContent()); + + ListIterator it = lines.listIterator(); + while (it.hasNext()) { + String next = it.next(); + if (next == null) { + it.remove(); + continue; + } + String replaced = replaceTags(faction, fplayer, next); + if (replaced == null) { + it.remove(); + } else { + it.set(replaced); + } + } + return lines; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/struct/BanInfo.java b/Factions/src/main/java/com/massivecraft/factions/struct/BanInfo.java new file mode 100644 index 0000000..365d7a3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/struct/BanInfo.java @@ -0,0 +1,42 @@ +package com.massivecraft.factions.struct; + +public class BanInfo { + + // FPlayer IDs + private final String banner; + private final String banned; + private final long time; + + public BanInfo(String banner, String banned, long time) { + this.banner = banner; + this.banned = banned; + this.time = time; + } + + /** + * Get the FPlayer ID of the player who issued the ban. + * + * @return FPlayer ID. + */ + public String getBanner() { + return this.banner; + } + + /** + * Get the FPlayer ID of the player who got banned. + * + * @return FPlayer ID. + */ + public String getBanned() { + return banned; + } + + /** + * Get the server time when the ban was issued. + * + * @return system timestamp. + */ + public long getTime() { + return time; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/struct/ChatMode.java b/Factions/src/main/java/com/massivecraft/factions/struct/ChatMode.java new file mode 100644 index 0000000..0d31ca8 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/struct/ChatMode.java @@ -0,0 +1,47 @@ +package com.massivecraft.factions.struct; + +import com.massivecraft.factions.util.TL; + +public enum ChatMode { + MOD(4, TL.CHAT_MOD), + FACTION(3, TL.CHAT_FACTION), + ALLIANCE(2, TL.CHAT_ALLIANCE), + TRUCE(1, TL.CHAT_TRUCE), + PUBLIC(0, TL.CHAT_PUBLIC); + + public final int value; + public final TL nicename; + + ChatMode(final int value, final TL nicename) { + this.value = value; + this.nicename = nicename; + } + + public boolean isAtLeast(ChatMode role) { + return this.value >= role.value; + } + + public boolean isAtMost(ChatMode role) { + return this.value <= role.value; + } + + @Override + public String toString() { + return this.nicename.toString(); + } + + public ChatMode getNext() { + switch (this) { + case PUBLIC: + return TRUCE; + case TRUCE: + return ALLIANCE; + case ALLIANCE: + return FACTION; + case FACTION: + return MOD; + default: + return PUBLIC; + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/struct/Permission.java b/Factions/src/main/java/com/massivecraft/factions/struct/Permission.java new file mode 100644 index 0000000..c1805f8 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/struct/Permission.java @@ -0,0 +1,149 @@ +package com.massivecraft.factions.struct; + +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.command.CommandSender; + +public enum Permission { + MANAGE_SAFE_ZONE("managesafezone"), + MANAGE_WAR_ZONE("managewarzone"), + OWNERSHIP_BYPASS("ownershipbypass"), + BYPASS_REMOVAL("essentials.bypassremoval"), + ADMIN("admin"), + ADMIN_ANY("admin.any"), + AHOME("ahome"), + ALTS("alts"), + ANNOUNCE("announce"), + AUTOCLAIM("autoclaim"), + AUTO_LEAVE_BYPASS("autoleavebypass"), + BAN("ban"), + BYPASS("bypass"), + CHAT("chat"), + CHATSPY("chatspy"), + CLAIM("claim"), + CLAIMAT("claimat"), + CLAIM_FILL("claim.fill"), + CLAIM_LINE("claim.line"), + CLAIM_CORNER("claim.corner"), + CLAIM_RADIUS("claim.radius"), + CLAIM_SEEALL("claim.seeall"), + COLEADER("coleader"), + COLEADER_ANY("coleader.any"), + COORDS("coords"), + CREATE("create"), + DEFAULTRANK("defaultrank"), + DEINVITE("deinvite"), + DELHOME("delhome"), + DESCRIPTION("description"), + DISBAND("disband"), + DISBAND_ANY("disband.any"), + DTR("dtr"), + DTR_ANY("dtr.any"), + FLY("fly"), + FLY_AUTO("fly.auto"), + FLY_WILDERNESS("fly.wilderness"), + FLY_SAFEZONE("fly.safezone"), + FLY_WARZONE("fly.warzone"), + FLY_TRAILS("fly.trails"), + FLY_ANY("fly.any"), + HELP("help"), + HOME("home"), + INVITE("invite"), + JOIN("join"), + JOIN_ANY("join.any"), + JOIN_OTHERS("join.others"), + KICK("kick"), + KICK_ANY("kick.any"), + LEAVE("leave"), + LIST("list"), + LISTCLAIMS("listclaims"), + LISTCLAIMS_OTHER("listclaims.other"), + LOCK("lock"), + MAP("map"), + MAPHEIGHT("mapheight"), + MISSIONS("missions"), + MOD("mod"), + MOD_ANY("mod.any"), + MODIFY_DTR("modifydtr"), + MODIFY_POWER("modifypower"), + MONEY_BALANCE("money.balance"), + MONEY_BALANCE_ANY("money.balance.any"), + MONEY_DEPOSIT("money.deposit"), + MONEY_WITHDRAW("money.withdraw"), + MONEY_WITHDRAW_ANY("money.withdraw.any"), + MONEY_F2F("money.f2f"), + MONEY_F2P("money.f2p"), + MONEY_P2F("money.p2f"), + MONITOR_LOGINS("monitorlogins"), + NO_BOOM("noboom"), + OPEN("open"), + OWNER("owner"), + OWNERLIST("ownerlist"), + ROSTER_CONTROL("roster"), + SET_PEACEFUL("setpeaceful"), + SET_PERMANENT("setpermanent"), + SET_PERMANENTPOWER("setpermanentpower"), + SHOW_INVITES("showinvites"), + STRIKE_MANAGE("strike.manage"), + STRIKE_VIEW("strike.view"), + PERMISSIONS("permissions"), + POWERBOOST("powerboost"), + POWER("power"), + POWER_ANY("power.any"), + PROMOTE("promote"), + RELATION("relation"), + RELOAD("reload"), + SAVE("save"), + SETHOME("sethome"), + SETHOME_ANY("sethome.any"), + SHOW("show"), + SHOW_BYPASS_EXEMPT("show.bypassexempt"), + SOTW("sotw"), + STATUS("status"), + STEALTH("stealth"), + STUCK("stuck"), + TAG("tag"), + TITLE("title"), + TITLE_COLOR("title.color"), + TNT_ADMIN("tnt.admin"), + TNT_INFO("tnt.info"), + TNT_DEPOSIT("tnt.deposit"), + TNT_WITHDRAW("tnt.withdraw"), + TNT_FILL("tnt.fill"), + TNT_SIPHON("tnt.siphon"), + TOGGLE_ALLIANCE_CHAT("togglealliancechat"), + UNCLAIM("unclaim"), + UNCLAIM_ALL("unclaimall"), + UPGRADE("upgrade"), + VERSION("version"), + SCOREBOARD("scoreboard"), + SEECHUNK("seechunk"), + SETWARP("setwarp"), + SETPAYPAL("setpaypal"), + SEEPAYPAL("seepaypal"), + TOP("top"), + VAULT("vault"), + SETMAXVAULTS("setmaxvaults"), + NEAR("near"), + WARP("warp"), + UPDATES("updates"), + DEBUG("debug"); + + public final String node; + + Permission(final String node) { + this.node = "factions." + node; + } + + @Override + public String toString() { + return this.node; + } + + public boolean has(CommandSender sender, boolean informSenderIfNot) { + return FactionsPlugin.getInstance().getPermUtil().has(sender, this.node, informSenderIfNot); + } + + public boolean has(CommandSender sender) { + return has(sender, false); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/struct/RallyWaypoint.java b/Factions/src/main/java/com/massivecraft/factions/struct/RallyWaypoint.java new file mode 100644 index 0000000..ab20f9d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/struct/RallyWaypoint.java @@ -0,0 +1,25 @@ +package com.massivecraft.factions.struct; + +import com.lunarclient.bukkitapi.object.LCWaypoint; +import org.bukkit.entity.Player; + +import java.util.List; + +public class RallyWaypoint { + + private final LCWaypoint lcWaypoint; + private final List playersSentTo; + + public RallyWaypoint(LCWaypoint lcWaypoint, List playersSentTo) { + this.lcWaypoint = lcWaypoint; + this.playersSentTo = playersSentTo; + } + + public List getPlayersSentTo() { + return playersSentTo; + } + + public LCWaypoint getLcWaypoint() { + return lcWaypoint; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/tag/FactionTag.java b/Factions/src/main/java/com/massivecraft/factions/tag/FactionTag.java new file mode 100644 index 0000000..e2e91fc --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/tag/FactionTag.java @@ -0,0 +1,171 @@ +package com.massivecraft.factions.tag; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.landraidcontrol.DTRControl; +import com.massivecraft.factions.landraidcontrol.PowerControl; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.util.TL; +import org.apache.commons.lang.time.DurationFormatUtils; + +import java.util.function.BiFunction; +import java.util.function.Function; + +public enum FactionTag implements Tag { + HOME_X("x", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : Tag.isMinimalShow() ? null : "{ig}"), + HOME_Y("y", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : Tag.isMinimalShow() ? null : "{ig}"), + HOME_Z("z", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : Tag.isMinimalShow() ? null : "{ig}"), + CHUNKS("chunks", (fac) -> String.valueOf(fac.getLandRounded())), + WARPS("warps", (fac) -> String.valueOf(fac.getWarps().size())), + HEADER("header", (fac, fp) -> FactionsPlugin.getInstance().txt().titleize(fac.getTag(fp))), + POWER("power", (fac) -> String.valueOf(fac.getPowerRounded())), + MAX_POWER("maxPower", (fac) -> String.valueOf(fac.getPowerMaxRounded())), + POWER_BOOST("power-boost", (fac) -> { + double powerBoost = fac.getPowerBoost(); + return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); + }), + LEADER("leader", (fac) -> { + FPlayer fAdmin = fac.getFPlayerAdmin(); + return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); + }), + JOINING("joining", (fac) -> (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString())), + FACTION("faction", (Function) Faction::getTag), + FACTION_RELATION_COLOR("faction-relation-color", (fac, fp) -> fp == null ? "" : fp.getColorTo(fac).toString()), + HOME_WORLD("world", (fac) -> fac.hasHome() ? fac.getHome().getWorld().getName() : Tag.isMinimalShow() ? null : "{ig}"), + RAIDABLE("raidable", (fac) -> { + boolean raid = FactionsPlugin.getInstance().getLandRaidControl().isRaidable(fac); + return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); + }), + DTR("dtr", (fac) -> { + if (FactionsPlugin.getInstance().getLandRaidControl() instanceof PowerControl) { + int dtr = fac.getLandRounded() >= fac.getPowerRounded() ? 0 : (int) Math.ceil(((double) (fac.getPowerRounded() - fac.getLandRounded())) / FactionsPlugin.getInstance().conf().factions().landRaidControl().power().getLossPerDeath()); + return TL.COMMAND_SHOW_DEATHS_TIL_RAIDABLE.format(dtr); + } else { + return DTRControl.round(fac.getDTR()); + } + }), + MAX_DTR("max-dtr", (fac) -> { + if (FactionsPlugin.getInstance().getLandRaidControl() instanceof DTRControl) { + return DTRControl.round(((DTRControl) FactionsPlugin.getInstance().getLandRaidControl()).getMaxDTR(fac)); + } + return Tag.isMinimalShow() ? null : "{ig}"; + }), + DTR_FROZEN("dtr-frozen-status", (fac -> TL.DTR_FROZEN_STATUS_MESSAGE.format(fac.isFrozenDTR() ? TL.DTR_FROZEN_STATUS_TRUE.toString() : TL.DTR_FROZEN_STATUS_FALSE.toString()))), + DTR_FROZEN_TIME("dtr-frozen-time", (fac -> TL.DTR_FROZEN_TIME_MESSAGE.format(fac.isFrozenDTR() ? + DurationFormatUtils.formatDuration(fac.getFrozenDTRUntilTime() - System.currentTimeMillis(), FactionsPlugin.getInstance().conf().factions().landRaidControl().dtr().getFreezeTimeFormat()) : + TL.DTR_FROZEN_TIME_NOTFROZEN.toString()))), + MAX_CHUNKS("max-chunks", (fac -> String.valueOf(FactionsPlugin.getInstance().getLandRaidControl().getLandLimit(fac)))), + PEACEFUL("peaceful", (fac) -> fac.isPeaceful() ? FactionsPlugin.getInstance().conf().colors().relations().getPeaceful() + TL.COMMAND_SHOW_PEACEFUL.toString() : ""), + PERMANENT("permanent", (fac) -> fac.isPermanent() ? "permanent" : "{notPermanent}"), // no braces needed + LAND_VALUE("land-value", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("value")), + DESCRIPTION("description", Faction::getDescription), + CREATE_DATE("create-date", (fac) -> TL.sdf.format(fac.getFoundedDate())), + LAND_REFUND("land-refund", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("refund")), + BANK_BALANCE("faction-balance", (fac) -> { + if (Econ.shouldBeUsed()) { + return FactionsPlugin.getInstance().conf().economy().isBankEnabled() ? Econ.moneyString(Econ.getBalance(fac)) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); + } + return Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); + }), + TNT_BALANCE("tnt-balance", (fac) -> { + if (FactionsPlugin.getInstance().conf().commands().tnt().isEnable()) { + return String.valueOf(fac.getTNTBank()); + } + return Tag.isMinimalShow() ? null : ""; + }), + TNT_MAX("tnt-max-balance", (fac) -> { + if (FactionsPlugin.getInstance().conf().commands().tnt().isEnable()) { + return String.valueOf(FactionsPlugin.getInstance().conf().commands().tnt().getMaxStorage()); + } + return Tag.isMinimalShow() ? null : ""; + }), + ALLIES_COUNT("allies", (fac) -> String.valueOf(fac.getRelationCount(Relation.ALLY))), + ENEMIES_COUNT("enemies", (fac) -> String.valueOf(fac.getRelationCount(Relation.ENEMY))), + TRUCES_COUNT("truces", (fac) -> String.valueOf(fac.getRelationCount(Relation.TRUCE))), + ONLINE_COUNT("online", (fac, fp) -> { + if (fp != null && fp.isOnline()) { + return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size()); + } else { + // Only console should ever get here. + return String.valueOf(fac.getFPlayersWhereOnline(true).size()); + } + }), + ALT_COUNT("alts", (fac, fp) -> { + return String.valueOf(fac.getFPlayersWhereRole(Role.ALT).size()); + }), + OFFLINE_COUNT("offline", (fac, fp) -> { + if (fp != null && fp.isOnline()) { + return String.valueOf(fac.getFPlayers().size() - fac.getFPlayersWhereOnline(true, fp).size()); + } else { + // Only console should ever get here. + return String.valueOf(fac.getFPlayersWhereOnline(false).size()); + } + }), + FACTION_SIZE("members", (fac) -> String.valueOf(fac.getFPlayers().size())), + FACTION_KILLS("faction-kills", (fac) -> String.valueOf(fac.getKills())), + FACTION_DEATHS("faction-deaths", (fac) -> String.valueOf(fac.getDeaths())), + FACTION_BANCOUNT("faction-bancount", (fac) -> String.valueOf(fac.getBannedPlayers().size())), + STRIKES("strikes", (fac) -> fac.getStrikes().size() + ""), + ; + + private final String tag; + private final BiFunction biFunction; + private final Function function; + + public static String parse(String text, Faction faction, FPlayer player) { + for (FactionTag tag : FactionTag.values()) { + text = tag.replace(text, faction, player); + } + return text; + } + + public static String parse(String text, Faction faction) { + for (FactionTag tag : FactionTag.values()) { + text = tag.replace(text, faction); + } + return text; + } + + FactionTag(String tag, BiFunction function) { + this(tag, null, function); + } + + FactionTag(String tag, Function function) { + this(tag, function, null); + } + + FactionTag(String tag, Function function, BiFunction biFunction) { + if (tag.equalsIgnoreCase("permanent")) { + this.tag = tag; + } else { + this.tag = '{' + tag + '}'; + } + this.biFunction = biFunction; + this.function = function; + } + + @Override + public String getTag() { + return this.tag; + } + + @Override + public boolean foundInString(String test) { + return test != null && test.contains(this.tag); + } + + public String replace(String text, Faction faction, FPlayer player) { + if (!this.foundInString(text)) { + return text; + } + String result = this.function == null ? this.biFunction.apply(faction, player) : this.function.apply(faction); + return result == null ? null : text.replace(this.tag, result); + } + + public String replace(String text, Faction faction) { + return this.replace(text, faction, null); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/tag/FancyTag.java b/Factions/src/main/java/com/massivecraft/factions/tag/FancyTag.java new file mode 100644 index 0000000..1a02d08 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/tag/FancyTag.java @@ -0,0 +1,205 @@ +package com.massivecraft.factions.tag; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.util.MiscUtil; +import com.massivecraft.factions.util.QuadFunction; +import mkremins.fanciful.FancyMessage; +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public enum FancyTag implements Tag { + ALLIES_LIST("allies-list", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ALLY)), + ENEMIES_LIST("enemies-list", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ENEMY)), + TRUCES_LIST("truces-list", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.TRUCE)), + ONLINE_LIST("online-list", (target, fme, prefix, gm) -> { + List fancyMessages = new ArrayList<>(); + FancyMessage currentOnline = FactionsPlugin.getInstance().txt().parseFancy(prefix); + boolean firstOnline = true; + for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) { + if(p.getRole() == Role.ALT)continue; + if (fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) { + continue; // skip + } + String name = p.getNameAndTitle(); + currentOnline.then(firstOnline ? name : ", " + name); + currentOnline.tooltip(tipPlayer(p, gm)).color(fme.getColorTo(p)); + firstOnline = false; + if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOnline); + currentOnline = new FancyMessage(""); + } + } + fancyMessages.add(currentOnline); + return firstOnline && Tag.isMinimalShow() ? null : fancyMessages; + }), + ALT_LIST("alt-list", (target, fme, prefix, gm) -> { + List fancyMessages = new ArrayList<>(); + FancyMessage currentOnline = FactionsPlugin.getInstance().txt().parseFancy(prefix); + boolean firstOnline = true; + for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereRole(Role.ALT))) { + if(p.getRole() == Role.ALT)continue; + if (fme.getPlayer() != null) { + continue; // skip + } + String name = p.getNameAndTitle(); + currentOnline.then(firstOnline ? name : ", " + name); + currentOnline.tooltip(tipPlayer(p, gm)).color(fme.getColorTo(p)); + firstOnline = false; + if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOnline); + currentOnline = new FancyMessage(""); + } + } + fancyMessages.add(currentOnline); + return firstOnline && Tag.isMinimalShow() ? null : fancyMessages; + }), + OFFLINE_LIST("offline-list", (target, fme, prefix, gm) -> { + List fancyMessages = new ArrayList<>(); + FancyMessage currentOffline = FactionsPlugin.getInstance().txt().parseFancy(prefix); + boolean firstOffline = true; + for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(false, fme))) { + String name = p.getNameAndTitle(); + // Also make sure to add players that are online BUT can't be seen. + if (!p.isOnline() || (fme.getPlayer() != null && p.getPlayer() != null && p.isOnline() && !fme.getPlayer().canSee(p.getPlayer()))) { + currentOffline.then(firstOffline ? name : ", " + name); + currentOffline.tooltip(tipPlayer(p, gm)).color(fme.getColorTo(p)); + firstOffline = false; + if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOffline); + currentOffline = new FancyMessage(""); + } + } + } + fancyMessages.add(currentOffline); + return firstOffline && Tag.isMinimalShow() ? null : fancyMessages; + }), + ; + + private final String tag; + private final QuadFunction, List> function; + + private static List processRelation(String prefix, Faction faction, FPlayer fPlayer, Relation relation) { + List fancyMessages = new ArrayList<>(); + FancyMessage message = FactionsPlugin.getInstance().txt().parseFancy(prefix); + boolean first = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction == faction) { + continue; + } + String s = otherFaction.getTag(fPlayer); + if (otherFaction.getRelationTo(faction) == relation) { + message.then(first ? s : ", " + s); + message.tooltip(tipFaction(otherFaction, fPlayer)).color(fPlayer.getColorTo(otherFaction)); + first = false; + if (message.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(message); + message = new FancyMessage(""); + } + } + } + fancyMessages.add(message); + return first && Tag.isMinimalShow() ? null : fancyMessages; + } + + public static List parse(String text, Faction faction, FPlayer player, Map groupMap) { + for (FancyTag tag : FancyTag.values()) { + if (tag.foundInString(text)) { + return tag.getMessage(text, faction, player, groupMap); + } + } + return Collections.emptyList(); // We really shouldn't be here. + } + + public static boolean anyMatch(String text) { + return getMatch(text) != null; + } + + public static FancyTag getMatch(String text) { + for (FancyTag tag : FancyTag.values()) { + if (tag.foundInString(text)) { + return tag; + } + } + return null; + } + + /** + * Parses tooltip variables from config
Supports variables for factions only (type 2) + * + * @param faction faction to tooltip for + * @return list of tooltips for a fancy message + */ + private static List tipFaction(Faction faction, FPlayer player) { + List lines = new ArrayList<>(); + for (String line : FactionsPlugin.getInstance().conf().commands().toolTips().getFaction()) { + String string = Tag.parsePlain(faction, player, line); + if (string == null) { + continue; + } + lines.add(ChatColor.translateAlternateColorCodes('&', string)); + } + return lines; + } + + /** + * Parses tooltip variables from config
Supports variables for players and factions (types 1 and 2) + * + * @param fplayer player to tooltip for + * @return list of tooltips for a fancy message + */ + private static List tipPlayer(FPlayer fplayer, Map groupMap) { + List lines = new ArrayList<>(); + for (String line : FactionsPlugin.getInstance().conf().commands().toolTips().getPlayer()) { + String newLine = line; + everythingOnYourWayOut: + if (line.contains("{group}")) { + if (groupMap != null) { + String group = groupMap.get(UUID.fromString(fplayer.getId())); + if (group != null && !group.trim().isEmpty()) { + newLine = newLine.replace("{group}", group); + break everythingOnYourWayOut; + } + } + continue; + } + String string = Tag.parsePlain(fplayer, newLine); + if (string == null) { + continue; + } + lines.add(ChatColor.translateAlternateColorCodes('&', string)); + } + return lines; + } + + FancyTag(String tag, QuadFunction, List> function) { + this.tag = '{' + tag + '}'; + this.function = function; + } + + @Override + public String getTag() { + return this.tag; + } + + @Override + public boolean foundInString(String test) { + return test != null && test.contains(this.tag); + } + + public List getMessage(String text, Faction faction, FPlayer player, Map groupMap) { + if (!this.foundInString(text)) { + return Collections.emptyList(); // We really, really shouldn't be here. + } + return this.function.apply(faction, player, text.replace(this.getTag(), ""), groupMap); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/tag/GeneralTag.java b/Factions/src/main/java/com/massivecraft/factions/tag/GeneralTag.java new file mode 100644 index 0000000..8b75186 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/tag/GeneralTag.java @@ -0,0 +1,60 @@ +package com.massivecraft.factions.tag; + +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.util.TL; +import org.bukkit.Bukkit; + +import java.util.function.Supplier; + +public enum GeneralTag implements Tag { + MAX_WARPS("max-warps", () -> String.valueOf(FactionsPlugin.getInstance().conf().commands().warp().getMaxWarps())), + MAX_ALLIES("max-allies", () -> getRelation(Relation.ALLY)), + MAX_ENEMIES("max-enemies", () -> getRelation(Relation.ENEMY)), + MAX_TRUCES("max-truces", () -> getRelation(Relation.TRUCE)), + FACTIONLESS("factionless", () -> String.valueOf(FPlayers.getInstance().getOnlinePlayers().stream().filter(p -> !p.hasFaction()).count())), + FACTIONLESS_TOTAL("factionless-total", () -> String.valueOf(FPlayers.getInstance().getAllFPlayers().stream().filter(p -> !p.hasFaction()).count())), + TOTAL_ONLINE("total-online", () -> String.valueOf(Bukkit.getOnlinePlayers().size())), + ; + + private final String tag; + private final Supplier supplier; + + private static String getRelation(Relation relation) { + if (FactionsPlugin.getInstance().conf().factions().maxRelations().isEnabled()) { + return String.valueOf(relation.getMax()); + } + return TL.GENERIC_INFINITY.toString(); + } + + public static String parse(String text) { + for (GeneralTag tag : GeneralTag.values()) { + text = tag.replace(text); + } + return text; + } + + GeneralTag(String tag, Supplier supplier) { + this.tag = '{' + tag + '}'; + this.supplier = supplier; + } + + @Override + public String getTag() { + return this.tag; + } + + @Override + public boolean foundInString(String test) { + return test != null && test.contains(this.tag); + } + + public String replace(String text) { + if (!this.foundInString(text)) { + return text; + } + String result = this.supplier.get(); + return result == null ? null : text.replace(this.tag, result); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/tag/PlayerTag.java b/Factions/src/main/java/com/massivecraft/factions/tag/PlayerTag.java new file mode 100644 index 0000000..94c8d86 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/tag/PlayerTag.java @@ -0,0 +1,79 @@ +package com.massivecraft.factions.tag; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.integration.Econ; +import com.massivecraft.factions.util.TL; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.util.function.Function; + +public enum PlayerTag implements Tag { + GROUP("group", (fp) -> { + if (fp.isOnline()) { + return FactionsPlugin.getInstance().getPrimaryGroup(fp.getPlayer()); + } else { + return ""; + } + }), + LAST_SEEN("lastSeen", (fp) -> { + String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; + return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); + }), + PLAYER_BALANCE("balance", (fp) -> Econ.isSetup() ? Econ.getFriendlyBalance(fp) : (Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"))), + PLAYER_POWER("player-power", (fp) -> String.valueOf(fp.getPowerRounded())), + PLAYER_MAXPOWER("player-maxpower", (fp) -> String.valueOf(fp.getPowerMaxRounded())), + PLAYER_KILLS("player-kills", (fp) -> String.valueOf(fp.getKills())), + PLAYER_DEATHS("player-deaths", (fp) -> String.valueOf(fp.getDeaths())), + PLAYER_NAME("name", FPlayer::getName), + TOTAL_ONLINE_VISIBLE("total-online-visible", (fp) -> { + if (fp == null) { + return String.valueOf(Bukkit.getOnlinePlayers().size()); + } + int count = 0; + Player me = fp.getPlayer(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (me.canSee(player)) { + count++; + } + } + return String.valueOf(count); + }), + ; + + private final String tag; + private final Function function; + + public static String parse(String text, FPlayer player) { + for (PlayerTag tag : PlayerTag.values()) { + text = tag.replace(text, player); + } + return text; + } + + PlayerTag(String tag, Function function) { + this.tag = '{' + tag + '}'; + this.function = function; + } + + @Override + public String getTag() { + return this.tag; + } + + @Override + public boolean foundInString(String test) { + return test != null && test.contains(this.tag); + } + + public String replace(String text, FPlayer player) { + if (!this.foundInString(text)) { + return text; + } + String result = this.function.apply(player); + return result == null ? null : text.replace(this.tag, result); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/tag/Tag.java b/Factions/src/main/java/com/massivecraft/factions/tag/Tag.java new file mode 100644 index 0000000..9715e2f --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/tag/Tag.java @@ -0,0 +1,85 @@ +package com.massivecraft.factions.tag; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.entity.Player; + +public interface Tag { + int ARBITRARY_LIMIT = 25000; + + /** + * Replaces all variables in a plain raw line for a faction + * + * @param faction for faction + * @param line raw line from config with variables to replace for + * @return clean line + */ + static String parsePlain(Faction faction, String line) { + return GeneralTag.parse(FactionTag.parse(line, faction)); + } + + /** + * Replaces all variables in a plain raw line for a player + * + * @param fplayer for player + * @param line raw line from config with variables to replace for + * @return clean line + */ + static String parsePlain(FPlayer fplayer, String line) { + return parsePlain(fplayer.getFaction(), fplayer, line); + } + + /** + * Replaces all variables in a plain raw line for a faction, using relations from fplayer + * + * @param faction for faction + * @param fplayer from player + * @param line raw line from config with variables to replace for + * @return clean line + */ + static String parsePlain(Faction faction, FPlayer fplayer, String line) { + return GeneralTag.parse(PlayerTag.parse(FactionTag.parse(line, faction, fplayer), fplayer)); + } + + static String parsePlaceholders(Player player, String line) { + if (player == null || line == null) { + return line; + } + + if (FactionsPlugin.getInstance().isClipPlaceholderAPIHooked() && player.isOnline()) { + line = PlaceholderAPI.setPlaceholders(player, line); + } + + if (FactionsPlugin.getInstance().isMVdWPlaceholderAPIHooked() && player.isOnline()) { + String maybe = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line); + if (maybe != null) { + line = maybe; + // Amazing feature where, if the user makes a mistake and does not install any other MVdW plugins, + // it will simply return null to break everything down the line. + } + } + + return line; + } + + static boolean isMinimalShow() { + return FactionsPlugin.getInstance().conf().commands().show().isMinimal(); + } + + /** + * Gets the Tag's string representation. + * + * @return tag + */ + String getTag(); + + /** + * Gets if the Tag can be found in the given String. + * + * @param test string to test + * @return true if the tag is found in this string + */ + boolean foundInString(String test); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/AsciiCompass.java b/Factions/src/main/java/com/massivecraft/factions/util/AsciiCompass.java new file mode 100644 index 0000000..fc8f127 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/AsciiCompass.java @@ -0,0 +1,109 @@ +package com.massivecraft.factions.util; + +import org.bukkit.ChatColor; + +import java.util.ArrayList; + +public class AsciiCompass { + + public enum Point { + + N('N'), + NE('/'), + E('E'), + SE('\\'), + S('S'), + SW('/'), + W('W'), + NW('\\'); + + public final char asciiChar; + + Point(final char asciiChar) { + this.asciiChar = asciiChar; + } + + @Override + public String toString() { + return String.valueOf(this.asciiChar); + } + + public String getTranslation() { + if (this == N) { + return TL.COMPASS_SHORT_NORTH.toString(); + } + if (this == E) { + return TL.COMPASS_SHORT_EAST.toString(); + } + if (this == S) { + return TL.COMPASS_SHORT_SOUTH.toString(); + } + if (this == W) { + return TL.COMPASS_SHORT_WEST.toString(); + } + return toString(); + } + + public String toString(boolean isActive, ChatColor colorActive, String colorDefault) { + return (isActive ? colorActive : colorDefault) + getTranslation(); + } + } + + public static AsciiCompass.Point getCompassPointForDirection(double inDegrees) { + double degrees = (inDegrees - 180) % 360; + if (degrees < 0) { + degrees += 360; + } + + if (0 <= degrees && degrees < 22.5) { + return AsciiCompass.Point.N; + } else if (22.5 <= degrees && degrees < 67.5) { + return AsciiCompass.Point.NE; + } else if (67.5 <= degrees && degrees < 112.5) { + return AsciiCompass.Point.E; + } else if (112.5 <= degrees && degrees < 157.5) { + return AsciiCompass.Point.SE; + } else if (157.5 <= degrees && degrees < 202.5) { + return AsciiCompass.Point.S; + } else if (202.5 <= degrees && degrees < 247.5) { + return AsciiCompass.Point.SW; + } else if (247.5 <= degrees && degrees < 292.5) { + return AsciiCompass.Point.W; + } else if (292.5 <= degrees && degrees < 337.5) { + return AsciiCompass.Point.NW; + } else if (337.5 <= degrees && degrees < 360.0) { + return AsciiCompass.Point.N; + } else { + return null; + } + } + + public static ArrayList getAsciiCompass(Point point, ChatColor colorActive, String colorDefault) { + ArrayList ret = new ArrayList<>(); + String row; + + row = ""; + row += Point.NW.toString(Point.NW == point, colorActive, colorDefault); + row += Point.N.toString(Point.N == point, colorActive, colorDefault); + row += Point.NE.toString(Point.NE == point, colorActive, colorDefault); + ret.add(row); + + row = ""; + row += Point.W.toString(Point.W == point, colorActive, colorDefault); + row += colorDefault + "+"; + row += Point.E.toString(Point.E == point, colorActive, colorDefault); + ret.add(row); + + row = ""; + row += Point.SW.toString(Point.SW == point, colorActive, colorDefault); + row += Point.S.toString(Point.S == point, colorActive, colorDefault); + row += Point.SE.toString(Point.SE == point, colorActive, colorDefault); + ret.add(row); + + return ret; + } + + public static ArrayList getAsciiCompass(double inDegrees, ChatColor colorActive, String colorDefault) { + return getAsciiCompass(getCompassPointForDirection(inDegrees), colorActive, colorDefault); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/AsyncSpiralTask.java b/Factions/src/main/java/com/massivecraft/factions/util/AsyncSpiralTask.java new file mode 100644 index 0000000..0cc424e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/AsyncSpiralTask.java @@ -0,0 +1,16 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; + +public abstract class AsyncSpiralTask extends SpiralTask{ + public AsyncSpiralTask(FLocation fLocation, int radius) { + super(fLocation, radius, 0); + + this.runTaskTimerAsynchronously(FactionsPlugin.getInstance(), 0, 1); + + this.setTaskID(this.getTaskId()); + + this.timeout = 40; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java b/Factions/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java new file mode 100644 index 0000000..94da3cf --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java @@ -0,0 +1,96 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.ListIterator; +import java.util.logging.Level; + +public class AutoLeaveProcessTask extends BukkitRunnable { + + private transient boolean readyToGo; + private transient boolean finished; + private final transient ListIterator iterator; + private final transient double toleranceMillis; + + public AutoLeaveProcessTask() { + ArrayList fplayers = (ArrayList) FPlayers.getInstance().getAllFPlayers(); + this.iterator = fplayers.listIterator(); + this.toleranceMillis = FactionsPlugin.getInstance().conf().factions().other().getAutoLeaveAfterDaysOfInactivity() * 24 * 60 * 60 * 1000; + this.readyToGo = true; + this.finished = false; + } + + public void run() { + if (FactionsPlugin.getInstance().conf().factions().other().getAutoLeaveAfterDaysOfInactivity() <= 0.0 || FactionsPlugin.getInstance().conf().factions().other().getAutoLeaveRoutineMaxMillisecondsPerTick() <= 0.0) { + this.stop(); + return; + } + + if (!readyToGo) { + return; + } + // this is set so it only does one iteration at a time, no matter how frequently the timer fires + readyToGo = false; + // and this is tracked to keep one iteration from dragging on too long and possibly choking the system if there are a very large number of players to go through + long loopStartTime = System.currentTimeMillis(); + + while (iterator.hasNext()) { + long now = System.currentTimeMillis(); + + // if this iteration has been running for maximum time, stop to take a breather until next tick + if (now > loopStartTime + FactionsPlugin.getInstance().conf().factions().other().getAutoLeaveRoutineMaxMillisecondsPerTick()) { + readyToGo = true; + return; + } + + FPlayer fplayer = iterator.next(); + + // Check if they should be exempt from this. + if (!fplayer.willAutoLeave()) { + FactionsPlugin.getInstance().debug(Level.INFO, fplayer.getName() + " was going to be auto-removed but was set not to."); + continue; + } + + if (fplayer.isOffline() && now - fplayer.getLastLoginTime() > toleranceMillis) { + if (FactionsPlugin.getInstance().conf().logging().isFactionLeave() || FactionsPlugin.getInstance().conf().logging().isFactionKick()) { + FactionsPlugin.getInstance().log("Player " + fplayer.getName() + " was auto-removed due to inactivity."); + } + + // if player is faction admin, sort out the faction since he's going away + if (fplayer.getRole() == Role.ADMIN) { + Faction faction = fplayer.getFaction(); + if (faction != null) { + fplayer.getFaction().promoteNewLeader(); + } + } + + fplayer.leave(false); + iterator.remove(); // go ahead and remove this list's link to the FPlayer object + if (FactionsPlugin.getInstance().conf().factions().other().isAutoLeaveDeleteFPlayerData()) { + fplayer.remove(); + } + } + } + + // looks like we've finished + this.stop(); + } + + // we're done, shut down + public void stop() { + readyToGo = false; + finished = true; + + this.cancel(); + } + + public boolean isFinished() { + return finished; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java b/Factions/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java new file mode 100644 index 0000000..d68c92c --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java @@ -0,0 +1,27 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FactionsPlugin; + +public class AutoLeaveTask implements Runnable { + + private static AutoLeaveProcessTask task; + double rate; + + public AutoLeaveTask() { + this.rate = FactionsPlugin.getInstance().conf().factions().other().getAutoLeaveRoutineRunsEveryXMinutes(); + } + + public synchronized void run() { + if (task != null && !task.isFinished()) { + return; + } + + task = new AutoLeaveProcessTask(); + task.runTaskTimer(FactionsPlugin.getInstance(), 1, 1); + + // maybe setting has been changed? if so, restart this task at new rate + if (this.rate != FactionsPlugin.getInstance().conf().factions().other().getAutoLeaveRoutineRunsEveryXMinutes()) { + FactionsPlugin.getInstance().startAutoLeaveTask(true); + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/CC.java b/Factions/src/main/java/com/massivecraft/factions/util/CC.java new file mode 100644 index 0000000..b00f4bc --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/CC.java @@ -0,0 +1,116 @@ +/* + * Decompiled with CFR 0.150. + */ +package com.massivecraft.factions.util; + +import org.bukkit.ChatColor; + +import java.util.Arrays; +import java.util.List; + +public class CC { + public static final String Black = ChatColor.BLACK.toString(); + public static final String BlackB = ChatColor.BLACK + ChatColor.BOLD.toString(); + public static final String BlackI = ChatColor.BLACK + ChatColor.ITALIC.toString(); + public static final String BlackU = ChatColor.BLACK + ChatColor.UNDERLINE.toString(); + public static final String DarkBlue = ChatColor.DARK_BLUE.toString(); + public static final String DarkBlueB = ChatColor.DARK_BLUE + ChatColor.BOLD.toString(); + public static final String DarkBlueI = ChatColor.DARK_BLUE + ChatColor.ITALIC.toString(); + public static final String DarkBlueU = ChatColor.DARK_BLUE + ChatColor.UNDERLINE.toString(); + public static final String DarkGreen = ChatColor.DARK_GREEN.toString(); + public static final String DarkGreenB = ChatColor.DARK_GREEN + ChatColor.BOLD.toString(); + public static final String DarkGreenI = ChatColor.DARK_GREEN + ChatColor.ITALIC.toString(); + public static final String DarkGreenU = ChatColor.DARK_GREEN + ChatColor.UNDERLINE.toString(); + public static final String DarkAqua = ChatColor.DARK_AQUA.toString(); + public static final String DarkAquaB = ChatColor.DARK_AQUA + ChatColor.BOLD.toString(); + public static final String DarkAquaI = ChatColor.DARK_AQUA + ChatColor.ITALIC.toString(); + public static final String DarkAquaU = ChatColor.DARK_AQUA + ChatColor.UNDERLINE.toString(); + public static final String DarkRed = ChatColor.DARK_RED.toString(); + public static final String DarkRedB = ChatColor.DARK_RED + ChatColor.BOLD.toString(); + public static final String DarkRedI = ChatColor.DARK_RED + ChatColor.ITALIC.toString(); + public static final String DarkRedU = ChatColor.DARK_RED + ChatColor.UNDERLINE.toString(); + public static final String DarkPurple = ChatColor.DARK_PURPLE.toString(); + public static final String DarkPurpleB = ChatColor.DARK_PURPLE + ChatColor.BOLD.toString(); + public static final String DarkPurpleI = ChatColor.DARK_PURPLE + ChatColor.ITALIC.toString(); + public static final String DarkPurpleU = ChatColor.DARK_PURPLE + ChatColor.UNDERLINE.toString(); + public static final String Gold = ChatColor.GOLD.toString(); + public static final String GoldB = ChatColor.GOLD + ChatColor.BOLD.toString(); + public static final String GoldI = ChatColor.GOLD + ChatColor.ITALIC.toString(); + public static final String GoldU = ChatColor.GOLD + ChatColor.UNDERLINE.toString(); + public static final String Gray = ChatColor.GRAY.toString(); + public static final String GrayB = ChatColor.GRAY + ChatColor.BOLD.toString(); + public static final String GrayI = ChatColor.GRAY + ChatColor.ITALIC.toString(); + public static final String GrayU = ChatColor.GRAY + ChatColor.UNDERLINE.toString(); + public static final String DarkGray = ChatColor.DARK_GRAY.toString(); + public static final String DarkGrayB = ChatColor.DARK_GRAY + ChatColor.BOLD.toString(); + public static final String DarkGrayI = ChatColor.DARK_GRAY + ChatColor.ITALIC.toString(); + public static final String DarkGrayU = ChatColor.DARK_GRAY + ChatColor.UNDERLINE.toString(); + public static final String Blue = ChatColor.BLUE.toString(); + public static final String BlueB = ChatColor.BLUE + ChatColor.BOLD.toString(); + public static final String BlueI = ChatColor.BLUE + ChatColor.ITALIC.toString(); + public static final String BlueU = ChatColor.BLUE + ChatColor.UNDERLINE.toString(); + public static final String Green = ChatColor.GREEN.toString(); + public static final String GreenB = ChatColor.GREEN + ChatColor.BOLD.toString(); + public static final String GreenI = ChatColor.GREEN + ChatColor.ITALIC.toString(); + public static final String GreenU = ChatColor.GREEN + ChatColor.UNDERLINE.toString(); + public static final String Aqua = ChatColor.AQUA.toString(); + public static final String AquaB = ChatColor.AQUA + ChatColor.BOLD.toString(); + public static final String AquaI = ChatColor.AQUA + ChatColor.ITALIC.toString(); + public static final String AquaU = ChatColor.AQUA + ChatColor.UNDERLINE.toString(); + public static final String Red = ChatColor.RED.toString(); + public static final String RedB = ChatColor.RED + ChatColor.BOLD.toString(); + public static final String RedI = ChatColor.RED + ChatColor.ITALIC.toString(); + public static final String RedU = ChatColor.RED + ChatColor.UNDERLINE.toString(); + public static final String LightPurple = ChatColor.LIGHT_PURPLE.toString(); + public static final String LightPurpleB = ChatColor.LIGHT_PURPLE + ChatColor.BOLD.toString(); + public static final String LightPurpleI = ChatColor.LIGHT_PURPLE + ChatColor.ITALIC.toString(); + public static final String LightPurpleU = ChatColor.LIGHT_PURPLE + ChatColor.UNDERLINE.toString(); + public static final String Yellow = ChatColor.YELLOW.toString(); + public static final String YellowB = ChatColor.YELLOW + ChatColor.BOLD.toString(); + public static final String YellowI = ChatColor.YELLOW + ChatColor.ITALIC.toString(); + public static final String YellowU = ChatColor.YELLOW + ChatColor.UNDERLINE.toString(); + public static final String White = ChatColor.WHITE.toString(); + public static final String WhiteB = ChatColor.WHITE + ChatColor.BOLD.toString(); + public static final String WhiteI = ChatColor.WHITE + ChatColor.ITALIC.toString(); + public static final String WhiteU = ChatColor.WHITE + ChatColor.UNDERLINE.toString(); + public static final String Bold = ChatColor.BOLD.toString(); + public static final String Strike = ChatColor.STRIKETHROUGH.toString(); + public static final String Underline = ChatColor.UNDERLINE.toString(); + public static final String Magic = ChatColor.MAGIC.toString(); + public static final String Italic = ChatColor.ITALIC.toString(); + public static final String Reset = ChatColor.RESET.toString(); + public static final String Go = GreenB + " " + Green; + public static final String Wait = YellowB + " " + Yellow; + public static final String Stop = RedB + " " + Red; + + public static String prefix(char color) { + return CC.translate("&" + color + "&l &" + color); + } + + public static String translate(String string) { + char[] b = string.toCharArray(); + + for (int i = 0; i < b.length - 1; ++i) { + if (b[i] == '&' && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { + b[i] = 167; + b[i + 1] = Character.toLowerCase(b[i + 1]); + } + } + + return new String(b); + } + + public static List translate(List stringList) { + stringList.replaceAll(CC::translate); + return stringList; + } + + public static List translate(String... string) { + return CC.translate(Arrays.asList(string)); + } + + public static String strip(String string) { + return ChatColor.stripColor(string); + } +} + diff --git a/Factions/src/main/java/com/massivecraft/factions/util/Clickable.java b/Factions/src/main/java/com/massivecraft/factions/util/Clickable.java new file mode 100644 index 0000000..4ae2b65 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/Clickable.java @@ -0,0 +1,54 @@ +package com.massivecraft.factions.util; + + +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class Clickable { + private final List components = new ArrayList<>(); + + public Clickable(String msg) { + TextComponent message = new TextComponent(msg); + this.components.add(message); + } + + public Clickable(String msg, String hoverMsg) { + this(msg, hoverMsg, ""); + } + + public Clickable(String msg, String hoverMsg, String clickString) { + add(msg, hoverMsg, clickString); + } + + public TextComponent add(String msg, String hoverMsg) { + return add(msg, hoverMsg, ""); + } + + public TextComponent add(String msg, String hoverMsg, String clickString) { + TextComponent message = new TextComponent(TextUtil.parseColor(msg)); + if (hoverMsg != null && !hoverMsg.isEmpty()) + message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, (new ComponentBuilder(TextUtil.parseColor(hoverMsg))).create())); + if (clickString != null && !clickString.isEmpty()) + message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, clickString)); + this.components.add(message); + return message; + } + + public void add(String message) { + this.components.add(new TextComponent(TextUtil.parseColor(message))); + } + + public void sendToPlayer(Player player) { + player.spigot().sendMessage(this.asComponents()); + } + + public TextComponent[] asComponents() { + return this.components.toArray(new TextComponent[0]); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/Cooldown.java b/Factions/src/main/java/com/massivecraft/factions/util/Cooldown.java new file mode 100644 index 0000000..c1afc20 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/Cooldown.java @@ -0,0 +1,29 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.entity.Player; +import org.bukkit.metadata.FixedMetadataValue; + +import java.util.concurrent.TimeUnit; + +public class Cooldown { + + public static void setCooldown(Player player, String name, int seconds) { + player.setMetadata(name, new FixedMetadataValue(FactionsPlugin.getInstance(), System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds))); + } + + public static void setCooldown(Faction fac, String name, int seconds) { + for (FPlayer fPlayer : fac.getFPlayersWhereOnline(true)) { + if (fPlayer == null) continue; + fPlayer.getPlayer().setMetadata(name, new FixedMetadataValue(FactionsPlugin.getInstance(), System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds))); + } + } + + public static boolean isOnCooldown(Player player, String name) { + if (!player.hasMetadata(name) || player.getMetadata(name).size() <= 0) return false; + long time = player.getMetadata(name).get(0).asLong(); + return (time > System.currentTimeMillis()); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/DiscUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/DiscUtil.java new file mode 100644 index 0000000..71a3122 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/DiscUtil.java @@ -0,0 +1,112 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.scheduler.BukkitRunnable; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.logging.Level; + +public class DiscUtil { + + // -------------------------------------------- // + // BYTE + // -------------------------------------------- // + + + public static byte[] readBytes(File file) throws IOException { + int length = (int) file.length(); + byte[] output = new byte[length]; + InputStream in = new FileInputStream(file); + int offset = 0; + while (offset < length) { + offset += in.read(output, offset, (length - offset)); + } + in.close(); + return output; + } + + public static void writeBytes(File file, byte[] bytes) throws IOException { + if (!file.exists()) { + file.createNewFile(); + } + FileOutputStream out = new FileOutputStream(file); + out.write(bytes); + out.close(); + } + + // -------------------------------------------- // + // STRING + // -------------------------------------------- // + + public static void write(File file, String content) throws IOException { + writeBytes(file, content.getBytes(StandardCharsets.UTF_8)); + } + + public static String read(File file) throws IOException { + return new String(readBytes(file), StandardCharsets.UTF_8); + } + + // -------------------------------------------- // + // CATCH + // -------------------------------------------- // + + private static final HashMap locks = new HashMap<>(); + + public static boolean writeCatch(final File file, final String content, boolean sync) { + String name = file.getName(); + final Lock lock; + + // Create lock for each file if there isn't already one. + if (locks.containsKey(name)) { + lock = locks.get(name); + } else { + ReadWriteLock rwl = new ReentrantReadWriteLock(); + lock = rwl.writeLock(); + locks.put(name, lock); + } + + if (sync) { + lock.lock(); + try { + write(file, content); + } catch (IOException e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to write file " + file.getAbsolutePath(), e); + } finally { + lock.unlock(); + } + } else { + new BukkitRunnable() { + @Override + public void run() { + lock.lock(); + try { + write(file, content); + } catch (IOException e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to write file " + file.getAbsolutePath(), e); + } finally { + lock.unlock(); + } + } + }.runTaskAsynchronously(FactionsPlugin.getInstance()); + } + + return true; // don't really care but for some reason this is a boolean. + } + + public static String readCatch(File file) { + try { + return read(file); + } catch (IOException e) { + return null; + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java b/Factions/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java new file mode 100644 index 0000000..42dd707 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java @@ -0,0 +1,67 @@ +package com.massivecraft.factions.util; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public final class EnumTypeAdapter> extends TypeAdapter { + + private final Map nameToConstant = new HashMap<>(); + private final Map constantToName = new HashMap<>(); + + public EnumTypeAdapter(Class classOfT) { + try { + for (T constant : classOfT.getEnumConstants()) { + String name = constant.name(); + SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class); + if (annotation != null) { + name = annotation.value(); + } + nameToConstant.put(name, constant); + constantToName.put(constant, name); + } + } catch (NoSuchFieldException e) { + // ignore since it could be a modified enum + } + } + + public T read(JsonReader in) throws IOException { + if (in.peek() == JsonToken.NULL) { + in.nextNull(); + return null; + } + return nameToConstant.get(in.nextString()); + } + + public void write(JsonWriter out, T value) throws IOException { + out.value(value == null ? null : constantToName.get(value)); + } + + public static final TypeAdapterFactory ENUM_FACTORY = newEnumTypeHierarchyFactory(); + + public static TypeAdapterFactory newEnumTypeHierarchyFactory() { + return new TypeAdapterFactory() { + @SuppressWarnings({"unchecked"}) + public TypeAdapter create(Gson gson, TypeToken typeToken) { + Class rawType = typeToken.getRawType(); + if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) { + return null; + } + if (!rawType.isEnum()) { + rawType = rawType.getSuperclass(); // handle anonymous subclasses + } + return (TypeAdapter) new EnumTypeAdapter(rawType); + } + }; + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/FChestHolder.java b/Factions/src/main/java/com/massivecraft/factions/util/FChestHolder.java new file mode 100644 index 0000000..2e8ef48 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/FChestHolder.java @@ -0,0 +1,11 @@ +package com.massivecraft.factions.util; + +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +public class FChestHolder implements InventoryHolder { + @Override + public Inventory getInventory() { + return null; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/FlightUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/FlightUtil.java new file mode 100644 index 0000000..944c5e4 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/FlightUtil.java @@ -0,0 +1,129 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Relation; +import com.massivecraft.factions.struct.Permission; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Collection; + +public class FlightUtil { + + private static FlightUtil instance; + + private EnemiesTask enemiesTask; + + private FlightUtil() { + double enemyCheck = FactionsPlugin.getInstance().conf().commands().fly().getRadiusCheck() * 20; + if (enemyCheck > 0) { + enemiesTask = new EnemiesTask(); + enemiesTask.runTaskTimerAsynchronously(FactionsPlugin.getInstance(), 0, (long) enemyCheck); + } + + double spawnRate = FactionsPlugin.getInstance().conf().commands().fly().particles().getSpawnRate() * 20; + if (spawnRate > 0) { + new ParticleTrailsTask().runTaskTimer(FactionsPlugin.getInstance(), 0, (long) spawnRate); + } + } + + public static void start() { + instance = new FlightUtil(); + } + + public static FlightUtil instance() { + return instance; + } + + public boolean enemiesNearby(FPlayer target, int radius) { + if (this.enemiesTask == null) { + return false; + } else { + return this.enemiesTask.enemiesNearby(target, radius); + } + } + + public static class EnemiesTask extends BukkitRunnable { + + @Override + public void run() { + /*Collection players = FPlayers.getInstance().getOnlinePlayers(); + for (Player player : Bukkit.getOnlinePlayers()) { + if(Permission.FLY_ANY.has(player.getPlayer()))continue; + FPlayer pilot = FPlayers.getInstance().getByPlayer(player); + if (pilot.isFlying() && !pilot.isAdminBypassing()) { + if (enemiesNearby(pilot, FactionsPlugin.getInstance().conf().commands().fly().getEnemyRadius(), players)) { + pilot.msg(TL.COMMAND_FLY_ENEMY_DISABLE); + //pilot.setFlying(false); + if (pilot.isAutoFlying()) { + //pilot.setAutoFlying(false); + } + } + } + }*/ + } + + public boolean enemiesNearby(FPlayer target, int radius) { + return this.enemiesNearby(target, radius, FPlayers.getInstance().getOnlinePlayers()); + } + + public boolean enemiesNearby(FPlayer target, int radius, Collection players) { + if (!FactionsPlugin.getInstance().worldUtil().isEnabled(target.getPlayer().getWorld())) { + return false; + } + int radiusSquared = radius * radius; + Location loc = target.getPlayer().getLocation(); + Location cur = new Location(loc.getWorld(), 0, 0, 0); + for (FPlayer player : players) { + if (player == target || (player.getPlayer() != null && Permission.FLY_ANY.has(player.getPlayer())) || player.isAdminBypassing() || (player.getPlayer() != null && player.getPlayer().getGameMode() == GameMode.SPECTATOR)) { + continue; + } + + if (player.isStealth()) { + continue; + } + + player.getPlayer().getLocation(cur); + if (cur.getWorld().getUID().equals(loc.getWorld().getUID()) && + cur.distanceSquared(loc) <= radiusSquared && + player.getRelationTo(target) == Relation.ENEMY && + target.getPlayer().canSee(player.getPlayer())) { + return true; + } + } + return false; + } + } + + public static class ParticleTrailsTask extends BukkitRunnable { + + private final int amount; + private final float speed; + + private ParticleTrailsTask() { + this.amount = FactionsPlugin.getInstance().conf().commands().fly().particles().getAmount(); + this.speed = (float) FactionsPlugin.getInstance().conf().commands().fly().particles().getSpeed(); + } + + @Override + public void run() { + /*for (Player player : Bukkit.getOnlinePlayers()) { + FPlayer pilot = FPlayers.getInstance().getByPlayer(player); + if (pilot.isFlying()) { + if (pilot.getFlyTrailsEffect() != null && Permission.FLY_TRAILS.has(player) && pilot.getFlyTrailsState()) { + Object effect = FactionsPlugin.getInstance().getParticleProvider().effectFromString(pilot.getFlyTrailsEffect()); + FactionsPlugin.getInstance().getParticleProvider().spawn(effect, player.getLocation(), amount, speed, 0, 0, 0); + } + } + } + }*/ + + } + + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/ItemBase64.java b/Factions/src/main/java/com/massivecraft/factions/util/ItemBase64.java new file mode 100644 index 0000000..0add8ce --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/ItemBase64.java @@ -0,0 +1,190 @@ +package com.massivecraft.factions.util; + +import org.bukkit.Bukkit; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class ItemBase64 { + + /** + * Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor. + * + * @param playerInventory to turn into an array of strings. + * @return Array of strings: [ main content, armor content ] + * @throws IllegalStateException + */ + public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { + //get the main content part, this doesn't return the armor + String content = toBase64(playerInventory); + String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); + + return new String[] { content, armor }; + } + + /** + * + * A method to serialize an {@link ItemStack} array to Base64 String. + * + *

+ * + * Based off of {@link #toBase64(Inventory)}. + * + * @param items to turn into a Base64 String. + * @return Base64 string of the items. + * @throws IllegalStateException + */ + public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Write the size of the inventory + dataOutput.writeInt(items.length); + + // Save every element in the list + for (int i = 0; i < items.length; i++) { + dataOutput.writeObject(items[i]); + } + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * A method to serialize an inventory to Base64 string. + * + *

+ * + * Special thanks to Comphenix in the Bukkit forums or also known + * as aadnk on GitHub. + * + * Original Source + * + * @param inventory to serialize + * @return Base64 string of the provided inventory + * @throws IllegalStateException + */ + public static String toBase64(Inventory inventory) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Write the size of the inventory + dataOutput.writeInt(inventory.getSize()); + + // Save every element in the list + for (int i = 0; i < inventory.getSize(); i++) { + dataOutput.writeObject(inventory.getItem(i)); + } + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + public static String toBase64(ItemStack itemStack) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + dataOutput.writeObject(itemStack); + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * + * A method to get an {@link Inventory} from an encoded, Base64, string. + * + *

+ * + * Special thanks to Comphenix in the Bukkit forums or also known + * as aadnk on GitHub. + * + * Original Source + * + * @param data Base64 string of data containing an inventory. + * @return Inventory created from the Base64 string. + * @throws IOException + */ + public static Inventory fromBase64(String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt()); + + // Read the serialized inventory + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, (ItemStack) dataInput.readObject()); + } + + dataInput.close(); + return inventory; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } + + public static ItemStack itemStackFromBase64(String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + ItemStack itemStack = (ItemStack) dataInput.readObject(); + + dataInput.close(); + + return itemStack; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } + + /** + * Gets an array of ItemStacks from Base64 string. + * + *

+ * + * Base off of {@link #fromBase64(String)}. + * + * @param data Base64 string to convert to ItemStack array. + * @return ItemStack array created from the Base64 string. + * @throws IOException + */ + public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + ItemStack[] items = new ItemStack[dataInput.readInt()]; + + // Read the serialized inventory + for (int i = 0; i < items.length; i++) { + items[i] = (ItemStack) dataInput.readObject(); + } + + dataInput.close(); + return items; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/ItemBuilder.java b/Factions/src/main/java/com/massivecraft/factions/util/ItemBuilder.java new file mode 100644 index 0000000..df0fa08 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/ItemBuilder.java @@ -0,0 +1,270 @@ +package com.massivecraft.factions.util; + +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.*; + +public class ItemBuilder { + + private ItemMeta itemMeta; + private final ItemStack itemStack; + + public ItemBuilder(String material) { + this(Material.valueOf(material)); + } + + public ItemBuilder(Material material) { + this(material,1); + } + + public ItemBuilder(Material material, int amount) { + this(new ItemStack(material, amount)); + } + + public ItemBuilder(Material material, String name, String... lore) { + this(material, 1, (short) 0, name, lore); + } + + public ItemBuilder(Material material, String name, List lore) { + this(material, 1, (short) 0, name); + setLore(lore); + } + + public ItemBuilder(Material material, int amount, short durability) { + this(new ItemStack(material, amount, durability)); + } + + public ItemBuilder(Material material, int amount, short durability, String name, String... lore) { + this(new ItemStack(material, amount, durability)); + setName(name); + setLore(lore); + } + + public ItemBuilder(ItemBuilder itemBuilder) { + this.itemStack = itemBuilder.itemStack; + this.itemMeta = itemBuilder.itemMeta; + } + + public ItemBuilder(ConfigurationSection section) { + this(new ItemBuilder(section.getString("name")) + .setLore(section.getStringList("lore")) + .setDurability((short) section.getInt("damage")) + .setUnbreakable(section.getBoolean("unbreakable")) + ); + } + + public ItemBuilder(ItemStack itemStack) { + this.itemStack = itemStack; + this.itemMeta = itemStack.getItemMeta(); + } + + public ItemBuilder clone() { + return new ItemBuilder(build()); + } + + public ItemBuilder setMaterial(String material) { + itemStack.setType(Material.valueOf(material)); + return this; + } + + public ItemBuilder setMaterial(Material material) { + itemStack.setType(material); + return this; + } + + public ItemBuilder setDurability(short durability) { + itemStack.setDurability(durability); + return this; + } + + public ItemBuilder setName(String name) { + itemMeta.setDisplayName(name); + return this; + } + + public ItemBuilder addUnsafeEnchantment(Enchantment enchantment, int level) { + itemMeta.addEnchant(enchantment, level, true); + return this; + } + + public ItemBuilder addUnsafeEnchantments(Map enchantments) { + enchantments.forEach((enchantment, level) -> itemMeta.addEnchant(enchantment, level, true)); + return this; + } + + public ItemBuilder addEnchantment(Enchantment enchantment, int level) { + itemMeta.addEnchant(enchantment, level,false); + return this; + } + + public ItemBuilder addEnchantments(Map enchantments) { + enchantments.forEach((enchantment, level) -> itemMeta.addEnchant(enchantment, level, false)); + return this; + } + + public ItemBuilder removeEnchantment(Enchantment enchantment) { + itemMeta.removeEnchant(enchantment); + return this; + } + + public ItemBuilder removeEnchantments(Collection enchantments) { + enchantments.forEach(itemMeta::removeEnchant); + return this; + } + + public ItemBuilder setGlowing() { + if (!itemMeta.hasEnchants()) { + itemMeta.addEnchant(Enchantment.DURABILITY,1,true); + } + return addItemFlag(ItemFlag.HIDE_ENCHANTS); + } + + public ItemBuilder colorize() { + colorizeName(); + return colorizeLore(); + } + + public ItemBuilder colorizeLore() { + if (itemMeta.hasLore()) { + List lore = getItemMeta().getLore(); + lore.replaceAll(CC::translate); + return setLore(lore); + } + return this; + } + + public ItemBuilder colorizeName() { + if (itemMeta.hasDisplayName()) setName(CC.translate(getItemMeta().getDisplayName())); + return this; + } + + public ItemBuilder setUnbreakable(boolean unbreakable) { + itemMeta.setUnbreakable(unbreakable); + return this; + } + + public List getLore() { + return itemMeta.getLore(); + } + + public ItemBuilder setLore(String... lore) { + return setLore(Arrays.asList(lore)); + } + + public ItemBuilder setLore(List lore) { + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder removeLoreLine(String line) { + List lore = new ArrayList<>(itemMeta.getLore()); + lore.remove(line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder removeLoreLine(int index) { + if (index < 0) return this; + List lore = new ArrayList<>(itemMeta.getLore()); + if (index > lore.size()) return this; + lore.remove(index); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addLore(String ...lore) { + return addLore(Arrays.asList(lore)); + } + + public ItemBuilder addLore(List lore) { + lore.forEach(this::addLoreLine); + return this; + } + + public ItemBuilder addLoreLine(String line) { + List lore = itemMeta.hasLore() ? new ArrayList<>(itemMeta.getLore()) : new ArrayList<>(); + lore.add(line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder setLoreLine(String line, int pos) { + List lore = new ArrayList<>(itemMeta.getLore()); + if (pos >= lore.size()) return this; + lore.set(pos, line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addLoreLine(String line, int pos) { + List lore = new ArrayList<>(itemMeta.getLore()); + if (pos >= lore.size()) return this; + lore.add(pos, line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addItemFlags(List itemFlags) { + for (String itemFlagStr : itemFlags) { + try { + ItemFlag itemFlag = ItemFlag.valueOf(itemFlagStr); + addItemFlag(itemFlag); + } catch (IllegalArgumentException ignored) {} + } + return this; + } + + public ItemBuilder setItemFlags(List itemFlags) { + itemMeta.addItemFlags(itemFlags.toArray(new ItemFlag[0])); + return this; + } + + public ItemBuilder addItemFlag(ItemFlag itemFlag) { + itemMeta.addItemFlags(itemFlag); + return this; + } + + @SuppressWarnings("deprecation") + public ItemBuilder setColor(DyeColor color) { + itemStack.setDurability(color.getDyeData()); + return this; + } + + public ItemBuilder setLeatherArmorColor(Color color) { + LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; + if (Bukkit.getItemFactory().isApplicable(leatherArmorMeta, itemStack)) { + leatherArmorMeta.setColor(color); + itemMeta = leatherArmorMeta; + } + return this; + } + + public ItemBuilder setSkullOwner(String owner) { + SkullMeta skullMeta = (SkullMeta) itemMeta; + if (Bukkit.getItemFactory().isApplicable(skullMeta, itemStack)) { + skullMeta.setOwner(owner); + itemMeta = skullMeta; + } + return this; + } + + public ItemMeta getItemMeta() { + return itemMeta; + } + + public ItemStack build() { + itemStack.setItemMeta(itemMeta); + return itemStack; + } + +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/util/LazyLocation.java b/Factions/src/main/java/com/massivecraft/factions/util/LazyLocation.java new file mode 100644 index 0000000..a141bbc --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/LazyLocation.java @@ -0,0 +1,101 @@ +package com.massivecraft.factions.util; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + +import java.io.Serializable; + +/* + * This class provides a lazy-load Location, so that World doesn't need to be initialized + * yet when an object of this class is created, only when the Location is first accessed. + */ + +public class LazyLocation implements Serializable { + private static final long serialVersionUID = -6049901271320963314L; + private transient Location location = null; + private String worldName; + private double x; + private double y; + private double z; + private float pitch; + private float yaw; + + public LazyLocation(Location loc) { + setLocation(loc); + } + + public LazyLocation(final String worldName, final double x, final double y, final double z) { + this(worldName, x, y, z, 0, 0); + } + + public LazyLocation(final String worldName, final double x, final double y, final double z, final float yaw, final float pitch) { + this.worldName = worldName; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } + + // This returns the actual Location + public final Location getLocation() { + // make sure Location is initialized before returning it + initLocation(); + return location; + } + + // change the Location + public final void setLocation(Location loc) { + this.location = loc; + this.worldName = loc.getWorld().getName(); + this.x = loc.getX(); + this.y = loc.getY(); + this.z = loc.getZ(); + this.yaw = loc.getYaw(); + this.pitch = loc.getPitch(); + } + + + // This initializes the Location + private void initLocation() { + // if location is already initialized, simply return + if (location != null) { + return; + } + + // get World; hopefully it's initialized at this point + World world = Bukkit.getWorld(worldName); + if (world == null) { + return; + } + + // store the Location for future calls, and pass it on + location = new Location(world, x, y, z, yaw, pitch); + } + + + public final String getWorldName() { + return worldName; + } + + public final double getX() { + return x; + } + + public final double getY() { + return y; + } + + public final double getZ() { + return z; + } + + public final double getPitch() { + return pitch; + } + + public final double getYaw() { + return yaw; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java b/Factions/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java new file mode 100644 index 0000000..c843532 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java @@ -0,0 +1,110 @@ +package com.massivecraft.factions.util; + +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + + +public class MapFLocToStringSetTypeAdapter implements JsonDeserializer>>, JsonSerializer>> { + + @Override + public Map> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + try { + JsonObject obj = json.getAsJsonObject(); + if (obj == null) { + return null; + } + + Map> locationMap = new ConcurrentHashMap<>(); + Set nameSet; + Iterator iter; + String worldName; + String[] coords; + int x, z; + + for (Entry entry : obj.entrySet()) { + worldName = entry.getKey(); + for (Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) { + coords = entry2.getKey().trim().split("[,\\s]+"); + x = Integer.parseInt(coords[0]); + z = Integer.parseInt(coords[1]); + + nameSet = new HashSet<>(); + iter = entry2.getValue().getAsJsonArray().iterator(); + while (iter.hasNext()) { + nameSet.add(iter.next().getAsString()); + } + + locationMap.put(new FLocation(worldName, x, z), nameSet); + } + } + + return locationMap; + + } catch (Exception ex) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Error encountered while deserializing a Map of FLocations to String Sets.", ex); + return null; + } + } + + @Override + public JsonElement serialize(Map> src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject obj = new JsonObject(); + + try { + if (src != null) { + FLocation loc; + String locWorld; + Set nameSet; + Iterator iter; + JsonArray nameArray; + JsonPrimitive nameElement; + + for (Entry> entry : src.entrySet()) { + loc = entry.getKey(); + locWorld = loc.getWorldName(); + nameSet = entry.getValue(); + + if (nameSet == null || nameSet.isEmpty()) { + continue; + } + + nameArray = new JsonArray(); + iter = nameSet.iterator(); + while (iter.hasNext()) { + nameElement = new JsonPrimitive(iter.next()); + nameArray.add(nameElement); + } + + if (!obj.has(locWorld)) { + obj.add(locWorld, new JsonObject()); + } + + obj.get(locWorld).getAsJsonObject().add(loc.getCoordString(), nameArray); + } + } + return obj; + + } catch (Exception ex) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Error encountered while serializing a Map of FLocations to String Sets.", ex); + return obj; + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/Metrics.java b/Factions/src/main/java/com/massivecraft/factions/util/Metrics.java new file mode 100644 index 0000000..e8f2f1b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/Metrics.java @@ -0,0 +1,740 @@ +package com.massivecraft.factions.util; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; + +import javax.net.ssl.HttpsURLConnection; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +// !!!CONTAINS MODIFICATIONS FOR FACTIONSUUID!!! + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Metrics { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private final boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // The plugin id + private final int pluginId; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public Metrics(FactionsPlugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + this.pluginId = 5125; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { + } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JsonObject getPluginData() { + JsonObject data = new JsonObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + // FactionsUUID doesn't play by your rules. + pluginName = "FactionsUUID"; + pluginVersion = plugin.getDescription().getVersion().replace("${build.number}", "selfbuilt"); + // FactionsUUID was here + + data.addProperty("pluginName", pluginName); // Append the name of the plugin + data.addProperty("id", pluginId); // Append the id of the plugin + data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin + JsonArray customCharts = new JsonArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JsonObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.add("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JsonObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + String bukkitName = Bukkit.getName(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JsonObject data = new JsonObject(); + + data.addProperty("serverUUID", serverUUID); + + data.addProperty("playerAmount", playerAmount); + data.addProperty("onlineMode", onlineMode); + data.addProperty("bukkitVersion", bukkitVersion); + data.addProperty("bukkitName", bukkitName); + + data.addProperty("javaVersion", javaVersion); + data.addProperty("osName", osName); + data.addProperty("osArch", osArch); + data.addProperty("osVersion", osVersion); + data.addProperty("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JsonObject data = getServerData(); + + JsonArray pluginData = new JsonArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); + if (plugin instanceof JsonObject) { + pluginData.add((JsonObject) plugin); + } else { // old bstats version compatibility + try { + Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); + if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { + Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); + jsonStringGetter.setAccessible(true); + String jsonString = (String) jsonStringGetter.invoke(plugin); + JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); + pluginData.add(object); + } + } catch (ClassNotFoundException e) { + // minecraft version 1.14+ + if (logFailedRequests) { + this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); + } + } + } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } + } + } catch (NoSuchFieldException ignored) { + } + } + + data.add("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(() -> { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JsonObject getRequestJsonObject() { + JsonObject chart = new JsonObject(); + chart.addProperty("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.add("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JsonObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObject value = new JsonObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.addProperty(valueEntry.getKey(), 1/*valueEntry.getValue()*/); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.add(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JsonArray categoryValues = new JsonArray(); + categoryValues.add(new JsonPrimitive(entry.getValue())); + values.add(entry.getKey(), categoryValues); + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JsonArray categoryValues = new JsonArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(new JsonPrimitive(categoryValue)); + } + values.add(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + +} \ No newline at end of file diff --git a/Factions/src/main/java/com/massivecraft/factions/util/MiscUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/MiscUtil.java new file mode 100644 index 0000000..99a49f7 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/MiscUtil.java @@ -0,0 +1,185 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.perms.Role; +import com.massivecraft.factions.util.material.MaterialDb; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.event.entity.CreatureSpawnEvent; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.stream.Collectors; + +public class MiscUtil { + private static final Map entityTypeMap; + public static final Function ENTITY_TYPE_FUNCTION; + public static final Function MATERIAL_FUNCTION; + private static final Map spawnReasonMap; + public static final Function SPAWN_REASON_FUNCTION; + + static { + entityTypeMap = new HashMap<>(); + for (EntityType entityType : EntityType.values()) { + entityTypeMap.put(entityType.name(), entityType); + } + ENTITY_TYPE_FUNCTION = (string) -> string == null ? null : entityTypeMap.get(string.toUpperCase()); + + MATERIAL_FUNCTION = (string) -> { + Material mat = null; + if (string != null) { + mat = MaterialDb.get(string, null); + } + return mat; + }; + + spawnReasonMap = new HashMap<>(); + for (CreatureSpawnEvent.SpawnReason reason : CreatureSpawnEvent.SpawnReason.values()) { + spawnReasonMap.put(reason.name(), reason); + } + SPAWN_REASON_FUNCTION = (string) -> string == null ? null : spawnReasonMap.get(string.toUpperCase()); + } + + public static Set typeSetFromStringSet(Set stringSet, Function function) { + Set typeSet = new HashSet<>(); + for (String string : stringSet) { + if (string != null) { + Type item = function.apply(string); + if (item != null) { + typeSet.add(item); + } + } + } + return Collections.unmodifiableSet(typeSet); + } + + // Inclusive range + public static long[] range(long start, long end) { + long[] values = new long[(int) Math.abs(end - start) + 1]; + + if (end < start) { + long oldstart = start; + start = end; + end = oldstart; + } + + for (long i = start; i <= end; i++) { + values[(int) (i - start)] = i; + } + + return values; + } + + /// TODO create tag whitelist!! + public static HashSet substanceChars = new HashSet<>(Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")); + + public static String getComparisonString(String str) { + StringBuilder ret = new StringBuilder(); + + str = ChatColor.stripColor(str); + str = str.toLowerCase(); + + for (char c : str.toCharArray()) { + if (substanceChars.contains(String.valueOf(c))) { + ret.append(c); + } + } + return ret.toString().toLowerCase(); + } + + public static ArrayList validateTag(String str) { + ArrayList errors = new ArrayList<>(); + + for (String blacklistItem : FactionsPlugin.getInstance().conf().factions().other().getNameBlacklist()) { + if (str.toLowerCase().contains(blacklistItem.toLowerCase())) { + errors.add(FactionsPlugin.getInstance().txt().parse(TL.GENERIC_FACTIONTAG_BLACKLIST.toString())); + break; + } + } + + if (getComparisonString(str).length() < FactionsPlugin.getInstance().conf().factions().other().getTagLengthMin()) { + errors.add(FactionsPlugin.getInstance().txt().parse(TL.GENERIC_FACTIONTAG_TOOSHORT.toString(), FactionsPlugin.getInstance().conf().factions().other().getTagLengthMin())); + } + + if (str.length() > FactionsPlugin.getInstance().conf().factions().other().getTagLengthMax()) { + errors.add(FactionsPlugin.getInstance().txt().parse(TL.GENERIC_FACTIONTAG_TOOLONG.toString(), FactionsPlugin.getInstance().conf().factions().other().getTagLengthMax())); + } + + List badChars = null; + for (char c : str.toCharArray()) { + if (!substanceChars.contains(String.valueOf(c))) { + if (badChars == null) { + badChars = new ArrayList<>(); + } + badChars.add(Character.toString(c)); + } + } + if (badChars!=null) { + errors.add(FactionsPlugin.getInstance().txt().parse(TL.GENERIC_FACTIONTAG_ALPHANUMERIC.toString(), String.join("", badChars))); + } + + return errors; + } + + public static Iterable rankOrder(Iterable players) { + List admins = new ArrayList<>(); + List coleaders = new ArrayList<>(); + List moderators = new ArrayList<>(); + List normal = new ArrayList<>(); + List recruit = new ArrayList<>(); + List alt = new ArrayList<>(); + + for (FPlayer player : players) { + + // Fix for some data being broken when we added the recruit rank. + if (player.getRole() == null) { + player.setRole(Role.NORMAL); + FactionsPlugin.getInstance().log(Level.WARNING, String.format("Player %s had null role. Setting them to normal. This isn't good D:", player.getName())); + } + + switch (player.getRole()) { + case ADMIN: + admins.add(player); + break; + + case COLEADER: + coleaders.add(player); + break; + + case MODERATOR: + moderators.add(player); + break; + + case NORMAL: + normal.add(player); + break; + + case RECRUIT: + recruit.add(player); + break; + case ALT: + alt.add(player); + break; + } + } + + List ret = new ArrayList<>(); + ret.addAll(admins); + ret.addAll(coleaders); + ret.addAll(moderators); + ret.addAll(normal); + ret.addAll(recruit); + ret.addAll(alt); + return ret; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/MissionType.java b/Factions/src/main/java/com/massivecraft/factions/util/MissionType.java new file mode 100644 index 0000000..3b12c78 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/MissionType.java @@ -0,0 +1,7 @@ +package com.massivecraft.factions.util; + +public enum MissionType { + HARVEST_CANE, + FISH, + KILL_MOBS; +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java b/Factions/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java new file mode 100644 index 0000000..2f8732d --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java @@ -0,0 +1,63 @@ +package com.massivecraft.factions.util; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.massivecraft.factions.FactionsPlugin; + +import java.lang.reflect.Type; +import java.util.logging.Level; + + +public class MyLocationTypeAdapter implements JsonDeserializer, JsonSerializer { + + private static final String WORLD = "world"; + private static final String X = "x"; + private static final String Y = "y"; + private static final String Z = "z"; + private static final String YAW = "yaw"; + private static final String PITCH = "pitch"; + + @Override + public LazyLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + try { + JsonObject obj = json.getAsJsonObject(); + + String worldName = obj.get(WORLD).getAsString(); + double x = obj.get(X).getAsDouble(); + double y = obj.get(Y).getAsDouble(); + double z = obj.get(Z).getAsDouble(); + float yaw = obj.get(YAW).getAsFloat(); + float pitch = obj.get(PITCH).getAsFloat(); + + return new LazyLocation(worldName, x, y, z, yaw, pitch); + + } catch (Exception ex) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Error encountered while deserializing a LazyLocation.", ex); + return null; + } + } + + @Override + public JsonElement serialize(LazyLocation src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject obj = new JsonObject(); + + try { + obj.addProperty(WORLD, src.getWorldName()); + obj.addProperty(X, src.getX()); + obj.addProperty(Y, src.getY()); + obj.addProperty(Z, src.getZ()); + obj.addProperty(YAW, src.getYaw()); + obj.addProperty(PITCH, src.getPitch()); + + return obj; + } catch (Exception ex) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Error encountered while serializing a LazyLocation.", ex); + return obj; + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/Pair.java b/Factions/src/main/java/com/massivecraft/factions/util/Pair.java new file mode 100644 index 0000000..43ab2b8 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/Pair.java @@ -0,0 +1,23 @@ +package com.massivecraft.factions.util; + +public class Pair { + public static Pair of(Left left, Right right) { + return new Pair<>(left, right); + } + + private final Left left; + private final Right right; + + private Pair(Left left, Right right) { + this.left = left; + this.right = right; + } + + public Left getLeft() { + return this.left; + } + + public Right getRight() { + return this.right; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/PermUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/PermUtil.java new file mode 100644 index 0000000..e9871f5 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/PermUtil.java @@ -0,0 +1,55 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; + +import java.util.HashMap; +import java.util.Map; + + +public class PermUtil { + + public Map permissionDescriptions = new HashMap<>(); + + protected FactionsPlugin plugin; + + public PermUtil(FactionsPlugin plugin) { + this.plugin = plugin; + this.setup(); + } + + public String getForbiddenMessage(String perm) { + return plugin.txt().parse(TL.GENERIC_NOPERMISSION.toString(), getPermissionDescription(perm)); + } + + /** + * This method hooks into all permission plugins we are supporting + */ + public final void setup() { + for (Permission permission : plugin.getDescription().getPermissions()) { + //p.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\""); + this.permissionDescriptions.put(permission.getName(), permission.getDescription()); + } + } + + public String getPermissionDescription(String perm) { + String desc = permissionDescriptions.get(perm); + if (desc == null) { + return TL.GENERIC_DOTHAT.toString(); + } + return desc; + } + + public boolean has(CommandSender me, String perm, boolean informSenderIfNot) { + if (me == null) { + return false; // What? How? + } + if (me.hasPermission(perm)) { + return true; + } else if (informSenderIfNot) { + me.sendMessage(this.getForbiddenMessage(perm)); + } + return false; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/Persist.java b/Factions/src/main/java/com/massivecraft/factions/util/Persist.java new file mode 100644 index 0000000..8a97648 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/Persist.java @@ -0,0 +1,153 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FactionsPlugin; + +import java.io.File; +import java.lang.reflect.Type; +import java.util.logging.Level; + +// TODO: Give better name and place to differentiate from the entity-orm-ish system in "com.massivecraft.core.persist". + +public class Persist { + + private final FactionsPlugin plugin; + + public Persist(FactionsPlugin plugin) { + this.plugin = plugin; + } + + // ------------------------------------------------------------ // + // GET NAME - What should we call this type of object? + // ------------------------------------------------------------ // + + public static String getName(Class clazz) { + return clazz.getSimpleName().toLowerCase(); + } + + public static String getName(Object o) { + return getName(o.getClass()); + } + + public static String getName(Type type) { + return getName(type.getClass()); + } + + // ------------------------------------------------------------ // + // GET FILE - In which file would we like to store this object? + // ------------------------------------------------------------ // + + public File getFile(String name) { + return new File(plugin.getDataFolder(), name + ".json"); + } + + public File getFile(Class clazz) { + return getFile(getName(clazz)); + } + + public File getFile(Object obj) { + return getFile(getName(obj)); + } + + public File getFile(Type type) { + return getFile(getName(type)); + } + + + // NICE WRAPPERS + + public T loadOrSaveDefault(T def, Class clazz) { + return loadOrSaveDefault(def, clazz, getFile(clazz)); + } + + public T loadOrSaveDefault(T def, Class clazz, String name) { + return loadOrSaveDefault(def, clazz, getFile(name)); + } + + public T loadOrSaveDefault(T def, Class clazz, File file) { + if (!file.exists()) { + plugin.getLogger().info("Creating default: " + file); + this.save(def, file); + return def; + } + + T loaded = this.load(clazz, file); + + if (loaded == null) { + plugin.log(Level.WARNING, "Using default as I failed to load: " + file); + + // backup bad file, so user can attempt to recover their changes from it + File backup = new File(file.getPath() + "_bad"); + if (backup.exists()) { + backup.delete(); + } + plugin.log(Level.WARNING, "Backing up copy of bad file to: " + backup); + file.renameTo(backup); + + return def; + } + + return loaded; + } + + // SAVE + + public boolean save(Object instance) { + return save(instance, getFile(instance)); + } + + public boolean save(Object instance, String name) { + return save(instance, getFile(name)); + } + + public boolean save(Object instance, File file) { + return DiscUtil.writeCatch(file, plugin.getGson().toJson(instance), true); + } + + // LOAD BY CLASS + + public T load(Class clazz) { + return load(clazz, getFile(clazz)); + } + + public T load(Class clazz, String name) { + return load(clazz, getFile(name)); + } + + public T load(Class clazz, File file) { + String content = DiscUtil.readCatch(file); + if (content == null) { + return null; + } + + try { + return plugin.getGson().fromJson(content, clazz); + } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely + plugin.log(Level.WARNING, ex.getMessage()); + } + + return null; + } + + + // LOAD BY TYPE + @SuppressWarnings("unchecked") + public T load(Type typeOfT, String name) { + return (T) load(typeOfT, getFile(name)); + } + + @SuppressWarnings("unchecked") + public T load(Type typeOfT, File file) { + String content = DiscUtil.readCatch(file); + if (content == null) { + return null; + } + + try { + return (T) plugin.getGson().fromJson(content, typeOfT); + } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely + plugin.log(Level.WARNING, ex.getMessage()); + } + + return null; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/QuadFunction.java b/Factions/src/main/java/com/massivecraft/factions/util/QuadFunction.java new file mode 100644 index 0000000..a6a4e1f --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/QuadFunction.java @@ -0,0 +1,6 @@ +package com.massivecraft.factions.util; + +@FunctionalInterface +public interface QuadFunction { + R apply(T t, U u, V v, W w); +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/RelationUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/RelationUtil.java new file mode 100644 index 0000000..0a8f967 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/RelationUtil.java @@ -0,0 +1,145 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.iface.RelationParticipator; +import com.massivecraft.factions.perms.Relation; +import org.bukkit.ChatColor; + +public class RelationUtil { + + public static String describeThatToMe(RelationParticipator that, RelationParticipator me, boolean ucfirst) { + String ret = ""; + + Faction thatFaction = getFaction(that); + if (thatFaction == null) { + return "ERROR"; // ERROR + } + + Faction myFaction = getFaction(me); +// if (myFaction == null) return that.describeTo(null); // no relation, but can show basic name or tag + + if (that instanceof Faction) { + if (me instanceof FPlayer && myFaction == thatFaction) { + ret = TL.GENERIC_YOURFACTION.toString(); + } else { + ret = thatFaction.getTag(); + } + } else if (that instanceof FPlayer) { + FPlayer fplayerthat = (FPlayer) that; + if (that == me) { + ret = TL.GENERIC_YOU.toString(); + } else if (thatFaction == myFaction) { + ret = fplayerthat.getNameAndTitle(); + } else { + ret = fplayerthat.getNameAndTag(); + } + } + + if (ucfirst) { + ret = TextUtil.upperCaseFirst(ret); + } + + return "" + getColorOfThatToMe(that, me) + ret; + } + + public static String describeThatToMe(RelationParticipator that, RelationParticipator me) { + return describeThatToMe(that, me, false); + } + + public static Relation getRelationTo(RelationParticipator me, RelationParticipator that) { + return getRelationTo(that, me, false); + } + + public static Relation getRelationTo(RelationParticipator me, RelationParticipator that, boolean ignorePeaceful) { + Faction fthat = getFaction(that); + if (fthat == null) { + return Relation.NEUTRAL; // ERROR + } + + Faction fme = getFaction(me); + if (fme == null) { + return Relation.NEUTRAL; // ERROR + } + + if (!fthat.isNormal() || !fme.isNormal()) { + return Relation.NEUTRAL; + } + + if (fthat.equals(fme)) { + return Relation.MEMBER; + } + + if (!ignorePeaceful && (fme.isPeaceful() || fthat.isPeaceful())) { + return Relation.NEUTRAL; + } + + if (fme.getRelationWish(fthat).value >= fthat.getRelationWish(fme).value) { + return fthat.getRelationWish(fme); + } + + return fme.getRelationWish(fthat); + } + + public static Relation getRelationToFast(Faction me, Faction that, boolean ignorePeaceful) { + if (that == null) { + return Relation.NEUTRAL; // ERROR + } + + if (me == null) { + return Relation.NEUTRAL; // ERROR + } + + if (!that.isNormal() || !me.isNormal()) { + return Relation.NEUTRAL; + } + + if (that.equals(me)) { + return Relation.MEMBER; + } + + if (!ignorePeaceful && (me.isPeaceful() || that.isPeaceful())) { + return Relation.NEUTRAL; + } + + if (me.getRelationWish(that).value >= that.getRelationWish(me).value) { + return that.getRelationWish(me); + } + + return me.getRelationWish(that); + } + + public static Faction getFaction(RelationParticipator rp) { + if (rp instanceof Faction) { + return (Faction) rp; + } + + if (rp instanceof FPlayer) { + return ((FPlayer) rp).getFaction(); + } + + // ERROR + return null; + } + + public static ChatColor getColorOfThatToMe(RelationParticipator that, RelationParticipator me) { + Faction thatFaction = getFaction(that); + Faction faction = getFaction(me); + if (thatFaction != null) { + if (thatFaction.isPeaceful() && thatFaction != faction) { + return FactionsPlugin.getInstance().conf().colors().relations().getPeaceful(); + } + + if (thatFaction.isSafeZone() && thatFaction != faction) { + return FactionsPlugin.getInstance().conf().colors().factions().getSafezone(); + } + + if (thatFaction.isWarZone() && thatFaction != faction) { + return FactionsPlugin.getInstance().conf().colors().factions().getWarzone(); + } + } + + return getRelationToFast(thatFaction, faction, false).getColor(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/SeeChunkUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/SeeChunkUtil.java new file mode 100644 index 0000000..5d71fbb --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/SeeChunkUtil.java @@ -0,0 +1,111 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.FactionsPlugin; +import com.massivecraft.factions.util.material.MaterialDb; +import com.massivecraft.factions.util.particle.ParticleColor; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +@SuppressWarnings("unchecked") +public class SeeChunkUtil extends BukkitRunnable { + + private final Set playersSeeingChunks = new HashSet<>(); + private final boolean useColor; + private final Object effect; + + public SeeChunkUtil() { + String effectName = FactionsPlugin.getInstance().conf().commands().seeChunk().getParticleName(); + this.effect = FactionsPlugin.getInstance().getParticleProvider().effectFromString(effectName); + this.useColor = FactionsPlugin.getInstance().conf().commands().seeChunk().isRelationalColor(); + + FactionsPlugin.getInstance().getLogger().info(FactionsPlugin.getInstance().txt().parse("Using %s as the ParticleEffect for /f sc", FactionsPlugin.getInstance().getParticleProvider().effectName(effect))); + } + + @Override + public void run() { + for (UUID playerId : playersSeeingChunks) { + Player player = Bukkit.getPlayer(playerId); + if (player == null) { + playersSeeingChunks.remove(playerId); + continue; + } + FPlayer fme = FPlayers.getInstance().getByPlayer(player); + showPillars(player, fme, this.effect, useColor); + } + } + + public void updatePlayerInfo(UUID uuid, boolean toggle) { + if (toggle) { + playersSeeingChunks.add(uuid); + } else { + playersSeeingChunks.remove(uuid); + } + } + + public static void showPillars(Player me, FPlayer fme, Object effect, boolean useColor) { + World world = me.getWorld(); + FLocation flocation = new FLocation(me); + int chunkX = (int) flocation.getX(); + int chunkZ = (int) flocation.getZ(); + + ParticleColor color = null; + if (useColor) { + ChatColor chatColor = Board.getInstance().getFactionAt(flocation).getRelationTo(fme).getColor(); + color = ParticleColor.fromChatColor(chatColor); + } + + int blockX; + int blockZ; + + blockX = chunkX * 16; + blockZ = chunkZ * 16; + showPillar(me, world, blockX, blockZ, effect, color); + + blockX = chunkX * 16 + 16; + blockZ = chunkZ * 16; + showPillar(me, world, blockX, blockZ, effect, color); + + blockX = chunkX * 16; + blockZ = chunkZ * 16 + 16; + showPillar(me, world, blockX, blockZ, effect, color); + + blockX = chunkX * 16 + 16; + blockZ = chunkZ * 16 + 16; + showPillar(me, world, blockX, blockZ, effect, color); + } + + public static void showPillar(Player player, World world, int blockX, int blockZ, Object effect, ParticleColor color) { + // Lets start at the player's Y spot -30 to optimize + for (int blockY = player.getLocation().getBlockY() - 30; blockY < player.getLocation().getBlockY() + 30; blockY++) { + Location loc = new Location(world, blockX, blockY, blockZ); + if (loc.getBlock().getType() != Material.AIR) { + continue; + } + + if (effect != null) { + if (color == null) { + FactionsPlugin.getInstance().getParticleProvider().playerSpawn(player, effect, loc, 1); + } else { + FactionsPlugin.getInstance().getParticleProvider().playerSpawn(player, effect, loc, color); + } + } else { + Material mat = blockY % 5 == 0 ? MaterialDb.get("REDSTONE_LAMP") : MaterialDb.get("GLASS_PANE"); + VisualizeUtil.addLocation(player, loc, mat); + } + } + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/SmokeUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/SmokeUtil.java new file mode 100644 index 0000000..bf67d87 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/SmokeUtil.java @@ -0,0 +1,75 @@ +package com.massivecraft.factions.util; + +import org.bukkit.Effect; +import org.bukkit.Location; + +import java.util.Collection; +import java.util.Random; + +// http://mc.kev009.com/Protocol +// ----------------------------- +// Smoke Directions +// ----------------------------- +// Direction ID Direction +// 0 South - East +// 1 South +// 2 South - West +// 3 East +// 4 (Up or middle ?) +// 5 West +// 6 North - East +// 7 North +// 8 North - West +//----------------------------- + +public class SmokeUtil { + + public static Random random = new Random(); + + // -------------------------------------------- // + // Spawn once + // -------------------------------------------- // + + // Single ======== + public static void spawnSingle(Location location, int direction) { + if (location == null) { + return; + } + location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); + } + + public static void spawnSingle(Location location) { + spawnSingle(location, 4); + } + + public static void spawnSingleRandom(Location location) { + spawnSingle(location, random.nextInt(9)); + } + + // Simple Cloud ======== + public static void spawnCloudSimple(Location location) { + for (int i = 0; i <= 8; i++) { + spawnSingle(location, i); + } + } + + public static void spawnCloudSimple(Collection locations) { + for (Location location : locations) { + spawnCloudSimple(location); + } + } + + // Random Cloud ======== + public static void spawnCloudRandom(Location location, float thickness) { + int singles = (int) Math.floor(thickness * 9); + for (int i = 0; i < singles; i++) { + spawnSingleRandom(location.clone()); + } + } + + public static void spawnCloudRandom(Collection locations, float thickness) { + for (Location location : locations) { + spawnCloudRandom(location, thickness); + } + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/SpiralTask.java b/Factions/src/main/java/com/massivecraft/factions/util/SpiralTask.java new file mode 100644 index 0000000..f6f5afa --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/SpiralTask.java @@ -0,0 +1,237 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.logging.Level; + + +/* + * reference diagram, task should move in this pattern out from chunk 0 in the center. + * 8 [>][>][>][>][>] etc. + * [^][6][>][>][>][>][>][6] + * [^][^][4][>][>][>][4][v] + * [^][^][^][2][>][2][v][v] + * [^][^][^][^][0][v][v][v] + * [^][^][^][1][1][v][v][v] + * [^][^][3][<][<][3][v][v] + * [^][5][<][<][<][<][5][v] + * [7][<][<][<][<][<][<][7] + */ + +public abstract class SpiralTask extends BukkitRunnable { + + // general task-related reference data + private final transient World world; + private transient boolean readyToGo = false; + private transient int taskID = -1; + private final transient int limit; + + // values for the spiral pattern routine + private transient int x = 0; + private transient int z = 0; + private transient boolean isZLeg = false; + private transient boolean isNeg = false; + private transient int length = -1; + private transient int current = 0; + + protected transient int timeout = 10; + + @SuppressWarnings("LeakingThisInConstructor") + public SpiralTask(FLocation fLocation, int radius) { + // limit is determined based on spiral leg length for given radius; see insideRadius() + this.limit = (radius - 1) * 2; + + this.world = Bukkit.getWorld(fLocation.getWorldName()); + if (this.world == null) { + FactionsPlugin.getInstance().log(Level.WARNING, "[SpiralTask] A valid world must be specified!"); + this.stop(); + return; + } + + this.x = (int) fLocation.getX(); + this.z = (int) fLocation.getZ(); + + this.readyToGo = true; + + // get this party started + this.runTaskTimer(FactionsPlugin.getInstance(), 0, 1); + + this.setTaskID(this.getTaskId()); + } + + //This constructor is used so we can set the task ID in a sub-class + public SpiralTask(FLocation fLocation, int radius, int dummymarker) { + // limit is determined based on spiral leg length for given radius; see insideRadius() + this.limit = (radius - 1) * 2; + + this.world = Bukkit.getWorld(fLocation.getWorldName()); + if (this.world == null) { + FactionsPlugin.getInstance().log(Level.WARNING, "[SpiralTask] A valid world must be specified!"); + this.stop(); + return; + } + + this.x = (int) fLocation.getX(); + this.z = (int) fLocation.getZ(); + + this.readyToGo = true; + } + + /* + * This is where the necessary work is done; you'll need to override this method with whatever you want + * done at each chunk in the spiral pattern. + * Return false if the entire task needs to be aborted, otherwise return true to continue. + */ + public abstract boolean work(); + + public void stopTooSoon(){ + this.stop(); + } + + /* + * Returns an FLocation pointing at the current chunk X and Z values. + */ + public final FLocation currentFLocation() { + return new FLocation(world.getName(), x, z); + } + + /* + * Returns a Location pointing at the current chunk X and Z values. + * note that the Location is at the corner of the chunk, not the center. + */ + public final Location currentLocation() { + return new Location(world, FLocation.chunkToBlock(x), 65.0, FLocation.chunkToBlock(z)); + } + + /* + * Returns current chunk X and Z values. + */ + public final int getX() { + return x; + } + + public final int getZ() { + return z; + } + + + + /* + * Below are the guts of the class, which you normally wouldn't need to mess with. + */ + + public final void setTaskID(int ID) { + if (ID == -1) { + this.stop(); + } + taskID = ID; + } + + public final void run() { + if (!this.valid() || !readyToGo) { + return; + } + + // this is set so it only does one iteration at a time, no matter how frequently the timer fires + readyToGo = false; + + // make sure we're still inside the specified radius + if (!this.insideRadius()) { + return; + } + + // track this to keep one iteration from dragging on too long and possibly choking the system + long loopStartTime = now(); + + // keep going until the task has been running for 20ms or more, then stop to take a breather + while (now() < loopStartTime + timeout) { + // run the primary task on the current X/Z coordinates + if (!this.work()) { + this.finish(); + return; + } + + // move on to next chunk in spiral + if (!this.moveToNext()) { + return; + } + } + + // ready for the next iteration to run + readyToGo = true; + } + + // step through chunks in spiral pattern from center; returns false if we're done, otherwise returns true + public final boolean moveToNext() { + if (!this.valid()) { + return false; + } + + // make sure we don't need to turn down the next leg of the spiral + if (current < length) { + current++; + + // if we're outside the radius, we're done + if (!this.insideRadius()) { + return false; + } + } else { // one leg/side of the spiral down... + current = 0; + isZLeg ^= true; + // every second leg (between X and Z legs, negative or positive), length increases + if (isZLeg) { + isNeg ^= true; + length++; + } + } + + // move one chunk further in the appropriate direction + if (isZLeg) { + z += (isNeg) ? -1 : 1; + } else { + x += (isNeg) ? -1 : 1; + } + + return true; + } + + public final boolean insideRadius() { + boolean inside = current < limit; + if (!inside) { + this.finish(); + } + return inside; + } + + // for successful completion + public void finish() { +// P.getInstance().log("SpiralTask successfully completed!"); + + this.stop(); + } + + // we're done, whether finished or cancelled + public final void stop() { + if (!this.valid()) { + return; + } + + readyToGo = false; + Bukkit.getServer().getScheduler().cancelTask(taskID); + taskID = -1; + } + + // is this task still valid/workable? + public final boolean valid() { + return taskID != -1; + } + + private static long now() { + return System.currentTimeMillis(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/StrikeInfo.java b/Factions/src/main/java/com/massivecraft/factions/util/StrikeInfo.java new file mode 100644 index 0000000..50a36d8 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/StrikeInfo.java @@ -0,0 +1,23 @@ +package com.massivecraft.factions.util; + +import java.io.Serializable; + +public class StrikeInfo implements Serializable { + + private long givenAt; + + private String strikeReason; + + public StrikeInfo(long givenAt, String strikeReason){ + this.givenAt = givenAt; + this.strikeReason = strikeReason; + } + + public long getGivenAt() { + return givenAt; + } + + public String getStrikeReason() { + return strikeReason; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/TL.java b/Factions/src/main/java/com/massivecraft/factions/util/TL.java new file mode 100644 index 0000000..8143465 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/TL.java @@ -0,0 +1,1173 @@ +/* + * Copyright (C) 2013 drtshock + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.massivecraft.factions.util; + +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.text.SimpleDateFormat; + +/** + * An enum for requesting strings from the language file. The contents of this enum file may be subject to frequent + * changes. + */ +public enum TL { + /** + * Translation meta + */ + _AUTHOR("misc"), + _RESPONSIBLE("misc"), + _LANGUAGE("English"), + _ENCODING("UTF-8"), + _LOCALE("en_US"), + _REQUIRESUNICODE("false"), + _DEFAULT("true"), + _STATE("complete"), //incomplete, limited, partial, majority, complete + + /** + * Localised translation meta + */ + _LOCAL_AUTHOR("misc"), + _LOCAL_RESPONSIBLE("misc"), + _LOCAL_LANGUAGE("English"), + _LOCAL_REGION("US"), + _LOCAL_STATE("complete"), //And this is the English version. It's not ever going to be not complete. + + /** + * Command translations + */ + COMMAND_ADMIN_NOTMEMBER("%1$s&e is not a member in your faction."), + COMMAND_ADMIN_NOTADMIN("&cYou are not the faction admin."), + COMMAND_ADMIN_TARGETSELF("&cThe target player musn't be yourself."), + COMMAND_ADMIN_DEMOTES("&eYou have demoted %1$s&e from the position of faction admin."), + COMMAND_ADMIN_DEMOTED("&eYou have been demoted from the position of faction admin by %1$s&e."), + COMMAND_ADMIN_PROMOTES("&eYou have promoted %1$s&e to the position of faction admin."), + COMMAND_ADMIN_PROMOTED("%1$s&e gave %2$s&e the leadership of %3$s&e."), + COMMAND_ADMIN_DESCRIPTION("Hand over your admin rights"), + + COMMAND_AHOME_DESCRIPTION("Send a player to their f home no matter what."), + COMMAND_AHOME_NOHOME("%1$s doesn't have an f home."), + COMMAND_AHOME_SUCCESS("%1$s was sent to their f home."), + COMMAND_AHOME_OFFLINE("%1$s is offline."), + COMMAND_AHOME_TARGET("You were sent to your f home."), + + COMMAND_ANNOUNCE_DESCRIPTION("Announce a message to players in faction."), + + COMMAND_AUTOCLAIM_ENABLED("&eNow auto-claiming land for &d%1$s&e."), + COMMAND_AUTOCLAIM_DISABLED("&eAuto-claiming of land disabled."), + COMMAND_AUTOCLAIM_REQUIREDRANK("&cYou must be &d%1$s&c to claim land."), + COMMAND_AUTOCLAIM_OTHERFACTION("&cYou can't claim land for &d%1$s&c."), + COMMAND_AUTOCLAIM_DESCRIPTION("Auto-claim land as you walk around"), + + COMMAND_AUTOHELP_HELPFOR("Help for command \""), + + COMMAND_BAN_DESCRIPTION("Ban players from joining your Faction."), + COMMAND_BAN_TARGET("&cYou were banned from &7%1$s"), // banned player perspective + COMMAND_BAN_BANNED("&e%1$s &cbanned &7%2$s"), + COMMAND_BAN_ALREADYBANNED("&c%1$s is already banned"), + COMMAND_BAN_SELF("&cYou may not ban yourself"), + COMMAND_BAN_INSUFFICIENTRANK("&cYour rank is too low to ban &7%1$s"), + + COMMAND_BANLIST_DESCRIPTION("View a Faction's ban list"), + COMMAND_BANLIST_HEADER("&6There are &c%d&6 bans for %s"), + COMMAND_BANLIST_ENTRY("&7%d. &c%s &r- &a%s &r- &e%s"), + COMMAND_BANLIST_NOFACTION("&4You are not in a Faction."), + COMMAND_BANLIST_INVALID("We couldn't find a Faction by the name %s"), + + COMMAND_BOOM_PEACEFULONLY("&cThis command is only usable by factions which are specifically designated as peaceful."), + COMMAND_BOOM_TOTOGGLE("to toggle explosions"), + COMMAND_BOOM_FORTOGGLE("for toggling explosions"), + COMMAND_BOOM_ENABLED("%1$s&e has %2$s explosions in your faction's territory."), + COMMAND_BOOM_DESCRIPTION("Toggle explosions (peaceful factions only)"), + + COMMAND_BYPASS_ENABLE("&eYou have enabled admin bypass mode. You will be able to build or destroy anywhere."), + COMMAND_BYPASS_ENABLELOG(" has ENABLED admin bypass mode."), + COMMAND_BYPASS_DISABLE("&eYou have disabled admin bypass mode."), + COMMAND_BYPASS_DISABLELOG(" has DISABLED admin bypass mode."), + COMMAND_BYPASS_DESCRIPTION("Enable admin bypass mode"), + + COMMAND_CHAT_DISABLED("&cThe built in chat channels are disabled on this server."), + COMMAND_CHAT_INVALIDMODE("&cUnrecognised chat mode. &ePlease enter either 'a','f','m','t' or 'p'"), + COMMAND_CHAT_INSUFFICIENTRANK("&cYou must be at least moderator to enter this chat."), + COMMAND_CHAT_DESCRIPTION("Change chat mode"), + + COMMAND_CHAT_MODE_PUBLIC("&ePublic chat mode."), + COMMAND_CHAT_MODE_ALLIANCE("&eAlliance only chat mode."), + COMMAND_CHAT_MODE_TRUCE("&eTruce only chat mode."), + COMMAND_CHAT_MODE_FACTION("&eFaction only chat mode."), + COMMAND_CHAT_MODE_MOD("&eMod only chat mode."), + + COMMAND_CHATSPY_ENABLE("&eYou have enabled chat spying mode."), + COMMAND_CHATSPY_ENABLELOG(" has ENABLED chat spying mode."), + COMMAND_CHATSPY_DISABLE("&eYou have disabled chat spying mode."), + COMMAND_CHATSPY_DISABLELOG(" has DISABLED chat spying mode."), + COMMAND_CHATSPY_DESCRIPTION("Enable admin chat spy mode"), + + COMMAND_CLAIM_INVALIDRADIUS("&cIf you specify a radius, it must be at least 1."), + COMMAND_CLAIM_TOOBIG("&cYou can't claim a radius that large! Try <= %s!"), + COMMAND_CLAIM_TOOBIGCONFIRM("&eAre you sure you want to claim in a radius of &d%s&e? Type &d/f claim confirm &eto confirm."), + COMMAND_CLAIM_RADIUS("&eClaiming &d%s &echunks at &d%s&e, &d%s&e for &d%s&e."), + COMMAND_CLAIM_DENIED("&cYou do not have permission to claim in a radius."), + COMMAND_CLAIM_DESCRIPTION("Claim land from where you are standing"), + COMMAND_CLAIM_OUTSIDEBORDER("&cYou can't make a claim outside of the world border!"), + + COMMAND_CLAIMFILL_DESCRIPTION("Claim land filling in a gap in claims"), + COMMAND_CLAIMFILL_ABOVEMAX("&cThe maximum limit for claim fill is %s."), + COMMAND_CLAIMFILL_ALREADYCLAIMED("&cCannot claim fill using already claimed land!"), + COMMAND_CLAIMFILL_TOOFAR("&cThis fill would exceed the maximum distance of %.2f"), + COMMAND_CLAIMFILL_PASTLIMIT("&cThis claim would exceed the limit!"), + COMMAND_CLAIMFILL_NOTENOUGHLANDLEFT("%s &cdoes not have enough land left to make %d claims"), + COMMAND_CLAIMFILL_TOOMUCHFAIL("&cAborting claim fill after %d failures"), + + COMMAND_CLAIMLINE_INVALIDRADIUS("&cIf you specify a distance, it must be at least 1."), + COMMAND_CLAIMLINE_DENIED("&cYou do not have permission to claim in a line."), + COMMAND_CLAIMLINE_DESCRIPTION("Claim land in a straight line."), + COMMAND_CLAIMLINE_ABOVEMAX("&cThe maximum limit for claim line is &c%s&c."), + COMMAND_CLAIMLINE_NOTVALID("%s&c is not a cardinal direction. You may use &dnorth&c, &deast&c, &dsouth &cor &dwest&c."), + + COMMAND_COLEADER_CANDIDATES("Players you can promote: "), + COMMAND_COLEADER_CLICKTOPROMOTE("Click to promote "), + COMMAND_COLEADER_NOTMEMBER("%1$s&c is not a member in your faction."), + COMMAND_COLEADER_NOTADMIN("&cYou are not the faction admin."), + COMMAND_COLEADER_SELF("&cThe target player musn't be yourself."), + COMMAND_COLEADER_TARGETISADMIN("&cThe target player is a faction admin. Demote them first."), + COMMAND_COLEADER_REVOKES("&eYou have removed coleader status from %1$s&e."), + COMMAND_COLEADER_REVOKED("%1$s&e is no longer coleader in your faction."), + COMMAND_COLEADER_PROMOTES("%1$s&e was promoted to coleader in your faction."), + COMMAND_COLEADER_PROMOTED("&eYou have promoted %1$s&e to coleader."), + COMMAND_COLEADER_DESCRIPTION("Give or revoke coleader rights"), + COMMAND_COLEADER_ALREADY_COLEADER("The faction already has a coleader. There can only be 1."), + + COMMAND_CONVERT_BACKEND_RUNNING("Already running that backend."), + COMMAND_CONVERT_BACKEND_INVALID("Invalid backend"), + COMMAND_CONVERT_DESCRIPTION("Convert the plugin backend"), + + COMMAND_COORDS_MESSAGE("&e%s's location: &6%d&e, &6%d&e, &6%d&e in &6%s&e"), + COMMAND_COORDS_DESCRIPTION("Broadcast your current position to your faction"), + + COMMAND_CREATE_MUSTLEAVE("&cYou must leave your current faction first."), + COMMAND_CREATE_INUSE("&cThat tag is already in use."), + COMMAND_CREATE_TOCREATE("to create a new faction"), + COMMAND_CREATE_FORCREATE("for creating a new faction"), + COMMAND_CREATE_ERROR("&cThere was an internal error while trying to create your faction. Please try again."), + COMMAND_CREATE_CREATED("%1$s&e created a new faction %2$s"), + COMMAND_CREATE_YOUSHOULD("&eYou should now: %1$s"), + COMMAND_CREATE_CREATEDLOG(" created a new faction: "), + COMMAND_CREATE_DESCRIPTION("Create a new faction"), + + COMMAND_INSPECT_DISABLED_MSG("&8(&c!&8)&7 Inspect mode is now &cdisabled"), + COMMAND_INSPECT_DISABLED_NOFAC("&8(&c!&8)&7 Inspect mode is now &cdisabled,&7 because you &cdo not have a faction!"), + COMMAND_INSPECT_ENABLED("&8(&a!&8)&7 Inspect mode is now &aenabled."), + COMMAND_INSPECT_HEADER("&8&m---&7Inspect Data&8&m---&8//&ax:{x},y:{y},z:{z}"), + COMMAND_INSPECT_ROW("&a{time} &8// &a{action} &8// &a{player} &8// &a{block-type}"), + COMMAND_INSPECT_NODATA("&8(&a!&8)&7 No Data was found"), + COMMAND_INSPECT_NOTINCLAIM("&8(&a!&8)&7 You can &conly&7 inspect in &cyour &7claims!"), + COMMAND_INSPECT_BYPASS("&8(&a!&8)&7 Inspecting in &cbypass&7 mode"), + COMMAND_INSPECT_DESCRIPTION("Inspect blocks"), + + COMMAND_DEBUG_RUNNING("&eNow running..."), + COMMAND_DEBUG_COMPLETE("&eDebug generated! Share this URL: %s"), + COMMAND_DEBUG_DESCRIPTION("Create a debug paste"), + COMMAND_DEBUG_DELETIONKEY("&eDeletion key: %s"), + COMMAND_DEBUG_FAIL("&eERROR! Could not debug. See console for why."), + + COMMAND_DEINVITE_CANDEINVITE("Players you can deinvite: "), + COMMAND_DEINVITE_CLICKTODEINVITE("Click to revoke invite for %1$s"), + COMMAND_DEINVITE_ALREADYMEMBER("%1$s&e is already a member of %2$s"), + COMMAND_DEINVITE_MIGHTWANT("&eYou might want to: %1$s"), + COMMAND_DEINVITE_REVOKED("%1$s&e revoked your invitation to &d%2$s&e."), + COMMAND_DEINVITE_REVOKES("%1$s&e revoked %2$s's&e invitation."), + COMMAND_DEINVITE_DESCRIPTION("Remove a pending invitation"), + + COMMAND_DELFWARP_DELETED("&eDeleted warp &6%1$s"), + COMMAND_DELFWARP_INVALID("&eCouldn't find warp &6%1$s"), + COMMAND_DELFWARP_TODELETE("to delete warp"), + COMMAND_DELFWARP_FORDELETE("for deleting warp"), + COMMAND_DELFWARP_DESCRIPTION("Delete a faction warp"), + + COMMAND_DELHOME_DEL("%1$s&e unset the home for your faction."), + COMMAND_DELHOME_DESCRIPTION("Unset the faction home"), + COMMAND_DELHOME_TOSET("to unset the faction home"), + COMMAND_DELHOME_FORSET("for unsetting the faction home"), + + COMMAND_DESCRIPTION_CHANGES("You have changed the description for &d%1$s&e to:"), + COMMAND_DESCRIPTION_CHANGED("&eThe faction %1$s&e changed their description to:"), + COMMAND_DESCRIPTION_TOCHANGE("to change faction description"), + COMMAND_DESCRIPTION_FORCHANGE("for changing faction description"), + COMMAND_DESCRIPTION_DESCRIPTION("Change the faction description"), + + COMMAND_DISBAND_IMMUTABLE("&eYou cannot disband the Wilderness, safe zone, or war zone."), + COMMAND_DISBAND_MARKEDPERMANENT("&eThis faction is designated as permanent, so you cannot disband it."), + COMMAND_DISBAND_BROADCAST_YOURS("&d%1$s&e disbanded your faction."), + COMMAND_DISBAND_BROADCAST_NOTYOURS("&d%1$s&e disbanded the faction %2$s."), + COMMAND_DISBAND_HOLDINGS("&eYou have been given the disbanded faction's bank, totaling %1$s."), + COMMAND_DISBAND_DESCRIPTION("Disband a faction"), + + COMMAND_DTR_TOSHOW("to show faction DTR info"), + COMMAND_DTR_FORSHOW("for showing faction DTR info"), + COMMAND_DTR_DTR("%1$s&6 - DTR / Max DTR: &e%2$s / %3$s"), + COMMAND_DTR_DESCRIPTION("Show faction DTR info"), + COMMAND_DTR_MODIFY_DESCRIPTION("Modify faction DTR"), + COMMAND_DTR_MODIFY_DONE("&eSet DTR for %s&e to %s"), + + COMMAND_FLY_DESCRIPTION("Enter or leave Faction flight mode"), + COMMAND_FLY_CHANGE("&eFaction flight &d%1$s"), + COMMAND_FLY_DAMAGE("&eFaction flight &ddisabled&e due to entering combat"), + COMMAND_FLY_AUTO("&eFaction auto flight &d%1$s"), + COMMAND_FLY_NO_ACCESS("&cCannot fly in territory of %1$s"), + COMMAND_FLY_ENEMY_NEARBY("&cCannot enable fly, enemy nearby"), + COMMAND_FLY_ENEMY_DISABLE("&cEnemy nearby, disabling fly"), + + COMMAND_FLYTRAILS_DESCRIPTION("Enabled or change fly trails"), + COMMAND_FLYTRAILS_PARTICLE_INVALID("&cInvalid particle effect"), + COMMAND_FLYTRAILS_PARTICLE_PERMS("&cInsufficient permission to use &d%1s"), + COMMAND_FLYTRAILS_PARTICLE_CHANGE("&eFaction flight trail effect set to &d%1s"), + COMMAND_FLYTRAILS_CHANGE("&eFaction flight trail &d%1s"), + + COMMAND_FWARP_CLICKTOWARP("Click to warp!"), + COMMAND_FWARP_COMMANDFORMAT("&e/f warp [password]"), + COMMAND_FWARP_WARPED("&eWarped to &6%1$s"), + COMMAND_FWARP_INVALID_WARP("&eCouldn't find warp &6%1$s"), + COMMAND_FWARP_TOWARP("to warp"), + COMMAND_FWARP_FORWARPING("for warping"), + COMMAND_FWARP_WARPS("Warps: "), + COMMAND_FWARP_DESCRIPTION("Teleport to a faction warp"), + COMMAND_FWARP_INVALID_PASSWORD("&4Invalid password!"), + COMMAND_FWARP_PASSWORD_REQUIRED("&aPlease enter warp password. This will not be visible to anyone else"), + COMMAND_FWARP_PASSWORD_CANCEL("&cWarp canceled"), + COMMAND_FWARP_NOACCESS("&cYou do not have permission to use %s &cwarps"), + + COMMAND_WARPOTHER_COMMANDFORMAT("&e/f warpother [password]"), + + COMMAND_HELP_404("&cThis page does not exist"), + COMMAND_HELP_NEXTCREATE("&eLearn how to create a faction on the next page."), + COMMAND_HELP_INVITATIONS("command.help.invitations", "&eYou might want to close it and use invitations:"), + COMMAND_HELP_HOME("&eAnd don't forget to set your home:"), + COMMAND_HELP_BANK_1("&eYour faction has a bank which is used to pay for certain"), + COMMAND_HELP_BANK_2("ðings, so it will need to have money deposited into it."), + COMMAND_HELP_BANK_3("&eTo learn more, use the money command."), + COMMAND_HELP_PLAYERTITLES("&ePlayer titles are just for fun. No rules connected to them."), + COMMAND_HELP_OWNERSHIP_1("&eClaimed land with ownership set is further protected so"), + COMMAND_HELP_OWNERSHIP_2("ðat only the owner(s), faction admin, and possibly the"), + COMMAND_HELP_OWNERSHIP_3("&efaction moderators have full access."), + COMMAND_HELP_RELATIONS_1("&eSet the relation you WISH to have with another faction."), + COMMAND_HELP_RELATIONS_2("&eYour default relation with other factions will be neutral."), + COMMAND_HELP_RELATIONS_3("&eIf BOTH factions choose \"ally\" you will be allies."), + COMMAND_HELP_RELATIONS_4("&eIf ONE faction chooses \"enemy\" you will be enemies."), + COMMAND_HELP_RELATIONS_5("&eYou can never hurt members or allies."), + COMMAND_HELP_RELATIONS_6("&eYou can not hurt neutrals in their own territory."), + COMMAND_HELP_RELATIONS_7("&eYou can always hurt enemies and players without faction."), + COMMAND_HELP_RELATIONS_8(""), + COMMAND_HELP_RELATIONS_9("&eDamage from enemies is reduced in your own territory."), + COMMAND_HELP_RELATIONS_10("&eWhen you die you lose power. It is restored over time."), + COMMAND_HELP_RELATIONS_11("&eThe power of a faction is the sum of all member power."), + COMMAND_HELP_RELATIONS_12("&eThe power of a faction determines how much land it can hold."), + COMMAND_HELP_RELATIONS_13("&eYou can claim land from factions with too little power."), + COMMAND_HELP_PERMISSIONS_1("&eOnly faction members can build and destroy in their own"), + COMMAND_HELP_PERMISSIONS_2("&eterritory. Usage of the following items is also restricted:"), + COMMAND_HELP_PERMISSIONS_3("&eDoor, Chest, Furnace, Dispenser, Diode."), + COMMAND_HELP_PERMISSIONS_4(""), + COMMAND_HELP_PERMISSIONS_5("&eMake sure to put pressure plates in front of doors for your"), + COMMAND_HELP_PERMISSIONS_6("&eguest visitors. Otherwise they can't get through. You can"), + COMMAND_HELP_PERMISSIONS_7("&ealso use this to create member only areas."), + COMMAND_HELP_PERMISSIONS_8("&eAs dispensers are protected, you can create traps without"), + COMMAND_HELP_PERMISSIONS_9("&eworrying about those arrows getting stolen."), + COMMAND_HELP_ADMIN_1("&b/f claim safezone &eclaim land for the safe zone"), + COMMAND_HELP_ADMIN_2("&b/f claim warzone &eclaim land for the war zone"), + COMMAND_HELP_ADMIN_3("&b/f autoclaim [safezone|warzone] &etake a guess"), + COMMAND_HELP_MOAR_1("Finally some commands for the server admins:"), + COMMAND_HELP_MOAR_2("&eMore commands for server admins:"), + COMMAND_HELP_MOAR_3("&eEven more commands for server admins:"), + COMMAND_HELP_DESCRIPTION("Display a help page"), + + COMMAND_SOTW_DESCRIPTION("Turn sotw on/off"), + + COMMAND_HOME_DENIED("&cSorry, you cannot teleport to the home of %s"), + COMMAND_HOME_DISABLED("&cSorry, Faction homes are disabled on this server."), + COMMAND_HOME_TELEPORTDISABLED("&cSorry, the ability to teleport to Faction homes is disabled on this server."), + COMMAND_HOME_NOHOME("&cYour faction does not have a home. "), + COMMAND_HOME_INENEMY("&cYou cannot teleport to your faction home while in the territory of an enemy faction."), + COMMAND_HOME_WRONGWORLD("&cYou cannot teleport to your faction home while in a different world."), + COMMAND_HOME_ENEMYNEAR("&cYou cannot teleport to your faction home while an enemy is within %s blocks of you."), + COMMAND_HOME_TOTELEPORT("to teleport to your faction home"), + COMMAND_HOME_FORTELEPORT("for teleporting to your faction home"), + COMMAND_HOME_DESCRIPTION("Teleport to the faction home"), + + COMMAND_INVITE_TOINVITE("to invite someone"), + COMMAND_INVITE_FORINVITE("for inviting someone"), + COMMAND_INVITE_CLICKTOJOIN("Click to join!"), + COMMAND_INVITE_INVITEDYOU(" has invited you to join "), + COMMAND_INVITE_INVITED("%1$s&e invited %2$s&e to your faction."), + COMMAND_INVITE_ALREADYMEMBER("%1$s&e is already a member of %2$s"), + COMMAND_INVITE_DESCRIPTION("Invite a player to your faction"), + COMMAND_INVITE_BANNED("&7%1$s &cis banned from your Faction. Not sending an invite."), + + COMMAND_JOIN_CANNOTFORCE("&cYou do not have permission to move other players into a faction."), + COMMAND_JOIN_SYSTEMFACTION("&cPlayers may only join normal factions. This is a system faction."), + COMMAND_JOIN_ALREADYMEMBER("&c%1$s %2$s already a member of %3$s"), + COMMAND_JOIN_ATLIMIT(" &c!&f The faction %1$s is at the limit of %2$d members, so %3$s cannot currently join."), + COMMAND_JOIN_INOTHERFACTION("&c%1$s must leave %2$s current faction first."), + COMMAND_JOIN_NEGATIVEPOWER("&c%1$s cannot join a faction with a negative power level."), + COMMAND_JOIN_REQUIRESINVITATION("&eThis faction requires invitation."), + COMMAND_JOIN_ATTEMPTEDJOIN("%1$s&e tried to join your faction."), + COMMAND_JOIN_TOJOIN("to join a faction"), + COMMAND_JOIN_FORJOIN("for joining a faction"), + COMMAND_JOIN_SUCCESS("&e%1$s successfully joined %2$s."), + COMMAND_JOIN_MOVED("&e%1$s moved you into the faction %2$s."), + COMMAND_JOIN_JOINED("&e%1$s joined your faction."), + COMMAND_JOIN_JOINEDLOG("%1$s joined the faction %2$s."), + COMMAND_JOIN_MOVEDLOG("%1$s moved the player %2$s into the faction %3$s."), + COMMAND_JOIN_DESCRIPTION("Join a faction"), + COMMAND_JOIN_BANNED("&cYou are banned from %1$s &c:("), + + COMMAND_ALT_OPEN("&eSuccessfully opened %1$s &eto alts with code &d%2$s&e."), + COMMAND_ALT_ALREADYOPEN("%1$s &cis already open to alts with code %2$s."), + COMMAND_ALT_CLOSE("&eSuccessfully closed %1$s &eto new alts."), + COMMAND_ALT_ALREADYCLOSED("%1$s &cis already closed to alts."), + COMMAND_ALT_NOTOPEN("%1$s &cis not open to new alts!"), + COMMAND_ALT_WRONGCODE("%1$s &cis not the correct code for %2$s&c!"), + COMMAND_ALT_SUCCESS("&e%1$s &esuccessfully joined %2$s &eas an alt."), + COMMAND_ALT_USAGE("Faction alt control commands"), + COMMAND_ALT_OPENUSAGE("Open a faction to new alts"), + COMMAND_ALT_CLOSEUSAGE("Close a faction to new alts"), + COMMAND_ALT_JOINUSAGE("Join a faction as an alt"), + + COMMAND_KICK_CANDIDATES("Players you can kick: "), + COMMAND_KICK_CLICKTOKICK("Click to kick "), + COMMAND_KICK_SELF("&cYou cannot kick yourself."), + COMMAND_KICK_NONE("That player is not in a faction."), + COMMAND_KICK_NOTMEMBER("%1$s&c is not a member of %2$s"), + COMMAND_KICK_INSUFFICIENTRANK("&cYour rank is too low to kick this player."), + COMMAND_KICK_NEGATIVEPOWER("&cYou cannot kick that member until their power is positive."), + COMMAND_KICK_TOKICK("to kick someone from the faction"), + COMMAND_KICK_FORKICK("for kicking someone from the faction"), + COMMAND_KICK_FACTION("%1$s&e kicked %2$s&e from the faction! :O"), //message given to faction members + COMMAND_KICK_KICKS("&eYou kicked %1$s&e from the faction %2$s&e!"), //kicker perspective + COMMAND_KICK_KICKED("%1$s&e kicked you from %2$s&e! :O"), //kicked player perspective + COMMAND_KICK_DESCRIPTION("Kick a player from the faction"), + + COMMAND_LIST_FACTIONLIST("Faction List "), + COMMAND_LIST_TOLIST("to list the factions"), + COMMAND_LIST_FORLIST("for listing the factions"), + COMMAND_LIST_ONLINEFACTIONLESS("Online factionless: "), + COMMAND_LIST_DESCRIPTION("See a list of the factions"), + + COMMAND_LISTCLAIMS_MESSAGE("&eClaims by %s&e in %s:"), + COMMAND_LISTCLAIMS_INVALIDWORLD("&cInvalid world name %s"), + COMMAND_LISTCLAIMS_NOCLAIMS("&cNo claims by %s&e in world %s"), + COMMAND_LISTCLAIMS_DESCRIPTION("List your faction's claims"), + + COMMAND_LOCK_LOCKED("&eFactions is now locked"), + COMMAND_LOCK_UNLOCKED("&eFactions in now unlocked"), + COMMAND_LOCK_DESCRIPTION("Lock all write stuff. Apparently."), + + COMMAND_LOGINS_TOGGLE("&eSet login / logout notifications for Faction members to: &6%s"), + COMMAND_LOGINS_DESCRIPTION("Toggle(?) login / logout notifications for Faction members"), + + COMMAND_MAP_TOSHOW("to show the map"), + COMMAND_MAP_FORSHOW("for showing the map"), + COMMAND_MAP_UPDATE_ENABLED("&eMap auto update &2ENABLED."), + COMMAND_MAP_UPDATE_DISABLED("&eMap auto update &4DISABLED."), + COMMAND_MAP_DESCRIPTION("Show the territory map, and set optional auto update"), + + COMMAND_MAPHEIGHT_DESCRIPTION("&eUpdate the lines that /f map sends"), + COMMAND_MAPHEIGHT_SET("&eSet /f map lines to &a%1$d"), + COMMAND_MAPHEIGHT_CURRENT("&eCurrent mapheight: &a%1$d"), + + COMMAND_MOD_CANDIDATES("Players you can promote: "), + COMMAND_MOD_CLICKTOPROMOTE("Click to promote "), + COMMAND_MOD_NOTMEMBER("%1$s&c is not a member in your faction."), + COMMAND_MOD_NOTADMIN("&cYou are not the faction admin."), + COMMAND_MOD_SELF("&cThe target player musn't be yourself."), + COMMAND_MOD_TARGETISADMIN("&cThe target player is a faction admin. Demote them first."), + COMMAND_MOD_REVOKES("&eYou have removed moderator status from %1$s&e."), + COMMAND_MOD_REVOKED("%1$s&e is no longer moderator in your faction."), + COMMAND_MOD_PROMOTES("%1$s&e was promoted to moderator in your faction."), + COMMAND_MOD_PROMOTED("&eYou have promoted %1$s&e to moderator."), + COMMAND_MOD_DESCRIPTION("Give or revoke moderator rights"), + + COMMAND_MODIFYPOWER_ADDED("&eAdded &6%1$f &epower to &6%2$s. &eNew total rounded power: &6%3$d"), + COMMAND_MODIFYPOWER_DESCRIPTION("Modify the power of a faction/player"), + + COMMAND_MONEY_LONG("&eThe faction money commands."), + COMMAND_MONEY_DESCRIPTION("Faction money commands"), + + COMMAND_MONEYBALANCE_SHORT("show faction balance"), + COMMAND_MONEYBALANCE_DESCRIPTION("Show your factions current money balance"), + + COMMAND_MONEYDEPOSIT_DESCRIPTION("Deposit money"), + COMMAND_MONEYDEPOSIT_DEPOSITED("%1$s deposited %2$s in the faction bank: %3$s"), + + COMMAND_MONEYTRANSFERFF_DESCRIPTION("Transfer f -> f"), + COMMAND_MONEYTRANSFERFF_TRANSFER("%1$s transferred %2$s from the faction \"%3$s\" to the faction \"%4$s\""), + + COMMAND_MONEYTRANSFERFP_DESCRIPTION("Transfer f -> p"), + COMMAND_MONEYTRANSFERFP_TRANSFER("%1$s transferred %2$s from the faction \"%3$s\" to the player \"%4$s\""), + + COMMAND_MONEYTRANSFERPF_DESCRIPTION("Transfer p -> f"), + COMMAND_MONEYTRANSFERPF_TRANSFER("%1$s transferred %2$s from the player \"%3$s\" to the faction \"%4$s\""), + + COMMAND_MONEYWITHDRAW_DESCRIPTION("Withdraw money"), + COMMAND_MONEYWITHDRAW_WITHDRAW("%1$s withdrew %2$s from the faction bank: %3$s"), + + COMMAND_NEAR_DESCRIPTION("Show nearby faction members"), + COMMAND_NEAR_PLAYER("&a&l{role-prefix}&8{name} (&d{distance}m&8)"), + COMMAND_NEAR_PLAYERLIST("&eNear: {players-nearby}"), + COMMAND_NEAR_NONE("&8None"), + + COMMAND_OPEN_TOOPEN("to open or close the faction"), + COMMAND_OPEN_FOROPEN("for opening or closing the faction"), + COMMAND_OPEN_OPEN("open"), + COMMAND_OPEN_CLOSED("closed"), + COMMAND_OPEN_CHANGES("%1$s&e changed the faction to &d%2$s&e."), + COMMAND_OPEN_CHANGED("&eThe faction %1$s&e is now %2$s"), + COMMAND_OPEN_DESCRIPTION("Switch if invitation is required to join"), + + COMMAND_OWNER_DISABLED("&cSorry, but owned areas are disabled on this server."), + COMMAND_OWNER_LIMIT("&cSorry, but you have reached the server's &dlimit of %1$d &cowned areas per faction."), + COMMAND_OWNER_WRONGFACTION("&cThis land is not claimed by your faction, so you can't set ownership of it."), + COMMAND_OWNER_NOTCLAIMED("&cThis land is not claimed by a faction. Ownership is not possible."), + COMMAND_OWNER_NOTMEMBER("%1$s&e is not a member of this faction."), + COMMAND_OWNER_CLEARED("&eYou have cleared ownership for this claimed area."), + COMMAND_OWNER_REMOVED("&eYou have removed ownership of this claimed land from %1$s&e."), + COMMAND_OWNER_TOSET("to set ownership of claimed land"), + COMMAND_OWNER_FORSET("for setting ownership of claimed land"), + COMMAND_OWNER_ADDED("&eYou have added %1$s&e to the owner list for this claimed land."), + COMMAND_OWNER_DESCRIPTION("Set ownership of claimed land"), + + COMMAND_OWNERLIST_DISABLED("&cSorry, but owned areas are disabled on this server."),//dup-> + COMMAND_OWNERLIST_WRONGFACTION("&cThis land is not claimed by your faction."),//eq + COMMAND_OWNERLIST_NOTCLAIMED("&eThis land is not claimed by any faction, thus no owners."),//eq + COMMAND_OWNERLIST_NONE("&eNo owners are set here; everyone in the faction has access."), + COMMAND_OWNERLIST_OWNERS("&eCurrent owner(s) of this land: %1$s"), + COMMAND_OWNERLIST_DESCRIPTION("List owner(s) of this claimed land"), + + COMMAND_PEACEFUL_DESCRIPTION("Set a faction to peaceful"), + COMMAND_PEACEFUL_YOURS("%1$s has %2$s your faction"), + COMMAND_PEACEFUL_OTHER("%s&e has %s the faction '%s&e'."), + COMMAND_PEACEFUL_GRANT("granted peaceful status to"), + COMMAND_PEACEFUL_REVOKE("removed peaceful status from"), + + COMMAND_PERM_DESCRIPTION("&6Edit or list your Faction's permissions."), + COMMAND_PERM_INVALID_RELATION("Invalid relation defined. Try something like 'ally'"), + COMMAND_PERM_INVALID_ACCESS("Invalid access defined. Try something like 'allow'"), + COMMAND_PERM_INVALID_ACTION("Invalid action defined. Try something like 'build'"), + COMMAND_PERM_SET("&aSet permission &e%1$s &ato &b%2$s &afor relation &c%3$s"), + COMMAND_PERM_INVALID_SET("&cCannot set a locked permission"), + COMMAND_PERM_TOP("RCT MEM OFF ALLY TRUCE NEUT ENEMY"), + + COMMAND_PERMANENT_DESCRIPTION("Toggles a faction's permanence"), + COMMAND_PERMANENT_GRANT("added permanent status to"), + COMMAND_PERMANENT_REVOKE("removed permanent status from"), + COMMAND_PERMANENT_YOURS("%1$s has %2$s your faction"), + COMMAND_PERMANENT_OTHER("%s&e has %s the faction '%s&e'."), + COMMAND_PROMOTE_TARGET("You've been %1$s to %2$s"), + COMMAND_PROMOTE_ISALT("That player is an alt!"), + COMMAND_PROMOTE_SUCCESS("You successfully %1$s %2$s to %3$s"), + COMMAND_PROMOTE_PROMOTED("promoted"), + COMMAND_PROMOTE_DEMOTED("demoted"), + + COMMAND_PERMANENTPOWER_DESCRIPTION("Toggle faction power permanence"), + COMMAND_PERMANENTPOWER_GRANT("added permanentpower status to"), + COMMAND_PERMANENTPOWER_REVOKE("removed permanentpower status from"), + COMMAND_PERMANENTPOWER_SUCCESS("&eYou %s &d%s&e."), + COMMAND_PERMANENTPOWER_FACTION("%s&e %s your faction"), + + COMMAND_PROMOTE_DESCRIPTION("/f promote "), + COMMAND_PROMOTE_WRONGFACTION("%1$s is not part of your faction."), + COMMAND_NOACCESS("You don't have access to that."), + COMMAND_PROMOTE_NOTTHATPLAYER("That player cannot be promoted."), + COMMAND_PROMOTE_NOT_ALLOWED("You can't promote or demote that player."), + + COMMAND_POWER_TOSHOW("to show player power info"), + COMMAND_POWER_FORSHOW("for showing player power info"), + COMMAND_POWER_POWER("%1$s&6 - Power / Maxpower: &e%2$d / %3$d %4$s"), + COMMAND_POWER_BONUS(" (bonus: "), + COMMAND_POWER_PENALTY(" (penalty: "), + COMMAND_POWER_DESCRIPTION("Show player power info"), + + COMMAND_POWERBOOST_HELP_1("&cYou must specify \"p\" or \"player\" to target a player or \"f\" or \"faction\" to target a faction."), + COMMAND_POWERBOOST_HELP_2("&cex. /f powerboost p SomePlayer 0.5 -or- /f powerboost f SomeFaction -5"), + COMMAND_POWERBOOST_INVALIDNUM("&cYou must specify a valid numeric value for the power bonus/penalty amount."), + COMMAND_POWERBOOST_PLAYER("Player \"%1$s\""), + COMMAND_POWERBOOST_FACTION("Faction \"%1$s\""), + COMMAND_POWERBOOST_BOOST("&e%1$s now has a power bonus/penalty of %2$d to min and max power levels."), + COMMAND_POWERBOOST_BOOSTLOG("%1$s has set the power bonus/penalty for %2$s to %3$d."), + COMMAND_POWERBOOST_DESCRIPTION("Apply permanent power bonus/penalty to specified player or faction"), + + COMMAND_RELATIONS_ALLTHENOPE("&cNope! You can't."), + COMMAND_RELATIONS_MORENOPE("&cNope! You can't declare a relation to yourself :)"), + COMMAND_RELATIONS_ALREADYINRELATIONSHIP("&cYou already have that relation wish set with %1$s."), + COMMAND_RELATIONS_TOMARRY("to change a relation wish"), + COMMAND_RELATIONS_FORMARRY("for changing a relation wish"), + COMMAND_RELATIONS_MUTUAL("&eYour faction is now %1$s&e to %2$s"), + COMMAND_RELATIONS_PEACEFUL("&eThis will have no effect while your faction is peaceful."), + COMMAND_RELATIONS_PEACEFULOTHER("&eThis will have no effect while their faction is peaceful."), + COMMAND_RELATIONS_DESCRIPTION("Set relation wish to another faction"), + COMMAND_RELATIONS_EXCEEDS_ME("&eFailed to set relation wish. You can only have %1$s %2$s."), + COMMAND_RELATIONS_EXCEEDS_THEY("&eFailed to set relation wish. They can only have %1$s %2$s."), + + COMMAND_RELATIONS_PROPOSAL_1("%1$s&e wishes to be your %2$s"), + COMMAND_RELATIONS_PROPOSAL_2("&eType &b/%1$s %2$s %3$s&e to accept."), + COMMAND_RELATIONS_PROPOSAL_SENT("%1$s&e were informed that you wish to be %2$s"), + + COMMAND_RELOAD_TIME("&eReloaded &dall configuration files &efrom disk, took &d%1$d ms&e."), + COMMAND_RELOAD_DESCRIPTION("Reload data file(s) from disk"), + + COMMAND_ROSTER_USAGE("Control your faction's roster"), + COMMAND_ROSTER_ROTATE_FULL("You can't rotate into your faction! There isn't enough room!"), + COMMAND_ROSTER_ROTATE_SUCCESS("%1$s &erotated into %2$s&e."), + COMMAND_ROSTER_ROTATE_OUT("%1$s &ewas rotated out of %2$s&e."), + COMMAND_ROSTER_JOIN("%1$s &ejoined %2$s&e's roster."), + + COMMAND_ROSTER_LIST_USAGE("List your faction's roster"), + COMMAND_ROSTER_LIST_NOROSTER("&cYou aren't on a roster"), + COMMAND_ROSTER_LIST_HEADER("%1$s&e's roster"), + COMMAND_ROSTER_LIST_FORMAT("&e<&d!&e> %1$s &8- &e%2$s"), + + COMMAND_ROSTER_HELP_USAGE("View info about how rosters work"), + COMMAND_ROSTER_HELP_USED("&eRosters are very simple on this server!\n" + + "&8&m------------------------------------------------\n" + + "&eInvite players using the &d/f invite &ecommand and they'll be automatically added to your roster when they use &d/f join&e.\n" + + "&8&m------------------------------------------------\n" + + "&eRotations are done via the &d/f join &ecommand as well.\n" + + "&eSimply type &d/f join (your-faction)&e and you will be automatically rotated into your current roster.\n" + + "&8&m------------------------------------------------\n" + + "&eManaging your roster is easy as well.\n" + + "&eIf you would like to &cremove &esomeone from your roster, just use the &d/f kick &ecommand!\n" + + "&ePromotions are handled as if the player were in your faction as well, just use the &d/f promote&e command!"), + + COMMAND_STRIKE_LIST_USAGE("List a faction's strikes"), + COMMAND_STRIKE_LIST_NOFACTION("&cYou need to specify a faction!"), + COMMAND_STRIKE_LIST_HEADER("%1$s&e's strike info:"), + COMMAND_STRIKE_LIST_FORMAT("&e<&d%1$s&e> %2$s &8- &e%3$s"), + COMMAND_STRIKE_LIST_BLAMELESS("%1$s &ehasn't been striked."), + + COMMAND_STRIKE_GIVE_USAGE("Give a faction a strike... They broke the rules!"), + COMMAND_STRIKE_GIVE_SUCCESS("&eGiven %1$s &ea strike for &d%2$s"), + + COMMAND_STRIKE_TAKE_USAGE("Take a strike from a faction... We're sorry :("), + COMMAND_STRIKE_TAKE_DOESNTEXIST("&cThat strike doesn't exist! Try a different index."), + COMMAND_STRIKE_TAKE_SUCCESS("&eRemoved a strike from %1$s&e."), + + COMMAND_STRIKE_USAGE("Strike commands for factions"), + + COMMAND_MISSIONS_USAGE("View and manage missions"), + + COMMAND_ROSTER_LEAVE_CONFIRM("&cAre you sure you want to leave your faction? Roster rotations are done automatically! Leaving your faction will remove you from your roster."), + + COMMAND_SAFEUNCLAIMALL_DESCRIPTION("Unclaim all safe zone land"), + COMMAND_SAFEUNCLAIMALL_UNCLAIMED("&eYou unclaimed ALL safe zone land."), + COMMAND_SAFEUNCLAIMALL_UNCLAIMEDLOG("%1$s unclaimed all safe zones."), + + COMMAND_SAVEALL_SUCCESS("&eFactions saved to disk!"), + COMMAND_SAVEALL_DESCRIPTION("Save all data to disk"), + + COMMAND_SCOREBOARD_DESCRIPTION("Scoreboardy things"), + + COMMAND_SETDEFAULTROLE_DESCRIPTION("/f defaultrole - set your Faction's default role."), + COMMAND_SETDEFAULTROLE_NOTTHATROLE("You cannot set the default to admin."), + COMMAND_SETDEFAULTROLE_SUCCESS("Set default role of your faction to %1$s"), + COMMAND_SETDEFAULTROLE_INVALIDROLE("Couldn't find matching role for %1$s"), + + COMMAND_SETFWARP_NOTCLAIMED("&eYou can only set warps in your faction territory."), + COMMAND_SETFWARP_LIMIT("&eYour Faction already has the max amount of warps set &6(%1$d)."), + COMMAND_SETFWARP_SET("&eSet warp &6%1$s&e and password &b'%2$s' &eto your location."), + COMMAND_SETFWARP_TOSET("to set warp"), + COMMAND_SETFWARP_FORSET("for setting warp"), + COMMAND_SETFWARP_DESCRIPTION("Set a faction warp"), + + COMMAND_SETHOME_DISABLED("&cSorry, Faction homes are disabled on this server."), + COMMAND_SETHOME_NOTCLAIMED("&cSorry, your faction home can only be set inside your own claimed territory."), + COMMAND_SETHOME_TOSET("to set the faction home"), + COMMAND_SETHOME_FORSET("for setting the faction home"), + COMMAND_SETHOME_SET("%1$s&e set the home for your faction. You can now use:"), + COMMAND_SETHOME_SETOTHER("&cYou have set the home for the %1$s&e faction."), + COMMAND_SETHOME_DESCRIPTION("Set the faction home"), + + COMMAND_SETMAXVAULTS_DESCRIPTION("Set max vaults for a Faction."), + COMMAND_SETMAXVAULTS_SUCCESS("&aSet max vaults for &e%s &ato &b%d"), + + COMMAND_SETPAYPAL_DESCRIPTION("Set paypal for your faction"), + COMMAND_SETPAYPAL_NOTADMIN("&cYou must be a faction admin to setpaypal."), + COMMAND_SETPAYPAL_NOTVALID("&c%1$s isn't a valid email address!"), + COMMAND_SETPAYPAL_SUCCESS("&eSet &ayour faction&e's paypal link to &c%1$s&e."), + + COMMAND_SEEPAYPAL_DESCRIPTION("Set paypal for your faction"), + COMMAND_SEEPAYPAL_ISNTSET("%1$s&e's paypal link has not been set."), + COMMAND_SEEPAYPAL_SEE("%1$s's paypal link is &a%2$s"), + + COMMAND_TNT_TERRITORYONLY("&cCommand can only be run from your faction's territory!"), + COMMAND_TNT_ADMINSET_USAGE("&cSet tnt as an admin!"), + COMMAND_TNT_ADMINSET_DESCRIPTION("&eSet %1$s&e's tnt to &c%2$s&&e."), + COMMAND_TNT_DEPOSIT_DESCRIPTION("Add to your faction's TNT bank"), + COMMAND_TNT_DEPOSIT_FAIL_FULL("&cFaction bank already at maximum!"), + COMMAND_TNT_DEPOSIT_FAIL_NOTENOUGH("&cYou do not have that much TNT!"), + COMMAND_TNT_DEPOSIT_FAIL_POSITIVE("&cMust deposit at least one!"), + COMMAND_TNT_DEPOSIT_SUCCESS("&eYour faction now has %d TNT"), + COMMAND_TNT_FILL_DESCRIPTION("Fill TNT into nearby dispensers"), + COMMAND_TNT_FILL_MESSAGE("&eFilled %d TNT into %d dispensers. %d left in the faction bank."), + COMMAND_TNT_FILL_FAIL_MAXRADIUS("&c%d is bigger than the maximum radius of %d"), + COMMAND_TNT_FILL_FAIL_NOTENOUGH("&cThe faction bank does not have %d TNT!"), + COMMAND_TNT_FILL_FAIL_NEEDMORE("&cYou would need %d tnt to fill that many dispensers! The most you can do is %d per!"), + COMMAND_TNT_FILL_FAIL_POSITIVE("&cPositive values only!"), + COMMAND_TNT_INFO_DESCRIPTION("View your faction's TNT bank"), + COMMAND_TNT_INFO_MESSAGE("&eYour faction has &c%1$s &eout of &c%2$s &eTNT."), + COMMAND_TNT_SIPHON_DESCRIPTION("Take TNT from nearby dispensers"), + COMMAND_TNT_SIPHON_MESSAGE("&eAcquired %d TNT, for a total of %d in the faction bank."), + COMMAND_TNT_SIPHON_FAIL_POSITIVE("&cPositive values only!"), + COMMAND_TNT_SIPHON_FAIL_FULL("&cFaction bank already at maximum!"), + COMMAND_TNT_SIPHON_FAIL_MAXRADIUS("&c%d is bigger than the maximum radius of %d"), + COMMAND_TNT_WITHDRAW_DESCRIPTION("Withdraw TNT from the faction bank"), + COMMAND_TNT_WITHDRAW_MESSAGE("&eWithdrew %d TNT. %d left in the faction bank."), + COMMAND_TNT_WITHDRAW_FAIL_NOTENOUGH("&cThe faction bank does not have %d TNT!"), + COMMAND_TNT_WITHDRAW_FAIL_POSITIVE("&cPositive values only!"), + + COMMAND_UPGRADE_NOT_ENOUGH("&cYou don't have enough money to upgrade that!"), + COMMAND_UPGRADE_ALREADY_MAX("&cThat is already maxed out!"), + COMMAND_UPGRADE_SUCCESSFUL("&eSuccessfully upgraded &d%1$s &eto level &d%2$s&e."), + COMMAND_UPGRADE_DESCRIPTION("Upgrade your faction"), + + COMMAND_VAULT_DESCRIPTION("/f vault to open one of your Faction's vaults."), + COMMAND_VAULT_TOOHIGH("&cYou tried to open vault %d but your Faction only has %d vaults."), + + COMMAND_SEECHUNK_DESCRIPTION("Show chunk boundaries"), + COMMAND_SEECHUNK_TOGGLE("&eSeechunk &d%1$s"), + + COMMAND_SHOW_NOFACTION_SELF("You are not in a faction"), + COMMAND_SHOW_NOFACTION_OTHER("That's not a faction"), + COMMAND_SHOW_TOSHOW("to show faction information"), + COMMAND_SHOW_FORSHOW("for showing faction information"), + COMMAND_SHOW_DESCRIPTION("&6Description: &e%1$s"), + COMMAND_SHOW_PEACEFUL("This faction is Peaceful"), + COMMAND_SHOW_PERMANENT("&6This faction is permanent, remaining even with no members."), + COMMAND_SHOW_JOINING("&6Joining: &e%1$s "), + COMMAND_SHOW_INVITATION("invitation is required"), + COMMAND_SHOW_UNINVITED("no invitation is needed"), + COMMAND_SHOW_NOHOME("n/a"), + COMMAND_SHOW_POWER("&6Land / Power / Maxpower: &e %1$d/%2$d/%3$d %4$s."), + COMMAND_SHOW_BONUS(" (bonus: "), + COMMAND_SHOW_PENALTY(" (penalty: "), + COMMAND_SHOW_DEPRECIATED("(%1$s depreciated)"), //This is spelled correctly. + COMMAND_SHOW_LANDVALUE("&6Total land value: &e%1$s %2$s"), + COMMAND_SHOW_BANKCONTAINS("&6Bank contains: &e%1$s"), + COMMAND_SHOW_ALLIES("Allies: "), + COMMAND_SHOW_ENEMIES("Enemies: "), + COMMAND_SHOW_MEMBERSONLINE("Members online: "), + COMMAND_SHOW_MEMBERSOFFLINE("Members offline: "), + COMMAND_SHOW_COMMANDDESCRIPTION("Show faction information"), + COMMAND_SHOW_DEATHS_TIL_RAIDABLE("&eDTR: %1$d"), + COMMAND_SHOW_EXEMPT("&cThis faction is exempt and cannot be seen."), + + COMMAND_SHOWINVITES_PENDING("Players with pending invites: "), + COMMAND_SHOWINVITES_CLICKTOREVOKE("Click to revoke invite for %1$s"), + COMMAND_SHOWINVITES_DESCRIPTION("Show pending faction invites"), + + COMMAND_STATUS_FORMAT("%1$s Power: %2$s Last Seen: %3$s"), + COMMAND_STATUS_ONLINE("Online"), + COMMAND_STATUS_AGOSUFFIX(" ago."), + COMMAND_STATUS_DESCRIPTION("Show the status of a player"), + + COMMAND_STEALTH_DESCRIPTION("Toggles stealth mode"), + COMMAND_STEALTH_TOGGLE("&7Stealth mode has been &a%1$s"), + + COMMAND_STUCK_TIMEFORMAT("m 'minutes', s 'seconds.'"), + COMMAND_STUCK_CANCELLED("&6Teleport cancelled because you were damaged"), + COMMAND_STUCK_OUTSIDE("&6Teleport cancelled because you left &e%1$d &6block radius"), + COMMAND_STUCK_EXISTS("&6You are already teleporting, you must wait &e%1$s"), + COMMAND_STUCK_START("&6Teleport will commence in &e%s&6. Don't take or deal damage. "), + COMMAND_STUCK_TELEPORT("&6Teleported safely to %1$d, %2$d, %3$d."), + COMMAND_STUCK_TOSTUCK("to safely teleport %1$s out"), + COMMAND_STUCK_FORSTUCK("for %1$s initiating a safe teleport out"), + COMMAND_STUCK_DESCRIPTION("Safely teleports you out of enemy faction"), + + COMMAND_TAG_TAKEN("&cThat tag is already taken"), + COMMAND_TAG_TOCHANGE("to change the faction tag"), + COMMAND_TAG_FORCHANGE("for changing the faction tag"), + COMMAND_TAG_FACTION("%1$s&e changed your faction tag to %2$s"), + COMMAND_TAG_CHANGED("&eThe faction %1$s&e changed their name to %2$s."), + COMMAND_TAG_DESCRIPTION("Change the faction tag"), + + COMMAND_TITLE_TOCHANGE("to change a players title"), + COMMAND_TITLE_FORCHANGE("for changing a players title"), + COMMAND_TITLE_CHANGED("%1$s&e changed a title: %2$s"), + COMMAND_TITLE_DESCRIPTION("Set or remove a players title"), + + COMMAND_TOGGLEALLIANCECHAT_DESCRIPTION("Toggles whether or not you will see alliance chat"), + COMMAND_TOGGLEALLIANCECHAT_IGNORE("Alliance chat is now ignored"), + COMMAND_TOGGLEALLIANCECHAT_UNIGNORE("Alliance chat is no longer ignored"), + + COMMAND_TOGGLESB_DISABLED("You can't toggle scoreboards while they are disabled."), + + COMMAND_TOP_DESCRIPTION("Sort Factions to see the top of some criteria."), + COMMAND_TOP_TOP("Top Factions by %s. Page %d/%d"), + COMMAND_TOP_LINE("%d. &6%s: &c%s"), // Rank. Faction: Value + COMMAND_TOP_INVALID("Could not sort by %s. Try balance, online, members, power or land."), + + COMMAND_UNBAN_DESCRIPTION("Unban someone from your Faction"), + COMMAND_UNBAN_NOTBANNED("&7%s &cisn't banned. Not doing anything."), + COMMAND_UNBAN_UNBANNED("&e%1$s &cunbanned &7%2$s"), + COMMAND_UNBAN_TARGET("&aYou were unbanned from &r%s"), + + COMMAND_UNCLAIM_SAFEZONE_SUCCESS("&eSafe zone was unclaimed."), + COMMAND_UNCLAIM_SAFEZONE_NOPERM("&cThis is a safe zone. You lack permissions to unclaim."), + COMMAND_UNCLAIM_WARZONE_SUCCESS("&eWar zone was unclaimed."), + COMMAND_UNCLAIM_WARZONE_NOPERM("&cThis is a war zone. You lack permissions to unclaim."), + COMMAND_UNCLAIM_UNCLAIMED("%1$s&e unclaimed some of your land."), + COMMAND_UNCLAIM_UNCLAIMEDAMOUNT("%1$s&e unclaimed &d%2$s &eland."), + COMMAND_UNCLAIM_UNCLAIMS("&eYou unclaimed this land."), + COMMAND_UNCLAIM_WRONGFACTIONOTHER("&cAttempted to unclaim land for incorrect faction"), + COMMAND_UNCLAIM_LOG("%1$s unclaimed land at (%2$s) from the faction: %3$s"), + COMMAND_UNCLAIM_WRONGFACTION("&cYou don't own this land."), + COMMAND_UNCLAIM_TOUNCLAIM("to unclaim this land"), + COMMAND_UNCLAIM_FORUNCLAIM("for unclaiming this land"), + COMMAND_UNCLAIM_FACTIONUNCLAIMED("%1$s&e unclaimed some land."), + COMMAND_UNCLAIM_DESCRIPTION("Unclaim the land where you are standing"), + + COMMAND_UNCLAIMALL_TOUNCLAIM("to unclaim all faction land"), + COMMAND_UNCLAIMALL_FORUNCLAIM("for unclaiming all faction land"), + COMMAND_UNCLAIMALL_UNCLAIMED("%1$s&e unclaimed ALL of your faction's land."), + COMMAND_UNCLAIMALL_LOG("%1$s unclaimed everything for the faction: %2$s"), + COMMAND_UNCLAIMALL_DESCRIPTION("Unclaim all of your factions land"), + + COMMAND_VERSION_VERSION("&eYou are running %1$s"), + COMMAND_VERSION_DESCRIPTION("Show plugin and translation version information"), + + COMMAND_CORNER_DESCRIPTION("Claim an entire corner for your faction"), + COMMAND_CORNER_MUSTBEINCORNER("&cYou must be standing in a corner to use this command!"), + COMMAND_CORNER_ISNTSOTW("&cYou can only claim a corner during SOTW!"), + COMMAND_CORNER_SUCCESS("&eSuccessfully claimed this corner for &ayour faction&e!"), + COMMAND_CORNER_MUSTOWN("&cYou must own the corner to claim it!"), + + COMMAND_WARUNCLAIMALL_DESCRIPTION("Unclaim all war zone land"), + COMMAND_WARUNCLAIMALL_SUCCESS("&eYou unclaimed ALL war zone land."), + COMMAND_WARUNCLAIMALL_LOG("%1$s unclaimed all war zones."), + + + /** + * Leaving - This is accessed through a command, and so it MAY need a COMMAND_* slug :s + */ + LEAVE_PASSADMIN("&cYou must give the admin role to someone else first."), + LEAVE_NEGATIVEPOWER("&cYou cannot leave until your power is positive."), + LEAVE_TOLEAVE("to leave your faction."), + LEAVE_FORLEAVE("for leaving your faction."), + LEAVE_LEFT("%s&e left faction %s&e."), + LEAVE_DISBANDED("&e%s&e was disbanded."), + LEAVE_DISBANDEDLOG("The faction %s (%s) was disbanded due to the last player (%s) leaving."), + LEAVE_DESCRIPTION("Leave your faction"), + + /** + * Claiming - Same as above basically. No COMMAND_* because it's not in a command class, but... + */ + CLAIM_PROTECTED("&cThis land is protected"), + CLAIM_DISABLED("&cSorry, this world has land claiming disabled."), + CLAIM_CANTCLAIM("&cYou can't claim land for &d%s&c."), + CLAIM_ALREADYOWN("%s&e already own this land."), + CLAIM_MUSTBE("&cYou must be &d%s&c to claim land."), + CLAIM_MEMBERS("Factions must have at least &d%s&c members to claim land."), + CLAIM_SAFEZONE("&cYou can not claim a safe zone."), + CLAIM_WARZONE("&cYou can not claim a war zone."), + CLAIM_POWER("&cYou can't claim more land! You need more power!"), + CLAIM_DTR_LAND("&cYou can't claim more land!"), + CLAIM_LIMIT("&cLimit reached. You can't claim more land!"), + CLAIM_ALLY("&cYou can't claim the land of your allies."), + CLAIM_CONTIGIOUS("&cYou can only claim additional land which is connected to your first claim or controlled by another faction!"), + CLAIM_FACTIONCONTIGUOUS("&cYou can only claim additional land which is connected to your first claim!"), + CLAIM_PEACEFUL("%s&e owns this land. Your faction is peaceful, so you cannot claim land from other factions."), + CLAIM_PEACEFULTARGET("%s&e owns this land, and is a peaceful faction. You cannot claim land from them."), + CLAIM_THISISSPARTA("%s&e owns this land and is strong enough to keep it."), + CLAIM_BORDER("&cYou must start claiming land at the border of the territory."), + CLAIM_TOCLAIM("to claim this land"), + CLAIM_FORCLAIM("for claiming this land"), + CLAIM_TOOVERCLAIM("to overclaim this land"), + CLAIM_FOROVERCLAIM("for over claiming this land"), + CLAIM_CLAIMED("&d%s&e claimed land for &d%s&e from &d%s&e."), + CLAIM_CLAIMEDAMOUNT("&d%s&e claimed &d%s &eland for &d%s&e."), + CLAIM_CLAIMEDLOG("%s claimed land at (%s) for the faction: %s | in world %s"), + CLAIM_OVERCLAIM_DISABLED("&eOver claiming is disabled on this server."), + CLAIM_TOOCLOSETOOTHERFACTION("&eYour claim is too close to another Faction. Buffer required is %d"), + CLAIM_OUTSIDEWORLDBORDER("&eYour claim is outside the border."), + CLAIM_OUTSIDEBORDERBUFFER("&eYour claim is outside the border. %d chunks away world edge required."), + CLAIM_CLICK_TO_CLAIM("Click to try to claim &2(%1$d, %2$d)"), + CLAIM_YOUAREHERE("You are here"), + + /** + * More generic, or less easily categorisable translations, which may apply to more than one class + */ + GENERIC_YOU("you"), + GENERIC_YOURFACTION("your faction"), + GENERIC_NOPERMISSION("&cYou don't have permission to %1$s."), + GENERIC_DOTHAT("do that"), //Ugh nuke this from high orbit + GENERIC_NOPLAYERMATCH("&cNo player match found for \"&3%1$s&c\"."), + GENERIC_NOPLAYERFOUND("&cNo player \"&3%1$s&c\" could not be found."), + GENERIC_NOFACTIONMATCH("&cNo faction match found for \"&3%1$s&c\"."), + GENERIC_ARGS_TOOFEW("&cToo few arguments. &eUse like this:"), + GENERIC_ARGS_TOOMANY("&cStrange argument \"&3%1$s&c\". &eUse the command like this:"), + GENERIC_DEFAULTDESCRIPTION("Default faction description :("), + GENERIC_OWNERS("Owner(s): %1$s"), + GENERIC_PUBLICLAND("Public faction land."), + GENERIC_FACTIONLESS("factionless"), + GENERIC_SERVERADMIN("A server admin"), + GENERIC_DISABLED("disabled"), + GENERIC_ENABLED("enabled"), + GENERIC_INFINITY("∞"), + GENERIC_CONSOLEONLY("This command cannot be run as a player."), + GENERIC_PLAYERONLY("&cThis command can only be used by ingame players."), + GENERIC_MEMBERONLY("&cYou are not member of any faction."), + GENERIC_ASKYOURLEADER("&e Ask your leader to:"), + GENERIC_YOUSHOULD("&eYou should:"), + GENERIC_YOUMAYWANT("&eYou may want to: "), + GENERIC_DISABLEDWORLD("&cFactions is disabled in this world."), + GENERIC_YOUMUSTBE("&cYou must be &d%s&c."), + GENERIC_TRANSLATION_VERSION("Translation: %1$s(%2$s,%3$s) State: %4$s"), + GENERIC_TRANSLATION_CONTRIBUTORS("Translation contributors: %1$s"), + GENERIC_TRANSLATION_RESPONSIBLE("Responsible for translation: %1$s"), + GENERIC_FACTIONTAG_BLACKLIST("&eThat faction tag is blacklisted."), + GENERIC_FACTIONTAG_TOOSHORT("&eThe faction tag can't be shorter than &d%1$s&e chars."), + GENERIC_FACTIONTAG_TOOLONG("&eThe faction tag can't be longer than &d%s&e chars."), + GENERIC_FACTIONTAG_ALPHANUMERIC("&eFaction tag must be alphanumeric. \"&d%s&e\" is not allowed."), + GENERIC_PLACEHOLDER(""), + + /** + * Clip placeholder stuff + */ + PLACEHOLDER_ROLE_NAME("None"), + PLACEHOLDER_CUSTOM_FACTION("{faction} "), + + /** + * ASCII compass (for chat map) + */ + COMPASS_SHORT_NORTH("N"), + COMPASS_SHORT_EAST("E"), + COMPASS_SHORT_SOUTH("S"), + COMPASS_SHORT_WEST("W"), + + /** + * Chat modes + */ + CHAT_MOD("mod chat"), + CHAT_FACTION("faction chat"), + CHAT_ALLIANCE("alliance chat"), + CHAT_TRUCE("truce chat"), + CHAT_PUBLIC("public chat"), + + /** + * Economy stuff + */ + + ECON_OFF("no %s"), // no balance, no value, no refund, etc + ECON_FORMAT("###,###.###"), + ECON_DISABLED("Faction econ is disabled."), + ECON_OVER_BAL_CAP("&4The amount &e%s &4is over Essentials' balance cap."), + ECON_BALANCE("&6%s's&e balance is &d%s&e."), + ECON_NOPERM("&d%s&e lacks permission to control &d%s's&e money."), + ECON_CANTAFFORD_TRANSFER("&d%s can't afford to transfer &d%s to %s."), + ECON_CANTAFFORD_AMOUNT("&d%s&e can't afford &d%s&e %s."), + ECON_TRANSFER_UNABLE("Unable to transfer %s to &d%s from &d%s."), + ECON_TRANSFER_NOINVOKER("&d%s&e was transferred from &d%s&e to &d%s&e."), + ECON_TRANSFER_GAVE("&d%s&e &dgave %s&e to &d%s&e."), + ECON_TRANSFER_TOOK("&d%s&e &dtook %s&e from &d%s&e."), + ECON_TRANSFER_TRANSFER("&d%s&e transferred &d%s&e from &d%s&e to &d%s&e."), + ECON_GAIN_SUCCESS("&d%s&e gained &d%s&e %s."), + ECON_GAIN_FAILURE("&d%s&e would have gained &d%s&e %s, but the deposit failed."), + ECON_LOST_SUCCESS("&d%s&e lost &d%s&e %s."), + ECON_LOST_FAILURE("&d%s&e can't afford &d%s&e %s."), + + /** + * Relations + */ + RELATION_MEMBER_SINGULAR("member"), + RELATION_MEMBER_PLURAL("members"), + RELATION_ALLY_SINGULAR("ally"), + RELATION_ALLY_PLURAL("allies"), + RELATION_TRUCE_SINGULAR("truce"), + RELATION_TRUCE_PLURAL("truces"), + RELATION_NEUTRAL_SINGULAR("neutral"), + RELATION_NEUTRAL_PLURAL("neutrals"), + RELATION_ENEMY_SINGULAR("enemy"), + RELATION_ENEMY_PLURAL("enemies"), + + /** + * Roles + */ + ROLE_ADMIN("admin"), + ROLE_COLEADER("coleader"), + ROLE_MODERATOR("moderator"), + ROLE_NORMAL("normal member"), + ROLE_RECRUIT("recruit"), + ROLE_ALT("alt"), + + /** + * Region types. + */ + REGION_SAFEZONE("safezone"), + REGION_WARZONE("warzone"), + REGION_WILDERNESS("wilderness"), + + REGION_PEACEFUL("peaceful territory"), + /** + * In the player and entity listeners + */ + PLAYER_CANTADDTHATITEM("&cYou cant put that item in your f chest!"), + PLAYER_CANTHURT("&eYou may not harm other players in %s"), + PLAYER_SAFEAUTO("&eThis land is now a safe zone."), + PLAYER_WARAUTO("&eThis land is now a war zone."), + PLAYER_OUCH("&cOuch, that is starting to hurt. You should give it a rest."), + PLAYER_USE_WILDERNESS("&cYou can't use &d%s&c in the wilderness."), + PLAYER_USE_SAFEZONE("&cYou can't use &d%s&c in a safe zone."), + PLAYER_USE_WARZONE("&cYou can't use &d%s&c in a war zone."), + PLAYER_USE_TERRITORY("&cYou can't &d%s&c in the territory of &d%s&c."), + PLAYER_USE_OWNED("&cYou can't use &d%s&c in this territory, it is owned by: %s&c."), + PLAYER_COMMAND_WARZONE("&cYou can't use the command '%s' in war zone."), + PLAYER_COMMAND_NEUTRAL("&cYou can't use the command '%s' in neutral territory."), + PLAYER_COMMAND_ENEMY("&cYou can't use the command '%s' in enemy territory."), + PLAYER_COMMAND_PERMANENT("&cYou can't use the command '%s' because you are in a permanent faction."), + PLAYER_COMMAND_ALLY("&cYou can't use the command '%s' in ally territory."), + PLAYER_COMMAND_WILDERNESS("&cYou can't use the command '%s' in the wilderness."), + PLAYER_SOTW_NOFLY("&cYou cannot fly during SOTW!"), + + PLAYER_PORTAL_NOTALLOWED("&cDestination portal can't be created there."), + + PLAYER_POWER_NOLOSS_PEACEFUL("&eYou didn't lose any power since you are in a peaceful faction."), + PLAYER_POWER_NOLOSS_WORLD("&eYou didn't lose any power due to the world you died in."), + PLAYER_POWER_NOLOSS_WILDERNESS("&eYou didn't lose any power since you were in the wilderness."), + PLAYER_POWER_NOLOSS_WARZONE("&eYou didn't lose any power since you were in a war zone."), + PLAYER_POWER_LOSS_WARZONE("&cThe world you are in has power loss normally disabled, but you still lost power since you were in a war zone.\n&eYour power is now &d%d / %d"), + PLAYER_POWER_NOW("&eYour power is now &d%d / %d"), + + PLAYER_PVP_LOGIN("&eYou can't hurt other players for %d seconds after logging in."), + PLAYER_PVP_REQUIREFACTION("&eYou can't hurt other players until you join a faction."), + PLAYER_PVP_FACTIONLESS("&eYou can't hurt players who are not currently in a faction."), + PLAYER_PVP_PEACEFUL("&ePeaceful players cannot participate in combat."), + PLAYER_PVP_NEUTRAL("&eYou can't hurt neutral factions. Declare them as an enemy."), + PLAYER_PVP_CANTHURT("&eYou can't hurt %s&e."), + + PLAYER_PVP_NEUTRALFAIL("&eYou can't hurt %s&e in their own territory unless you declare them as an enemy."), + PLAYER_PVP_TRIED("%s&e tried to hurt you."), + + PERM_BUILD("Building blocks"), + PERM_DESTROY("Breaking blocks"), + PERM_PAINBUILD("If allow, can build but hurts to do so"), + PERM_ITEM("Using items"), + PERM_CONTAINER("Opening any block that can store items"), + PERM_BUTTON("Using buttons"), + PERM_DOOR("Opening doors"), + PERM_LEVER("Using levers"), + PERM_PLATE("Using pressure plates"), + PERM_FROSTWALK("Walking on water with the frostwalk enchantment"), + PERM_INVITE("Inviting others to join the faction"), + PERM_KICK("Kicking members from the faction"), + PERM_BAN("Banning players from the faction"), + PERM_PROMOTE("Promoting members of the faction"), + PERM_DISBAND("Disbanding the entire faction"), + PERM_ECONOMY("Spending faction money"), + PERM_TERRITORY("Claiming or unclaiming faction territory"), + PERM_HOME("Visiting the faction home"), + PERM_REPEATER("Changing repeaters"), + PERM_SETHOME("Setting the faction home"), + PERM_LISTCLAIMS("View listed faction claims"), + PERM_SETWARP("Setting and unsetting faction warps"), + PERM_TNTDEPOSIT("Deposit TNT into faction bank"), + PERM_TNTWITHDRAW("Withdraw TNT from faction bank"), + PERM_WARP("Using faction warps"), + PERM_CLAIMCORNER("Claim a corner for your faction"), + PERM_COLLECTOR_ACCESS("Access a factions collector"), + PERM_FLY("Flying in faction territory"), + PERM_OWNER("Set ownership of land using /f owner in faction territory"), + PERM_ROSTERCONTROL("Control a faction's roster"), + PERM_TASKS("Manage a faction's tasks"), + + PERM_SHORT_BUILD("build"), + PERM_SHORT_DESTROY("destroy"), + PERM_SHORT_PAINBUILD("painbuild"), + PERM_SHORT_ITEM("use items"), + PERM_SHORT_CONTAINER("open containers"), + PERM_SHORT_BUTTON("use buttons"), + PERM_SHORT_DOOR("open doors"), + PERM_SHORT_LEVER("use levers"), + PERM_SHORT_PLATE("use pressure plates"), + PERM_SHORT_FROSTWALK("frostwalk"), + PERM_SHORT_INVITE("invite"), + PERM_SHORT_KICK("kick"), + PERM_SHORT_BAN("ban"), + PERM_SHORT_PROMOTE("promote"), + PERM_SHORT_DISBAND("disband"), + PERM_SHORT_ECONOMY("spend faction money"), + PERM_SHORT_TERRITORY("manage faction territory"), + PERM_SHORT_HOME("visit home"), + PERM_SHORT_SETHOME("set home"), + PERM_SHORT_LISTCLAIMS("list claims"), + PERM_SHORT_SETWARP("set warps"), + PERM_SHORT_TNTDEPOSIT("deposit TNT"), + PERM_SHORT_TNTWITHDRAW("withdraw TNT"), + PERM_SHORT_REPEATER("change repeaters"), + PERM_SHORT_WARP("use warps"), + PERM_SHORT_FLY("fly"), + PERM_SHORT_OWNER("set ownership"), + PERM_SHORT_CLAIMCORNER("claim a corner"), + PERM_SHORT_COLLECTOR_ACCESS("access a collector"), + PERM_SHORT_ROSTERCONTROL("control roster"), + PERM_SHORT_TASKS("manage tasks"), + + PERM_DENIED_WILDERNESS("&cYou can't %s in the wilderness"), + PERM_DENIED_SAFEZONE("&c>You can't %s in a safe zone"), + PERM_DENIED_WARZONE("&cYou can't %s in a war zone"), + PERM_DENIED_TERRITORY("&cYou can't %s in the territory of %s"), + PERM_DENIED_PAINTERRITORY("&cIt is painful to %s in the territory of %s"), + PERM_DENIED_OWNED("&cYou can't %s in this territory, it is owned by: %s"), + PERM_DENIED_PAINOWNED("&cIt is painful to try to %s in this territory, it is owned by: %s"), + + GUI_WARPS_ONE_PAGE("%s warps"), + GUI_WARPS_PAGE("%1$s warps (page %2$d)"), + + GUI_PERMS_RELATION_NAME("Choose a relation%s:"), + GUI_PERMS_RELATION_ONLINEOFFLINEBIT(" (%s)"), + + GUI_PERMS_ACTION_NAME("Permissions: %1$s%2$s"), + GUI_PERMS_ACTION_ONLINEOFFLINEBIT(" (%s)"), + + GUI_PERMS_TOGGLE("Toggle online/offline"), + GUI_PERMS_ONLINE("online"), + GUI_PERMS_OFFLINE("offline"), + + GUI_PERMS_ACTION_LOCKED("(Locked)"), + GUI_PERMS_ACTION_ALLOW("Allow"), + GUI_PERMS_ACTION_DENY("Deny"), + + GUI_BUTTON_NEXT("&aNext"), + GUI_BUTTON_PREV("&cPrevious"), + GUI_BUTTON_BACK("&cBack"), + + /** + * Strings lying around in other bits of the plugins + */ + NOPAGES("&eSorry. No Pages available."), + INVALIDPAGE("&eInvalid page. Must be between 1 and %1$d"), + + /** + * The ones here before I started messing around with this + */ + TITLE("title", "&bFactions &0|&r"), + WILDERNESS("wilderness", "&2Wilderness"), + WILDERNESS_DESCRIPTION("wilderness-description", ""), + WARZONE("warzone", "&4Warzone"), + WARZONE_DESCRIPTION("warzone-description", "Not the safest place to be."), + SAFEZONE("safezone", "&6Safezone"), + SAFEZONE_DESCRIPTION("safezone-description", "Free from pvp and monsters."), + TOGGLE_SB("toggle-sb", "You now have scoreboards set to {value}"), + FACTION_LEAVE("faction-leave", "&6Leaving %1$s, &6Entering %2$s"), + FACTIONS_ANNOUNCEMENT_TOP("faction-announcement-top", "&d--Unread Faction Announcements--"), + FACTIONS_ANNOUNCEMENT_BOTTOM("faction-announcement-bottom", "&d--Unread Faction Announcements--"), + DEFAULT_PREFIX("default-prefix", "{relationcolor}[{faction}] &r"), + FACTION_LOGIN("faction-login", "&e%1$s &9logged in."), + FACTION_LOGOUT("faction-logout", "&e%1$s &9logged out.."), + NOFACTION_PREFIX("nofactions-prefix", "&6[&ano-faction&6]&r"), + DATE_FORMAT("date-format", "MM/d/yy h:ma"), // 3/31/15 07:49AM + + /** + * Raidable is used in multiple places. Allow more than just true/false. + */ + RAIDABLE_TRUE("raidable-true", "true"), + RAIDABLE_FALSE("raidable-false", "false"), + /** + * Warmups + */ + WARMUPS_NOTIFY_FLIGHT("&eFlight will enable in &d%2$d &eseconds."), + WARMUPS_NOTIFY_TELEPORT("&eYou will teleport to &d%1$s &ein &d%2$d &eseconds."), + WARMUPS_ALREADY("&cYou are already warming up."), + WARMUPS_CANCELLED("&cYou have cancelled your warmup."), + /** + * DTR + */ + DTR_CANNOT_FROZEN("&cAction denied due to frozen DTR"), + DTR_KICK_PENALTY("&cPenalty DTR lost due to kicking with frozen DTR"), + DTR_FROZEN_STATUS_MESSAGE("%s"), + DTR_FROZEN_STATUS_TRUE("Frozen"), + DTR_FROZEN_STATUS_FALSE("Not frozen"), + DTR_FROZEN_TIME_MESSAGE("%s"), + DTR_FROZEN_TIME_NOTFROZEN(""), + + RALLY_DESCRIPTION("Create a ping that your faction members can see"), + RALLY_COORDS_MESSAGE("&f%player% has rallied your faction at: x: %x%, y: %y%, z: %z% in world %world%"), + ; + + private String path; + private final String def; + private static YamlConfiguration LANG; + public static SimpleDateFormat sdf; + + /** + * Lang enum constructor. + * + * @param path The string path. + * @param start The default string. + */ + TL(String path, String start) { + this.path = path; + this.def = start; + } + + /** + * Lang enum constructor. Use this when your desired path simply exchanges '_' for '.' + * + * @param start The default string. + */ + TL(String start) { + this.path = this.name().replace('_', '.'); + if (this.path.startsWith(".")) { + path = "root" + path; + } + this.def = start; + } + + /** + * Set the {@code YamlConfiguration} to use. + * + * @param config The config to set. + */ + public static void setFile(YamlConfiguration config) { + LANG = config; + sdf = new SimpleDateFormat(DATE_FORMAT.toString()); + } + + @Override + public String toString() { + return this == TITLE ? ChatColor.translateAlternateColorCodes('&', LANG.getString(this.path, def)) + " " : ChatColor.translateAlternateColorCodes('&', LANG.getString(this.path, def)); + } + + public String format(Object... args) { + return String.format(toString(), args); + } + + /** + * Get the default value of the path. + * + * @return The default value of the path. + */ + public String getDefault() { + return this.def; + } + + /** + * Get the path to the string. + * + * @return The path to the string. + */ + public String getPath() { + return this.path; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/TextUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/TextUtil.java new file mode 100644 index 0000000..c5a339a --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/TextUtil.java @@ -0,0 +1,251 @@ +package com.massivecraft.factions.util; + +import mkremins.fanciful.FancyMessage; +import org.bukkit.ChatColor; +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class TextUtil { + + public Map tags; + + public TextUtil() { + this.tags = new HashMap<>(); + } + + // -------------------------------------------- // + // Top-level parsing functions. + // -------------------------------------------- // + + public String parse(String str, Object... args) { + return String.format(this.parse(str), args); + } + + public String parse(String str) { + return this.parseTags(parseColor(str)); + } + + // -------------------------------------------- // + // Tag parsing + // -------------------------------------------- // + + public String parseTags(String str) { + return replaceTags(str, this.tags); + } + + public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); + + public static String replaceTags(String str, Map tags) { + StringBuffer ret = new StringBuffer(); + Matcher matcher = patternTag.matcher(str); + while (matcher.find()) { + String tag = matcher.group(1); + String repl = tags.get(tag); + if (repl == null) { + matcher.appendReplacement(ret, "<" + tag + ">"); + } else { + matcher.appendReplacement(ret, repl); + } + } + matcher.appendTail(ret); + return ret.toString(); + } + + // -------------------------------------------- // + // Fancy parsing + // -------------------------------------------- // + + public FancyMessage parseFancy(String prefix) { + return toFancy(parse(prefix)); + } + + public static FancyMessage toFancy(String first) { + String text = ""; + FancyMessage message = new FancyMessage(text); + ChatColor color = null; + char[] chars = first.toCharArray(); + + for (int i = 0; i < chars.length; i++) { + if (chars[i] == '§') { + if (color != null) { + if (color.isColor()) { + message.then(text).color(color); + } else { + message.then(text).style(color); + } + text = ""; + } + color = ChatColor.getByChar(chars[i + 1]); + i++; // skip color char + } else { + text += chars[i]; + } + } + if (text.length() > 0) { + if (color != null) { + if (color.isColor()) { + message.then(text).color(color); + } else { + message.then(text).style(color); + } + } else { + message.text(text); + } + } + return message; + } + + // -------------------------------------------- // + // Color parsing + // -------------------------------------------- // + + public static String parseColor(String string) { + string = parseColorAmp(string); + string = parseColorAcc(string); + string = parseColorTags(string); + return ChatColor.translateAlternateColorCodes('&', string); + } + + public static String parseColorAmp(String string) { + string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2"); + string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2"); + string = string.replace("&&", "&"); + return string; + } + + public static String parseColorAcc(String string) { + return string.replace("`e", "").replace("`r", ChatColor.RED.toString()).replace("`R", ChatColor.DARK_RED.toString()).replace("`y", ChatColor.YELLOW.toString()).replace("`Y", ChatColor.GOLD.toString()).replace("`g", ChatColor.GREEN.toString()).replace("`G", ChatColor.DARK_GREEN.toString()).replace("`a", ChatColor.AQUA.toString()).replace("`A", ChatColor.DARK_AQUA.toString()).replace("`b", ChatColor.BLUE.toString()).replace("`B", ChatColor.DARK_BLUE.toString()).replace("`p", ChatColor.LIGHT_PURPLE.toString()).replace("`P", ChatColor.DARK_PURPLE.toString()).replace("`k", ChatColor.BLACK.toString()).replace("`s", ChatColor.GRAY.toString()).replace("`S", ChatColor.DARK_GRAY.toString()).replace("`w", ChatColor.WHITE.toString()); + } + + public static String parseColorTags(String string) { + return string.replace("", "").replace("", "\u00A70").replace("", "\u00A71").replace("", "\u00A72").replace("", "\u00A73").replace("", "\u00A74").replace("", "\u00A75").replace("", "\u00A76").replace("", "\u00A77").replace("", "\u00A78").replace("", "\u00A79").replace("", "\u00A7a").replace("", "\u00A7b").replace("", "\u00A7c").replace("", "\u00A7d").replace("", "\u00A7e").replace("", "\u00A7f"); + } + + // -------------------------------------------- // + // Standard utils like UCFirst, implode and repeat. + // -------------------------------------------- // + + public static String upperCaseFirst(String string) { + return string.substring(0, 1).toUpperCase() + string.substring(1); + } + + public static String implode(List list, String glue) { + StringBuilder ret = new StringBuilder(); + for (int i = 0; i < list.size(); i++) { + if (i != 0) { + ret.append(glue); + } + ret.append(list.get(i)); + } + return ret.toString(); + } + + public static String repeat(String s, int times) { + if (times <= 0) { + return ""; + } else { + return s + repeat(s, times - 1); + } + } + + // -------------------------------------------- // + // Material name tools + // -------------------------------------------- // + + public static String getMaterialName(Material material) { + return material.toString().replace('_', ' ').toLowerCase(); + } + + // -------------------------------------------- // + // Paging and chrome-tools like titleize + // -------------------------------------------- // + + private final static String titleizeLine = repeat("-", 52); + private final static int titleizeBalance = -1; + + public String titleize(String str) { + String center = parseTags("") + str; + int centerlen = ChatColor.stripColor(center).length(); + int pivot = titleizeLine.length() / 2; + int eatLeft = (centerlen / 2) - titleizeBalance; + int eatRight = (centerlen - eatLeft) + titleizeBalance; + + if (eatLeft < pivot) { + return parseColor("&8&m") + titleizeLine.substring(0, pivot - eatLeft) + " " + center + parseColor("&8&m ") + titleizeLine.substring(pivot + eatRight); + } else { + return center; + } + } + + public ArrayList getPage(List lines, int pageHumanBased, String title) { + ArrayList ret = new ArrayList<>(); + int pageZeroBased = pageHumanBased - 1; + int pageheight = 9; + int pagecount = (lines.size() / pageheight) + 1; + + ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount)); + + if (pagecount == 0) { + ret.add(this.parseTags(TL.NOPAGES.toString())); + return ret; + } else if (pageZeroBased < 0 || pageHumanBased > pagecount) { + ret.add(this.parseTags(TL.INVALIDPAGE.format(pagecount))); + return ret; + } + + int from = pageZeroBased * pageheight; + int to = from + pageheight; + if (to > lines.size()) { + to = lines.size(); + } + + ret.addAll(lines.subList(from, to)); + + return ret; + } + + private static final char[] chars = new char[] { + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i', + 'j', + 'k', + 'l', + 'm', + 'n', + 'o', + 'p', + 'q', + 'r', + 's', + 't', + 'u', + 'v', + 'w', + 'x', + 'y', + 'z' + }; + + public static String generateRandomString(int length){ + char[] toReturn = new char[length]; + + for(int z = 0; z < length; z++){ + toReturn[z] = chars[ThreadLocalRandom.current().nextInt(chars.length)]; + } + return new String(toReturn); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/TitleAPI.java b/Factions/src/main/java/com/massivecraft/factions/util/TitleAPI.java new file mode 100644 index 0000000..f89f619 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/TitleAPI.java @@ -0,0 +1,139 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; + +/** + * With help from https://www.spigotmc.org/threads/send-titles-to-players-using-spigot-1-8-1-11-2.48819/ + */ +public class TitleAPI { + + private static TitleAPI instance; + private boolean supportsAPI = false; + private boolean bailOut = false; + + private final Map> classCache = new HashMap<>(); + + private Method methodChatTitle; + private Method methodGetHandle; + private Method methodSendPacket; + private Constructor titleConstructor; + private Field fieldTitle; + private Field fieldSubTitle; + private Field fieldPlayerConnection; + + public TitleAPI() { + instance = this; + + if (FactionsPlugin.getMCVersion() < 800) { + bailOut = true; + FactionsPlugin.getInstance().getLogger().info("Title support disabled because 1.7.10 is too old."); + return; + } + + try { + Player.class.getMethod("sendTitle", String.class, String.class, int.class, int.class, int.class); + supportsAPI = true; + FactionsPlugin.getInstance().getLogger().info("Found API support for sending player titles :D"); + } catch (NoSuchMethodException e) { + try { + this.methodChatTitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class); + this.titleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), int.class, int.class, int.class); + this.fieldTitle = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TITLE"); + this.fieldSubTitle = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("SUBTITLE"); + + FactionsPlugin.getInstance().getLogger().info("Didn't find API support for sending titles, using reflection instead."); + } catch (Exception ex) { + bailOut = true; + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Didn't find API support for sending titles, and failed to use reflection. Title support disabled.", ex); + } + } + } + + /** + * Send a title to player + * + * @param player Player to send the title to + * @param title The text displayed in the title + * @param subtitle The text displayed in the subtitle + * @param fadeInTime The time the title takes to fade in + * @param showTime The time the title is displayed + * @param fadeOutTime The time the title takes to fade out + */ + public void sendTitle(Player player, String title, String subtitle, int fadeInTime, int showTime, int fadeOutTime) { + if (bailOut) { + return; + } + + if (supportsAPI) { + player.sendTitle(title, subtitle, fadeInTime, showTime, fadeOutTime); + return; + } + + try { + Object chatTitle = methodChatTitle.invoke(null, "{\"text\": \"" + sanitize(title) + "\"}"); + Object chatsubTitle = methodChatTitle.invoke(null, "{\"text\": \"" + sanitize(subtitle) + "\"}"); + + Object titlePacket = titleConstructor.newInstance(fieldTitle.get(null), chatTitle, fadeInTime, showTime, fadeOutTime); + Object subTitlePacket = titleConstructor.newInstance(fieldSubTitle.get(null), chatsubTitle, fadeInTime, showTime, fadeOutTime); + + sendPacket(player, titlePacket); + sendPacket(player, subTitlePacket); + } catch (Exception e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to send title via reflection", e); + } + } + + private String sanitize(String string) { + return string.replace("\\", "\\\\").replace("\"", "\\\""); + } + + private void sendPacket(Player player, Object packet) { + try { + if (this.methodGetHandle == null) { + this.methodGetHandle = player.getClass().getMethod("getHandle"); + } + Object handle = this.methodGetHandle.invoke(player); + if (this.fieldPlayerConnection == null) { + this.fieldPlayerConnection = handle.getClass().getField("playerConnection"); + } + Object playerConnection = this.fieldPlayerConnection.get(handle); + if (this.methodSendPacket == null) { + this.methodSendPacket = playerConnection.getClass().getMethod("sendPacket", getNMSClass("Packet")); + } + this.methodSendPacket.invoke(playerConnection, packet); + } catch (Exception e) { + FactionsPlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to send title packet via reflection", e); + } + } + + /** + * Get NMS class using reflection + * + * @param name Name of the class + * @return Class + */ + private Class getNMSClass(String name) throws ClassNotFoundException { + String versionName = "net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "." + name; + + if (classCache.containsKey(versionName)) { + return classCache.get(versionName); + } + + Class clazz = Class.forName(versionName); + classCache.put(name, clazz); + return clazz; + } + + public static TitleAPI getInstance() { + return instance; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/Triplet.java b/Factions/src/main/java/com/massivecraft/factions/util/Triplet.java new file mode 100644 index 0000000..10b5e92 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/Triplet.java @@ -0,0 +1,29 @@ +package com.massivecraft.factions.util; + +public class Triplet { + public static Triplet of(Left left, Middle middle, Right right) { + return new Triplet<>(left, middle, right); + } + + private final Left left; + private final Middle middle; + private final Right right; + + private Triplet(Left left, Middle middle, Right right) { + this.left = left; + this.middle = middle; + this.right = right; + } + + public Left getLeft() { + return this.left; + } + + public Middle getMiddle() { + return middle; + } + + public Right getRight() { + return this.right; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/UUIDFetcher.java b/Factions/src/main/java/com/massivecraft/factions/util/UUIDFetcher.java new file mode 100644 index 0000000..99767e6 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/UUIDFetcher.java @@ -0,0 +1,104 @@ +package com.massivecraft.factions.util; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Callable; + +/** + * @author evilmidget38 + */ + +public class UUIDFetcher implements Callable> { + private static final double PROFILES_PER_REQUEST = 100; + private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; + private final JSONParser jsonParser = new JSONParser(); + private final List names; + private final boolean rateLimiting; + + public UUIDFetcher(List names, boolean rateLimiting) { + this.names = new ArrayList<>(names); + this.rateLimiting = rateLimiting; + } + + public UUIDFetcher(List names) { + this(names, true); + } + + public Map call() throws Exception { + Map uuidMap = new HashMap<>(); + int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); + for (int i = 0; i < requests; i++) { + HttpURLConnection connection = createConnection(); + String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); + writeBody(connection, body); + JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); + for (Object profile : array) { + JSONObject jsonProfile = (JSONObject) profile; + String id = (String) jsonProfile.get("id"); + String name = (String) jsonProfile.get("name"); + UUID uuid = UUIDFetcher.getUUID(id); + uuidMap.put(name, uuid); + } + if (rateLimiting && i != requests - 1) { + Thread.sleep(100L); + } + } + return uuidMap; + } + + private static void writeBody(HttpURLConnection connection, String body) throws Exception { + OutputStream stream = connection.getOutputStream(); + stream.write(body.getBytes()); + stream.flush(); + stream.close(); + } + + private static HttpURLConnection createConnection() throws Exception { + URL url = new URL(PROFILE_URL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + return connection; + } + + private static UUID getUUID(String id) { + return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); + } + + public static byte[] toBytes(UUID uuid) { + ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); + byteBuffer.putLong(uuid.getMostSignificantBits()); + byteBuffer.putLong(uuid.getLeastSignificantBits()); + return byteBuffer.array(); + } + + public static UUID fromBytes(byte[] array) { + if (array.length != 16) { + throw new IllegalArgumentException("Illegal byte array length: " + array.length); + } + ByteBuffer byteBuffer = ByteBuffer.wrap(array); + long mostSignificant = byteBuffer.getLong(); + long leastSignificant = byteBuffer.getLong(); + return new UUID(mostSignificant, leastSignificant); + } + + public static UUID getUUIDOf(String name) throws Exception { + return new UUIDFetcher(Collections.singletonList(name)).call().get(name); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/UpgradeType.java b/Factions/src/main/java/com/massivecraft/factions/util/UpgradeType.java new file mode 100644 index 0000000..adaea9e --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/UpgradeType.java @@ -0,0 +1,10 @@ +package com.massivecraft.factions.util; + +public enum UpgradeType { + TNT, + CHEST, + SPAWNER_BOOST, + CROP_BOOST, + WARP_AMOUNT, + FACTION_SIZE +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java new file mode 100644 index 0000000..e6acd6b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java @@ -0,0 +1,75 @@ +package com.massivecraft.factions.util; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; + +public class VisualizeUtil { + + protected static Map> playerLocations = new HashMap<>(); + + public static Set getPlayerLocations(Player player) { + return getPlayerLocations(player.getUniqueId()); + } + + public static Set getPlayerLocations(UUID uuid) { + return playerLocations.computeIfAbsent(uuid, k -> new HashSet<>()); + } + + @SuppressWarnings("deprecation") + public static void addLocation(Player player, Location location, Material material) { + getPlayerLocations(player).add(location); + player.sendBlockChange(location, material, (byte) 0); + } + + @SuppressWarnings("deprecation") + public static void addLocations(Player player, Map locationMaterialIds) { + Set ploc = getPlayerLocations(player); + for (Entry entry : locationMaterialIds.entrySet()) { + ploc.add(entry.getKey()); + player.sendBlockChange(entry.getKey(), entry.getValue(), (byte) 0); + } + } + + @SuppressWarnings("deprecation") + public static void addLocations(Player player, Collection locations, Material material) { + Set ploc = getPlayerLocations(player); + for (Location location : locations) { + ploc.add(location); + player.sendBlockChange(location, material, (byte) 0); + } + } + + @SuppressWarnings("deprecation") + public static void addBlocks(Player player, Collection blocks, Material material) { + Set ploc = getPlayerLocations(player); + for (Block block : blocks) { + Location location = block.getLocation(); + ploc.add(location); + player.sendBlockChange(location, material, (byte) 0); + } + } + + @SuppressWarnings("deprecation") + public static void clear(Player player) { + Set locations = getPlayerLocations(player); + if (locations == null) { + return; + } + for (Location location : locations) { + Block block = location.getWorld().getBlockAt(location); + player.sendBlockChange(location, block.getType(), block.getData()); + } + locations.clear(); + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java new file mode 100644 index 0000000..08d43f5 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java @@ -0,0 +1,42 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.scheduler.BukkitRunnable; + +public class WarmUpUtil { + + /** + * @param player The player to notify. + * @param translationKey The translation key used for notifying. + * @param action The action, inserted into the notification message. + * @param runnable The task to run after the delay. If the delay is 0, the task is instantly ran. + * @param delay The time used, in seconds, for the delay. + *

+ * note: for translations: %s = action, %d = delay + */ + public static void process(final FPlayer player, Warmup warmup, TL translationKey, String action, final Runnable runnable, long delay) { + if (delay > 0) { + if (player.isWarmingUp()) { + player.msg(TL.WARMUPS_ALREADY); + } else { + player.msg(translationKey.format(action, delay)); + int id = new BukkitRunnable() { + @Override + public void run() { + player.stopWarmup(); + runnable.run(); + } + }.runTaskLater(FactionsPlugin.getInstance(), delay * 20).getTaskId(); + player.addWarmup(warmup, id); + } + } else { + runnable.run(); + } + } + + public enum Warmup { + HOME, WARP, FLIGHT + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/WorldUtil.java b/Factions/src/main/java/com/massivecraft/factions/util/WorldUtil.java new file mode 100644 index 0000000..8231b3b --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/WorldUtil.java @@ -0,0 +1,41 @@ +package com.massivecraft.factions.util; + +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.HashSet; + +public class WorldUtil { + private HashSet worlds; + private final boolean check; + private boolean whitelist; + + public WorldUtil(FactionsPlugin plugin) { + check = plugin.conf().restrictWorlds().isRestrictWorlds(); + if (!check) { + return; + } + worlds = new HashSet<>(plugin.conf().restrictWorlds().getWorldList()); + whitelist = plugin.conf().restrictWorlds().isWhitelist(); + } + + private boolean isEnabled(String name) { + if (!check) { + return true; + } + return whitelist == worlds.contains(name); + } + + public boolean isEnabled(World world) { + return isEnabled(world.getName()); + } + + public boolean isEnabled(CommandSender sender) { + if (sender instanceof Player) { + return isEnabled(((Player) sender).getWorld().getName()); + } + return true; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/material/MaterialDb.java b/Factions/src/main/java/com/massivecraft/factions/util/material/MaterialDb.java new file mode 100644 index 0000000..6f10593 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/material/MaterialDb.java @@ -0,0 +1,59 @@ +package com.massivecraft.factions.util.material; + +import com.google.gson.reflect.TypeToken; +import com.massivecraft.factions.FactionsPlugin; +import org.bukkit.Material; + +import java.io.InputStreamReader; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; + +public class MaterialDb { + private static Map map; + + private MaterialDb() { + } + + public static Material get(String name) { + return get(name, Material.AIR); + } + + public static Material get(String name, Material defaultMaterial) { + if (name == null) { + FactionsPlugin.getInstance().log("Null material name found"); + return defaultMaterial; + } + + Material material = Material.getMaterial(name); + if (material == null) { + material = map.get(name.toUpperCase()); + } + + if (material == null) { + FactionsPlugin.getInstance().log(Level.INFO, "Material does not exist: " + name.toUpperCase()); + return defaultMaterial; + } + + return material; + } + + public static void load() { + InputStreamReader reader = new InputStreamReader(FactionsPlugin.getInstance().getResource("materials.json")); + Type typeToken = new TypeToken>() { + }.getType(); + HashMap materialData = FactionsPlugin.getInstance().getGson().fromJson(reader, typeToken); + map = new HashMap<>(); + materialData.forEach((n, l) -> { + Material matN = Material.getMaterial(n); + Material matL = Material.getMaterial(l); + boolean nNull = matN == null; + if (nNull == (matL == null)) { + return; + } + map.put(nNull ? n : l, nNull ? matL : matN); + }); + FactionsPlugin.getInstance().getLogger().info(String.format("Loaded %s material mappings.", map.size())); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/particle/BukkitParticleProvider.java b/Factions/src/main/java/com/massivecraft/factions/util/particle/BukkitParticleProvider.java new file mode 100644 index 0000000..0546d34 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/particle/BukkitParticleProvider.java @@ -0,0 +1,58 @@ +package com.massivecraft.factions.util.particle; + +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Player; + +public class BukkitParticleProvider implements ParticleProvider { + + @Override + public String name() { + return "BUKKIT"; + } + + @Override + public void spawn(Particle effect, Location location, int count) { + location.getWorld().spawnParticle(effect, location, count); + } + + @Override + public void playerSpawn(Player player, Particle effect, Location location, int count) { + player.spawnParticle(effect, location, count); + } + + @Override + public void spawn(Particle particle, Location location, int count, double speed, double offsetX, double offsetY, double offsetZ) { + location.getWorld().spawnParticle(particle, location, count, offsetX, offsetY, offsetZ, speed); + } + + @Override + public void playerSpawn(Player player, Particle particle, Location location, int count, double speed, double offsetX, double offsetY, double offsetZ) { + player.spawnParticle(particle, location, count, offsetX, offsetY, offsetZ, speed); + } + + @Override + public void spawn(Particle particle, Location location, ParticleColor color) { + location.getWorld().spawnParticle(particle, location, 1, new Particle.DustOptions(color.getColor(), 1)); + } + + @Override + public void playerSpawn(Player player, Particle particle, Location location, ParticleColor color) { + player.spawnParticle(particle, location, 1, new Particle.DustOptions(color.getColor(), 1.5f)); + } + + @Override + public Particle effectFromString(String string) { + for (Particle particle : Particle.values()) { + if (particle.name().equalsIgnoreCase(string)) { + return particle; + } + } + return null; + } + + @Override + public String effectName(Particle particle) { + return particle.name(); + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/particle/PacketParticleProvider.java b/Factions/src/main/java/com/massivecraft/factions/util/particle/PacketParticleProvider.java new file mode 100644 index 0000000..c38de15 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/particle/PacketParticleProvider.java @@ -0,0 +1,63 @@ +package com.massivecraft.factions.util.particle; + +import com.darkblade12.particleeffect.ParticleEffect; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.ArrayList; + +public class PacketParticleProvider implements ParticleProvider { + + @Override + public String name() { + return "PACKETS"; + } + + @Override + public void spawn(ParticleEffect particleEffect, Location location, int count) { + particleEffect.display(0, 0, 0, 1, count, location, new ArrayList<>(Bukkit.getOnlinePlayers())); + } + + @Override + public void playerSpawn(Player player, ParticleEffect particleEffect, Location location, int count) { + particleEffect.display(0, 0, 0, 1, count, location, player); + } + + @Override + public void spawn(ParticleEffect particleEffect, Location location, int count, double speed, double offsetX, double offsetY, double offsetZ) { + particleEffect.display((float) offsetX, (float) offsetY, (float) offsetZ, (float) speed, count, location, new ArrayList<>(Bukkit.getOnlinePlayers())); + } + + @Override + public void playerSpawn(Player player, ParticleEffect particleEffect, Location location, int count, double speed, double offsetX, double offsetY, double offsetZ) { + particleEffect.display((float) offsetX, (float) offsetY, (float) offsetZ, (float) speed, count, location, player); + } + + @Override + public void spawn(ParticleEffect particleEffect, Location location, ParticleColor color) { + spawn(particleEffect, location, 0, 1, color.getOffsetX(), color.getOffsetY(), color.getOffsetZ()); + } + + @Override + public void playerSpawn(Player player, ParticleEffect particleEffect, Location location, ParticleColor color) { + playerSpawn(player, particleEffect, location, 0, 1, color.getOffsetX(), color.getOffsetY(), color.getOffsetZ()); + } + + @Override + public ParticleEffect effectFromString(String string) { + for (ParticleEffect effect : ParticleEffect.values()) { + if (effect.name().equalsIgnoreCase(string)) { + return effect; + } + } + // If none of the Enum name matches fallback to the other names + return ParticleEffect.fromName(string); + } + + @Override + public String effectName(ParticleEffect particleEffect) { + return particleEffect.name(); + } + +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/particle/ParticleColor.java b/Factions/src/main/java/com/massivecraft/factions/util/particle/ParticleColor.java new file mode 100644 index 0000000..78d77b5 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/particle/ParticleColor.java @@ -0,0 +1,75 @@ +package com.massivecraft.factions.util.particle; + +import org.bukkit.ChatColor; +import org.bukkit.Color; + +public class ParticleColor { + + private final Color color; + + private final float red; + private final float green; + private final float blue; + + ParticleColor(Color color) { + this.color = color; + this.red = color.getRed(); + this.green = color.getGreen(); + this.blue = color.getBlue(); + } + + public float getOffsetX() { + if (red == 0) { + return Float.MIN_VALUE; + } + return red / 255; + } + + public float getOffsetY() { + return green / 255; + } + + public float getOffsetZ() { + return blue / 255; + } + + // Why Spigot? + public static ParticleColor fromChatColor(ChatColor chatColor) { + switch (chatColor) { + case AQUA: + return new ParticleColor(Color.AQUA); + case BLACK: + return new ParticleColor(Color.BLACK); + case BLUE: + case DARK_AQUA: + case DARK_BLUE: + return new ParticleColor(Color.BLUE); + case DARK_GRAY: + case GRAY: + return new ParticleColor(Color.GRAY); + case DARK_GREEN: + return new ParticleColor(Color.GREEN); + case DARK_PURPLE: + case LIGHT_PURPLE: + return new ParticleColor(Color.PURPLE); + case DARK_RED: + case RED: + return new ParticleColor(Color.RED); + case GOLD: + case YELLOW: + return new ParticleColor(Color.YELLOW); + case GREEN: + return new ParticleColor(Color.LIME); + case WHITE: + return new ParticleColor(Color.WHITE); + default: + break; + } + + return null; + } + + public Color getColor() { + return color; + } +} diff --git a/Factions/src/main/java/com/massivecraft/factions/util/particle/ParticleProvider.java b/Factions/src/main/java/com/massivecraft/factions/util/particle/ParticleProvider.java new file mode 100644 index 0000000..ec855b3 --- /dev/null +++ b/Factions/src/main/java/com/massivecraft/factions/util/particle/ParticleProvider.java @@ -0,0 +1,26 @@ +package com.massivecraft.factions.util.particle; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public interface ParticleProvider { + + String name(); + + void spawn(Effect effect, Location location, int count); + + void playerSpawn(Player player, Effect effect, Location location, int count); + + void spawn(Effect effect, Location location, int count, double speed, double offsetX, double offsetY, double offsetZ); + + void playerSpawn(Player player, Effect effect, Location location, int count, double speed, double offsetX, double offsetY, double offsetZ); + + void spawn(Effect effect, Location location, ParticleColor color); + + void playerSpawn(Player player, Effect effect, Location location, ParticleColor color); + + Effect effectFromString(String string); + + String effectName(Effect effect); + +} diff --git a/Factions/src/main/resources/lang.yml b/Factions/src/main/resources/lang.yml new file mode 100644 index 0000000..b889fd3 --- /dev/null +++ b/Factions/src/main/resources/lang.yml @@ -0,0 +1,5 @@ +# Lang file for FactionsUUID by drtshock +# Use & for color codes. +# Made with love <3 + + diff --git a/Factions/src/main/resources/lang/en_GB.yml b/Factions/src/main/resources/lang/en_GB.yml new file mode 100644 index 0000000..d69fe60 --- /dev/null +++ b/Factions/src/main/resources/lang/en_GB.yml @@ -0,0 +1,31 @@ +# Lang file for FactionsUUID by drtshock +# Use & for color codes. +# Made with love <3 + +#Slightly different localised variant for UK-style english (Color→Colour, etc) +#It's cut down to the sections that were actually changed. Ie basically nothing. What ho, dear chap! + +root: + AUTHOR: misc + RESPONSIBLE: Korikisulda + LANGUAGE: English + ENCODING: UTF-8 + LOCALE: en_GB + EXTENDS: en_US + REQUIRESUNICODE: 'false' + DEFAULT: 'false' + STATE: complete + LOCAL: + AUTHOR: misc + RESPONSIBLE: Korikisulda + LANGUAGE: English + REGION: UK + STATE: complete +COMMAND: + CONFIG: + COLOURSET: '" colour option set to "' + INVALID: + COLOUR: 'Cannot set "%1$s": "%2$s" is not a valid colour.' + COLLECTION: '"%1$s" is not a data collection type which can be modified with this + command.' + diff --git a/Factions/src/main/resources/lang/en_US.yml b/Factions/src/main/resources/lang/en_US.yml new file mode 100644 index 0000000..3d30907 --- /dev/null +++ b/Factions/src/main/resources/lang/en_US.yml @@ -0,0 +1,1120 @@ +# Lang file for FactionsUUID by drtshock +# Use & for color codes +# Made with love <3 + + + +root: + AUTHOR: misc + RESPONSIBLE: misc + LANGUAGE: English + ENCODING: UTF-8 + LOCALE: en_US + REQUIRESUNICODE: 'false' + DEFAULT: 'true' + STATE: complete + LOCAL: + AUTHOR: misc + RESPONSIBLE: misc + LANGUAGE: English + REGION: US + STATE: complete +COMMAND: + ADMIN: + NOTMEMBER: '&8(&c!&8) &7%1$s&7 is not a member in your faction' + NOTADMIN: '&8(&c!&8) &7You are not the faction admin' + TARGETSELF: '&8(&c!&8) &7The target player musn''t be yourself' + DEMOTES: '&8(&c!&8) &7You have demoted %1$s&7 from the position of faction admin' + DEMOTED: '&8(&c!&8) &7You have been demoted from the position of faction admin + by %1$s&7' + PROMOTES: '&8(&c!&8) &7You have promoted %1$s&7 to the position of faction admin' + PROMOTED: '&8(&c!&8) &7%1$s&7 gave %2$s&7 the leadership of %3$s' + DESCRIPTION: Hand over your admin rights + AHOME: + DESCRIPTION: Send a player to their f home no matter what + NOHOME: '%1$s doesn''t have an f home' + SUCCESS: '%1$s was sent to their f home' + OFFLINE: '%1$s is offline' + TARGET: You were sent to your f home + ANNOUNCE: + DESCRIPTION: Announce a message to players in faction + AUTOCLAIM: + ENABLED: '&8(&a!&8) &7Now auto-claiming land for &a%1$s' + DISABLED: '&8(&c!&8) &7Auto-claiming of land disabled' + REQUIREDRANK: '&8(&c!&8) &7You must be &a%1$s&c to claim land' + OTHERFACTION: '&8(&c!&8) &7You can''t claim land for &a%1$s' + DESCRIPTION: Auto-claim land as you walk around + AUTOHELP: + HELPFOR: Help for command " + BAN: + DESCRIPTION: Ban players from joining your Faction + TARGET: '&8(&c!&8) &7You were banned from &7%1$s' + BANNED: '&8(&c!&8) &7%1$s &cbanned &7%2$s' + ALREADYBANNED: '&8(&c!&8) &7%1$s is already banned' + SELF: '&8(&c!&8) &7You may not ban yourself' + INSUFFICIENTRANK: '&8(&c!&8) &7Your rank is too low to ban &7%1$s' + BANLIST: + DESCRIPTION: View a Faction's ban list + HEADER: '&8(&a!&8) &7There are &a%d&7 bans for %s' + ENTRY: '&7%d &c%s &r- &a%s &r- &7%s' + NOFACTION: '&8(&c!&8) &7You are not in a Faction' + INVALID: We couldn't find a Faction by the name %s + BOOM: + PEACEFULONLY: '&8(&c!&8) &7This command is only usable by factions which are specifically + designated as peaceful' + TOTOGGLE: to toggle explosions + FORTOGGLE: for toggling explosions + ENABLED: '%1$s&7 has %2$s explosions in your faction''s territory' + DESCRIPTION: Toggle explosions (peaceful factions only) + BYPASS: + ENABLE: '&8(&a!&8) &7You have enabled admin bypass mode You will be able to build + or destroy anywhere' + ENABLELOG: ' has ENABLED admin bypass mode' + DISABLE: '&8(&c!&8) &7You have disabled admin bypass mode' + DISABLELOG: ' has DISABLED admin bypass mode' + DESCRIPTION: Enable admin bypass mode + CHAT: + DISABLED: '&8(&c!&8) &7The built in chat channels are disabled on this server' + INVALIDMODE: '&8(&c!&8) &7Unrecognised chat mode &7Please enter either ''a'',''f'',''m'',''t'' + or ''p''' + INSUFFICIENTRANK: '&8(&c!&8) &7You must be at least moderator to enter this chat' + DESCRIPTION: Change chat mode + MODE: + PUBLIC: '&8(&a!&8) &fPublic&7 chat mode' + ALLIANCE: '&8(&a!&8) &dAlliance&7 only chat mode' + TRUCE: '&8(&a!&8) &bTruce&7 only chat mode' + FACTION: '&8(&a!&8) &aFaction&7 only chat mode' + MOD: '&8(&a!&8) &4Mod&7 only chat mode' + CHATSPY: + ENABLE: '&8(&a!&8) &7You have enabled chat spying mode' + ENABLELOG: ' has ENABLED chat spying mode' + DISABLE: '&8(&c!&8) &7You have disabled chat spying mode' + DISABLELOG: ' has DISABLED chat spying mode' + DESCRIPTION: Enable admin chat spy mode + CLAIM: + INVALIDRADIUS: '&8(&c!&8) &7If you specify a radius, it must be at least 1' + TOOBIG: '&8(&c!&8) &7You can''t claim a radius that large. Try <= %s!' + TOOBIGCONFIRM: '&8(&a!&8) &7Are you sure you want to claim in a radius of &a%s&7? + Type &a/f claim confirm &7to confirm' + RADIUS: '&8(&a!&8) &7Claiming &a%s &7chunks at &a%s&7, &a%s&7 for &a%s&7' + DENIED: '&8(&c!&8) &7You do not have permission to claim in a radius' + DESCRIPTION: Claim land from where you are standing + OUTSIDEBORDER: '&8(&c!&8) &7You can''t make a claim outside of the world border!' + CLAIMFILL: + DESCRIPTION: Claim land filling in a gap in claims + ABOVEMAX: '&8(&c!&8) &7The maximum limit for claim fill is %s' + ALREADYCLAIMED: '&8(&a!&8) &7Cannot claim fill using already claimed land!' + TOOFAR: '&8(&c!&8) &7This fill would exceed the maximum distance of %2f' + PASTLIMIT: '&8(&c!&8) &7This claim would exceed the limit' + NOTENOUGHLANDLEFT: '&8(&c!&8) &7%s &cdoes not have enough land left to make %d + claims' + TOOMUCHFAIL: '&8(&c!&8) &7Aborting claim fill after %d failures' + CLAIMLINE: + INVALIDRADIUS: '&8(&c!&8) &7If you specify a distance, it must be at least 1' + DENIED: '&8(&c!&8) &7You do not have permission to claim in a line' + DESCRIPTION: Claim land in a straight line + ABOVEMAX: '&8(&c!&8) &7The maximum limit for claim line is &c%s&c' + NOTVALID: '&8(&c!&8) &7%s&c is not a cardinal direction You may use &anorth&c, + &aeast&c, &asouth &cor &awest&c' + COLEADER: + CANDIDATES: 'Players you can promote: ' + CLICKTOPROMOTE: 'Click to promote ' + NOTMEMBER: '%1$s&c is not a member in your faction' + NOTADMIN: '&8(&c!&8) &7You are not the faction admin' + SELF: '&8(&c!&8) &7The target player musn''t be yourself' + TARGETISADMIN: '&8(&c!&8) &7The target player is a faction admin Demote them first' + REVOKES: '&8(&c!&8) &7You have removed coleader status from %1$s&7' + REVOKED: '&8(&c!&8) &7%1$s&7 is no longer coleader in your faction' + PROMOTES: '&8(&c!&8) &7%1$s&7 was promoted to coleader in your faction' + PROMOTED: '&8(&c!&8) &7You have promoted %1$s&7 to coleader' + DESCRIPTION: Give or revoke coleader rights + ALREADY: + COLEADER: The faction already has a coleader There can only be 1 + CONVERT: + BACKEND: + RUNNING: Already running that backend + INVALID: Invalid backend + DESCRIPTION: Convert the plugin backend + COORDS: + MESSAGE: '&7%s''s location: &a%d&7, &a%d&7, &a%d&7 in &a%s&7' + DESCRIPTION: Broadcast your current position to your faction + CREATE: + MUSTLEAVE: '&8(&c!&8) &7You must leave your current faction first' + INUSE: '&8(&c!&8) &7That tag is already in use' + TOCREATE: to create a new faction + FORCREATE: for creating a new faction + ERROR: '&8(&c!&8) &7There was an internal error while trying to create your faction + Please try again' + CREATED: '&8(&a!&8) &7%1$s&7 created a new faction %2$s' + YOUSHOULD: '&8(&a!&8) &7You should now: %1$s' + CREATEDLOG: ' created a new faction: ' + DESCRIPTION: Create a new faction + DEBUG: + RUNNING: '&7Now running' + COMPLETE: '&7Debug generated! Share this URL: %s' + DESCRIPTION: Create a debug paste + DELETIONKEY: '&7Deletion key: %s' + FAIL: '&7ERROR! Could not debug See console for why' + DEINVITE: + CANDEINVITE: 'Players you can deinvite: ' + CLICKTODEINVITE: Click to revoke invite for %1$s + ALREADYMEMBER: '%1$s&7 is already a member of %2$s' + MIGHTWANT: '&8(&c!&8) &7You might want to: %1$s' + REVOKED: '%1$s&7 revoked your invitation to &a%2$s&7' + REVOKES: '%1$s&7 revoked %2$s''s&7 invitation' + DESCRIPTION: Remove a pending invitation + DELFWARP: + DELETED: '&8(&c!&8) &7Deleted warp &a%1$s' + INVALID: '&8(&c!&8) &7Couldn''t find warp &a%1$s' + TODELETE: to delete warp + FORDELETE: for deleting warp + DESCRIPTION: Delete a faction warp + DELHOME: + DEL: '&8(&c!&8) &7%1$s&7 unset the home for your faction' + DESCRIPTION: Unset the faction home + TOSET: to unset the faction home + FORSET: for unsetting the faction home + DESCRIPTION: + CHANGES: '&8(&a!&8) &7You have changed the description for &a%1$s&7 to:' + CHANGED: '&8(&a!&8) &7The faction %1$s&7 changed their description to:' + TOCHANGE: to change faction description + FORCHANGE: for changing faction description + DESCRIPTION: Change the faction description + DISBAND: + IMMUTABLE: '&8(&c!&8) &7You cannot disband the Wilderness, safe zone, or war zone' + MARKEDPERMANENT: '&8(&c!&8) &7This faction is designated as permanent, so you + cannot disband it' + BROADCAST: + YOURS: '&8(&c!&8) &7&a%1$s&7 disbanded your faction' + NOTYOURS: '&8(&a!&8) &7%1$s&7 disbanded the faction %2$s' + HOLDINGS: '&8(&a!&8) &7You have been given the disbanded faction''s bank, totaling + %1$s' + DESCRIPTION: Disband a faction + DTR: + TOSHOW: to show faction DTR info + FORSHOW: for showing faction DTR info + DTR: '&8(&c!&8) &7%1$s&a - DTR / Max DTR: &7%2$s / %3$s' + DESCRIPTION: Show faction DTR info + MODIFY: + DESCRIPTION: Modify faction DTR + DONE: '&7Set DTR for %s&7 to %s' + FLY: + DESCRIPTION: Enter or leave Faction flight mode + CHANGE: '&8(&a!&8) &7Faction flight &a%1$s' + DAMAGE: '&8(&c!&8) &7Faction flight &adisabled&7 due to entering combat' + AUTO: '&8(&a!&8) &7Faction auto flight &a%1$s' + 'NO': + ACCESS: '&8(&c!&8) &7Cannot fly in territory of %1$s' + ENEMY: + NEARBY: '&8(&c!&8) &7Cannot enable fly, enemy nearby' + DISABLE: '&8(&c!&8) &7Enemy nearby, disabling fly' + FLYTRAILS: + DESCRIPTION: Enabled or change fly trails + PARTICLE: + INVALID: '&8(&c!&8) &7Invalid particle effect' + PERMS: '&8(&c!&8) &7Insufficient permission to use &a%1s' + CHANGE: '&7Faction flight trail effect set to &a%1s' + CHANGE: '&7Faction flight trail &a%1s' + FWARP: + CLICKTOWARP: Click to warp! + COMMANDFORMAT: '&7/f warp [password]' + WARPED: '&8(&c!&8) &7Warped to &a%1$s' + INVALID: + WARP: '&8(&c!&8) &7Couldn''t find warp &a%1$s' + PASSWORD: '&8(&c!&8) &7Invalid password' + TOWARP: to warp + FORWARPING: for warping + WARPS: 'Warps: ' + DESCRIPTION: Teleport to a faction warp + PASSWORD: + REQUIRED: '&8(&a!&8) &7Please enter warp password This will not be visible to + anyone else' + CANCEL: '&8(&c!&8) &7Warp canceled' + NOACCESS: '&8(&c!&8) &7You do not have permission to use %s &cwarps' + WARPOTHER: + COMMANDFORMAT: '&7/f warpother [password]' + HELP: + '404': '&8(&c!&8) &7This page does not exist' + NEXTCREATE: '&7Learn how to create a faction on the next page' + HOME: '&7And don''t forget to set your home:' + BANK: + '1': '&7Your faction has a bank which is used to pay for certain' + '2': '&7things, so it will need to have money deposited into it' + '3': '&7To learn more, use the money command' + PLAYERTITLES: '&7Player titles are just for fun No rules connected to them' + OWNERSHIP: + '1': '&7Claimed land with ownership set is further protected so' + '2': '&7that only the owner(s), faction admin, and possibly the' + '3': '&7faction moderators have full access' + RELATIONS: + '1': '&7Set the relation you WISH to have with another faction' + '2': '&7Your default relation with other factions will be neutral' + '3': '&7If BOTH factions choose "ally" you will be allies' + '4': '&7If ONE faction chooses "enemy" you will be enemies' + '5': '&7You can never hurt members or allies' + '6': '&7You can not hurt neutrals in their own territory' + '7': '&7You can always hurt enemies and players without faction' + '8': '' + '9': '&7Damage from enemies is reduced in your own territory' + '10': '&7When you die you lose power It is restored over time' + '11': '&7The power of a faction is the sum of all member power' + '12': '&7The power of a faction determines how much land it can hold' + '13': '&7You can claim land from factions with too little power' + PERMISSIONS: + '1': '&7Only faction members can build and destroy in their own' + '2': '&7territory Usage of the following items is also restricted:' + '3': '&7Door, Chest, Furnace, Dispenser, Diode' + '4': '' + '5': '&7Make sure to put pressure plates in front of doors for your' + '6': '&7guest visitors Otherwise they can''t get through You can' + '7': '&7also use this to create member only areas' + '8': '&7As dispensers are protected, you can create traps without' + '9': '&7worrying about those arrows getting stolen' + ADMIN: + '1': '&b/f claim safezone &7claim land for the safe zone' + '2': '&b/f claim warzone &7claim land for the war zone' + '3': '&b/f autoclaim [safezone|warzone] &7take a guess' + MOAR: + '1': 'Finally some commands for the server admins:' + '2': '&7More commands for server admins:' + '3': '&7Even more commands for server admins:' + DESCRIPTION: Display a help page + SOTW: + DESCRIPTION: Turn sotw on/off + HOME: + DENIED: '&8(&c!&8) &7Sorry, you cannot teleport to the home of %s' + DISABLED: '&8(&c!&8) &7Sorry, Faction homes are disabled on this server' + TELEPORTDISABLED: '&8(&c!&8) &7Sorry, the ability to teleport to Faction homes + is disabled on this server' + NOHOME: '&8(&c!&8) &7Your faction does not have a home ' + INENEMY: '&8(&c!&8) &7You cannot teleport to your faction home while in the territory + of an enemy faction' + WRONGWORLD: '&8(&c!&8) &7You cannot teleport to your faction home while in a different + world' + ENEMYNEAR: '&8(&c!&8) &7You cannot teleport to your faction home while an enemy + is within %s blocks of you' + TOTELEPORT: to teleport to your faction home + FORTELEPORT: for teleporting to your faction home + DESCRIPTION: Teleport to the faction home + INVITE: + TOINVITE: to invite someone + FORINVITE: for inviting someone + CLICKTOJOIN: Click to join! + INVITEDYOU: ' has invited you to join ' + INVITED: '&8(&a!&8) &7%1$s&7 invited %2$s&7 to your faction' + ALREADYMEMBER: '&8(&c!&8) &7%1$s&7 is already a member of %2$s' + DESCRIPTION: Invite a player to your faction + BANNED: '&8(&c!&8) &7&7%1$s &cis banned from your Faction Not sending an invite' + JOIN: + CANNOTFORCE: '&8(&c!&8) &7You do not have permission to move other players into + a faction' + SYSTEMFACTION: '&8(&c!&8) &7Players may only join normal factions This is a system + faction' + ALREADYMEMBER: '&8(&c!&8) &7%1$s %2$s already a member of %3$s' + ATLIMIT: '&8(&c!&8) &7The faction %1$s is at the limit of %2$d members, so %3$s + cannot currently join' + INOTHERFACTION: '&8(&c!&8) &7%1$s must leave %2$s current faction first' + NEGATIVEPOWER: '&8(&c!&8) &7%1$s cannot join a faction with a negative power level' + REQUIRESINVITATION: '&8(&c!&8) &7This faction requires invitation' + ATTEMPTEDJOIN: '&8(&c!&8) &7%1$s&7 tried to join your faction' + TOJOIN: to join a faction + FORJOIN: for joining a faction + SUCCESS: '&8(&a!&8) &7%1$s successfully joined %2$s' + MOVED: '&8(&a!&8) &7%1$s moved you into the faction %2$s' + JOINED: '&8(&a!&8) &7%1$s joined your faction' + JOINEDLOG: '&8(&a!&8) &7%1$s joined the faction %2$s' + MOVEDLOG: '&8(&a!&8) &7%1$s moved the player %2$s into the faction %3$s' + DESCRIPTION: Join a faction + BANNED: '&8(&c!&8) &7You are banned from %1$s' + ALT: + OPEN: '&8(&a!&8) &7Successfully opened %1$s &7to alts with code &a%2$s&7' + ALREADYOPEN: '&8(&c!&8) &7%1$s &cis already open to alts with code %2$s' + CLOSE: '&8(&a!&8) &7Successfully closed %1$s &7to new alts' + ALREADYCLOSED: '&8(&c!&8) &7%1$s &cis already closed to alts' + NOTOPEN: '&8(&c!&8) &7%1$s &cis not open to new alts!' + WRONGCODE: '&8(&c!&8) &7%1$s &cis not the correct code for %2$s&c!' + SUCCESS: '&8(&a!&8) &7&7%1$s &7successfully joined %2$s &7as an alt' + USAGE: Faction alt control commands + OPENUSAGE: Open a faction to new alts + CLOSEUSAGE: Close a faction to new alts + JOINUSAGE: Join a faction as an alt + KICK: + CANDIDATES: 'Players you can kick: ' + CLICKTOKICK: 'Click to kick ' + SELF: '&8(&c!&8) &7You cannot kick yourself' + NONE: That player is not in a faction + NOTMEMBER: '&8(&c!&8) &7%1$s&c is not a member of %2$s' + INSUFFICIENTRANK: '&8(&c!&8) &7Your rank is too low to kick this player' + NEGATIVEPOWER: '&8(&c!&8) &7You cannot kick that member until their power is positive' + TOKICK: to kick someone from the faction + FORKICK: for kicking someone from the faction + FACTION: '&8(&a!&8) &7%1$s&7 kicked %2$s&7 from the faction' + KICKS: '&8(&a!&8) &7You kicked %1$s&7 from the faction %2$s&7' + KICKED: '&8(&a!&8) &7%1$s&7 kicked you from %2$s&7' + DESCRIPTION: Kick a player from the faction + LIST: + FACTIONLIST: 'Faction List ' + TOLIST: to list the factions + FORLIST: for listing the factions + ONLINEFACTIONLESS: 'Online factionless: ' + DESCRIPTION: See a list of the factions + LISTCLAIMS: + MESSAGE: '&8(&a!&8) &7Claims by %s&7 in %s:' + INVALIDWORLD: '&8(&c!&8) &7nvalid world name %s' + NOCLAIMS: '&8(&c!&8) &7No claims by %s&7 in world %s' + DESCRIPTION: List your faction's claims + LOCK: + LOCKED: '&7Factions is now locked' + UNLOCKED: '&7Factions in now unlocked' + DESCRIPTION: Lock all write stuff Apparently + LOGINS: + TOGGLE: '&7Set login / logout notifications for Faction members to: &a%s' + DESCRIPTION: Toggle(?) login / logout notifications for Faction members + MAP: + TOSHOW: to show the map + FORSHOW: for showing the map + UPDATE: + ENABLED: '&8(&a!&8) &7Map auto update &2ENABLED' + DISABLED: '&8(&c!&8) &7Map auto update &4DISABLED' + DESCRIPTION: Show the territory map, and set optional auto update + MAPHEIGHT: + DESCRIPTION: '&7Update the lines that /f map sends' + SET: '&7Set /f map lines to &a%1$d' + CURRENT: '&7Current mapheight: &a%1$d' + MOD: + CANDIDATES: 'Players you can promote: ' + CLICKTOPROMOTE: 'Click to promote ' + NOTMEMBER: '%1$s&c is not a member in your faction' + NOTADMIN: '&8(&c!&8) &7You are not the faction admin' + SELF: '&8(&c!&8) &7The target player musn''t be yourself' + TARGETISADMIN: '&8(&c!&8) &7The target player is a faction admin Demote them first' + REVOKES: '&8(&c!&8) &7You have removed moderator status from %1$s&7' + REVOKED: '&8(&c!&8) &7%1$s&7 is no longer moderator in your faction' + PROMOTES: '&8(&c!&8) &7%1$s&7 was promoted to moderator in your faction' + PROMOTED: '&8(&c!&8) &7&7You have promoted %1$s&7 to moderator' + DESCRIPTION: Give or revoke moderator rights + MODIFYPOWER: + ADDED: '&7Added &a%1$f &7power to &a%2$s &7New total rounded power: &a%3$d' + DESCRIPTION: Modify the power of a faction/player + MONEY: + LONG: '&7The faction money commands' + DESCRIPTION: Faction money commands + MONEYBALANCE: + SHORT: show faction balance + DESCRIPTION: Show your factions current money balance + MONEYDEPOSIT: + DESCRIPTION: Deposit money + DEPOSITED: '&8(&a!&8) &7%1$s deposited %2$s in the faction bank: %3$s' + MONEYTRANSFERFF: + DESCRIPTION: Transfer f -> f + TRANSFER: '&8(&a!&8) &7%1$s transferred %2$s from the faction "%3$s" to the faction + "%4$s"' + MONEYTRANSFERFP: + DESCRIPTION: Transfer f -> p + TRANSFER: '&8(&a!&8) &7%1$s transferred %2$s from the faction "%3$s" to the player + "%4$s"' + MONEYTRANSFERPF: + DESCRIPTION: Transfer p -> f + TRANSFER: '&8(&a!&8) &7%1$s transferred %2$s from the player "%3$s" to the faction + "%4$s"' + MONEYWITHDRAW: + DESCRIPTION: Withdraw money + WITHDRAW: '&8(&a!&8) &7%1$s withdrew %2$s from the faction bank: %3$s' + NEAR: + DESCRIPTION: Show nearby faction members + PLAYER: '&a&l{role-prefix}&8{name} (&a{distance}m&8)' + PLAYERLIST: '&7Near: {players-nearby}' + NONE: '&8None' + OPEN: + TOOPEN: to open or close the faction + FOROPEN: for opening or closing the faction + OPEN: open + CLOSED: closed + CHANGES: '%1$s&7 changed the faction to &a%2$s&7' + CHANGED: '&7The faction %1$s&7 is now %2$s' + DESCRIPTION: Switch if invitation is required to join + OWNER: + DISABLED: '&8(&c!&8) &7Sorry, but owned areas are disabled on this server' + LIMIT: '&8(&c!&8) &7Sorry, but you have reached the server''s &alimit of %1$d + &cowned areas per faction' + WRONGFACTION: '&8(&c!&8) &7This land is not claimed by your faction, so you can''t + set ownership of it' + NOTCLAIMED: '&8(&c!&8) &7This land is not claimed by a faction Ownership is not + possible' + NOTMEMBER: '%1$s&7 is not a member of this faction' + CLEARED: '&7You have cleared ownership for this claimed area' + REMOVED: '&7You have removed ownership of this claimed land from %1$s&7' + TOSET: to set ownership of claimed land + FORSET: for setting ownership of claimed land + ADDED: '&7You have added %1$s&7 to the owner list for this claimed land' + DESCRIPTION: Set ownership of claimed land + OWNERLIST: + DISABLED: '&8(&c!&8) &7Sorry, but owned areas are disabled on this server' + WRONGFACTION: '&8(&c!&8) &7This land is not claimed by your faction' + NOTCLAIMED: '&7This land is not claimed by any faction, thus no owners' + NONE: '&7No owners are set here; everyone in the faction has access' + OWNERS: '&7Current owner(s) of this land: %1$s' + DESCRIPTION: List owner(s) of this claimed land + PEACEFUL: + DESCRIPTION: Set a faction to peaceful + YOURS: '%1$s has %2$s your faction' + OTHER: '%s&7 has %s the faction ''%s&7''' + GRANT: granted peaceful status to + REVOKE: removed peaceful status from + PERM: + DESCRIPTION: '&aEdit or list your Faction''s permissions' + INVALID: + RELATION: Invalid relation defined Try something like 'ally' + ACCESS: Invalid access defined Try something like 'allow' + ACTION: Invalid action defined Try something like 'build' + SET: '&8(&c!&8) &7Cannot set a locked permission' + SET: '&aSet permission &7%1$s &ato &b%2$s &afor relation &c%3$s' + TOP: RCT MEM OFF ALLY TRUCE NEUT ENEMY + PERMANENT: + DESCRIPTION: Toggles a faction's permanence + GRANT: added permanent status to + REVOKE: removed permanent status from + YOURS: '%1$s has %2$s your faction' + OTHER: '%s&7 has %s the faction ''%s&7''' + PROMOTE: + TARGET: You've been %1$s to %2$s + ISALT: That player is an alt! + SUCCESS: You successfully %1$s %2$s to %3$s + PROMOTED: promoted + DEMOTED: demoted + DESCRIPTION: /f promote + WRONGFACTION: '&8(&c!&8) &7%1$s is not part of your faction' + NOTTHATPLAYER: That player cannot be promoted + NOT: + ALLOWED: You can't promote or demote that player + PERMANENTPOWER: + DESCRIPTION: Toggle faction power permanence + GRANT: added permanentpower status to + REVOKE: removed permanentpower status from + SUCCESS: '&7You %s &a%s&7' + FACTION: '%s&7 %s your faction' + NOACCESS: You don't have access to that + POWER: + TOSHOW: to show player power info + FORSHOW: for showing player power info + POWER: '%1$s&a - Power / Maxpower: &7%2$d / %3$d %4$s' + BONUS: ' (bonus: ' + PENALTY: ' (penalty: ' + DESCRIPTION: Show player power info + POWERBOOST: + HELP: + '1': '&8(&c!&8) &7You must specify "p" or "player" to target a player or "f" + or "faction" to target a faction' + '2': '&8(&c!&8) &7ex /f powerboost p SomePlayer 05 -or- /f powerboost f SomeFaction + -5' + INVALIDNUM: '&8(&c!&8) &7You must specify a valid numeric value for the power + bonus/penalty amount' + PLAYER: Player "%1$s" + FACTION: Faction "%1$s" + BOOST: '&7%1$s now has a power bonus/penalty of %2$d to min and max power levels' + BOOSTLOG: '%1$s has set the power bonus/penalty for %2$s to %3$d' + DESCRIPTION: Apply permanent power bonus/penalty to specified player or faction + RELATIONS: + ALLTHENOPE: '&8(&c!&8) &7Nope. You cannot' + MORENOPE: '&8(&c!&8) &7You cannot declare a relation to yourself' + ALREADYINRELATIONSHIP: '&8(&c!&8) &7You already have that relation wish set with + %1$s' + TOMARRY: to change a relation wish + FORMARRY: for changing a relation wish + MUTUAL: '&8(&a!&8) &7Your faction is now %1$s&7 to %2$s' + PEACEFUL: '&8(&c!&8) &7This will have no effect while your faction is peaceful' + PEACEFULOTHER: '&8(&c!&8) &7This will have no effect while their faction is peaceful' + DESCRIPTION: Set relation wish to another faction + EXCEEDS: + ME: '&7Failed to set relation wish You can only have %1$s %2$s' + THEY: '&7Failed to set relation wish They can only have %1$s %2$s' + PROPOSAL: + '1': '&8(&a!&8) &7%1$s&7 wishes to be your %2$s' + '2': '&7Type &a/%1$s %2$s %3$s&7 to accept' + SENT: '%1$s&7 were informed that you wish to be %2$s' + RELOAD: + TIME: '&8(&a!&8) &7Reloaded &aall configuration files &7from disk, took &a%1$d + ms&7' + DESCRIPTION: Reload data file(s) from disk + ROSTER: + USAGE: Control your faction's roster + ROTATE: + FULL: You can't rotate into your faction! There isn't enough room! + SUCCESS: '%1$s &7rotated into %2$s&7' + OUT: '%1$s &7was rotated out of %2$s&7' + JOIN: '%1$s &7joined %2$s&7''s roster' + LIST: + USAGE: List your faction's roster + NOROSTER: '&8(&c!&8) &7You aren''t on a roster' + HEADER: '%1$s&7''s roster' + FORMAT: '&7<&a!&7> %1$s &8- &7%2$s' + HELP: + USAGE: View info about how rosters work + USED: |- + &7Rosters are very simple on this server! + &8&m------------------------------------------------ + &7Invite players using the &a/f invite &7command and they'll be automatically added to your roster when they use &a/f join&7 + &8&m------------------------------------------------ + &7Rotations are done via the &a/f join &7command as well + &7Simply type &a/f join (your-faction)&7 and you will be automatically rotated into your current roster + &8&m------------------------------------------------ + &7Managing your roster is easy as well + &7If you would like to &cremove &7someone from your roster, just use the &a/f kick &7command! + &7Promotions are handled as if the player were in your faction as well, just use the &a/f promote&7 command! + LEAVE: + CONFIRM: '&8(&c!&8) &7Are you sure you want to leave your faction? Roster rotations + are done automatically! Leaving your faction will remove you from your roster' + STRIKE: + LIST: + USAGE: List a faction's strikes + NOFACTION: '&8(&c!&8) &7You need to specify a faction!' + HEADER: '%1$s&7''s strike info:' + FORMAT: '&7<&a%1$s&7> %2$s &8- &7%3$s' + BLAMELESS: '%1$s &7hasn''t been striked' + GIVE: + USAGE: Give a faction a strike They broke the rules! + SUCCESS: '&7Given %1$s &7a strike for &a%2$s' + TAKE: + USAGE: Take a strike from a faction We're sorry :( + DOESNTEXIST: '&8(&c!&8) &7That strike doesn''t exist! Try a different index' + SUCCESS: '&7Removed a strike from %1$s&7' + USAGE: Strike commands for factions + STEALTH: + DESCRIPTION: Toggles stealth mode + TOGGLE: '&8(&c!&8) &7Stealth mode has been %1$s' + MISSIONS: + USAGE: View and manage missions + SAFEUNCLAIMALL: + DESCRIPTION: Unclaim all safe zone land + UNCLAIMED: '&7You unclaimed ALL safe zone land' + UNCLAIMEDLOG: '%1$s unclaimed all safe zones' + SAVEALL: + SUCCESS: '&7Factions saved to disk!' + DESCRIPTION: Save all data to disk + SCOREBOARD: + DESCRIPTION: Scoreboardy things + SETDEFAULTROLE: + DESCRIPTION: /f defaultrole - set your Faction's default role + NOTTHATROLE: You cannot set the default to admin + SUCCESS: Set default role of your faction to %1$s + INVALIDROLE: Couldn't find matching role for %1$s + SETFWARP: + NOTCLAIMED: '&7You can only set warps in your faction territory' + LIMIT: '&7Your Faction already has the max amount of warps set &a(%1$d)' + SET: '&7Set warp &a%1$s&7 and password &b''%2$s'' &7to your location' + TOSET: to set warp + FORSET: for setting warp + DESCRIPTION: Set a faction warp + SETHOME: + DISABLED: '&8(&c!&8) &7Sorry, Faction homes are disabled on this server' + NOTCLAIMED: '&8(&c!&8) &7Sorry, your faction home can only be set inside your + own claimed territory' + TOSET: to set the faction home + FORSET: for setting the faction home + SET: '%1$s&7 set the home for your faction You can now use:' + SETOTHER: '&8(&c!&8) &7You have set the home for the %1$s&7 faction' + DESCRIPTION: Set the faction home + SETMAXVAULTS: + DESCRIPTION: Set max vaults for a Faction + SUCCESS: '&aSet max vaults for &7%s &ato &b%d' + SETPAYPAL: + DESCRIPTION: Set paypal for your faction + NOTADMIN: '&8(&c!&8) &7You must be a faction admin to setpaypal' + NOTVALID: '&8(&c!&8) &7%1$s isn''t a valid email address!' + SUCCESS: '&7Set &ayour faction&7''s paypal link to &c%1$s&7' + SEEPAYPAL: + DESCRIPTION: Set paypal for your faction + ISNTSET: '%1$s&7''s paypal link has not been set' + SEE: '%1$s''s paypal link is &a%2$s' + TNT: + TERRITORYONLY: '&8(&c!&8) &7Command can only be run from your faction''s territory!' + ADMINSET: + DESCRIPTION: Add to a faction's TNT bank + USAGE: '&8(&c!&8) &7Set tnt as an admin' + DEPOSIT: + DESCRIPTION: Add to your faction's TNT bank + FAIL: + FULL: '&8(&c!&8) &7Faction bank already at maximum' + NOTENOUGH: '&8(&c!&8) &7You do not have that much TNT' + POSITIVE: '&8(&c!&8) &7Must deposit at least one' + SUCCESS: '&8(&a!&8) &7Your faction now has %d TNT' + FILL: + DESCRIPTION: Fill TNT into nearby dispensers + MESSAGE: '&8(&a!&8) &7Filled %d TNT into %d dispensers %d left in the faction + bank' + FAIL: + MAXRADIUS: '&8(&c!&8) &7%d is bigger than the maximum radius of %d' + NOTENOUGH: '&8(&c!&8) &7The faction bank does not have %d TNT!' + NEEDMORE: '&8(&c!&8) &7You would need %d tnt to fill that many dispensers! + The most you can do is %d per!' + POSITIVE: '&8(&c!&8) &7Positive values only!' + INFO: + DESCRIPTION: View your faction's TNT bank + MESSAGE: '&7Your faction has &c%1$s &7out of &c%2$s &7TNT' + SIPHON: + DESCRIPTION: Take TNT from nearby dispensers + MESSAGE: '&8(&c!&8) &7Acquired %d TNT, for a total of %d in the faction bank' + FAIL: + POSITIVE: '&8(&c!&8) &7Positive values only!' + FULL: '&8(&c!&8) &7Faction bank already at maximum!' + MAXRADIUS: '&8(&c!&8) &7%d is bigger than the maximum radius of %d' + WITHDRAW: + DESCRIPTION: Withdraw TNT from the faction bank + MESSAGE: '&8(&a!&8) &7Withdrew %d TNT %d left in the faction bank' + FAIL: + NOTENOUGH: '&8(&c!&8) &7The faction bank does not have %d TNT!' + POSITIVE: '&8(&c!&8) &7Positive values only!' + UPGRADE: + NOT: + ENOUGH: '&8(&c!&8) &7You don''t have enough money to upgrade that!' + ALREADY: + MAX: '&8(&c!&8) &7That is already maxed out!' + SUCCESSFUL: '&7Successfully upgraded &a%1$s &7to level &a%2$s&7' + DESCRIPTION: Upgrade your faction + VAULT: + DESCRIPTION: /f vault to open one of your Faction's vaults + TOOHIGH: '&8(&c!&8) &7You tried to open vault %d but your Faction only has %d + vaults' + SEECHUNK: + DESCRIPTION: Show chunk boundaries + TOGGLE: '&7Seechunk &a%1$s' + SHOW: + NOFACTION: + SELF: You are not in a faction + OTHER: That's not a faction + TOSHOW: to show faction information + FORSHOW: for showing faction information + DESCRIPTION: '&aDescription: &7%1$s' + PEACEFUL: This faction is Peaceful + PERMANENT: '&aThis faction is permanent, remaining even with no members' + JOINING: '&aJoining: &7%1$s ' + INVITATION: invitation is required + UNINVITED: no invitation is needed + NOHOME: N/A + POWER: '&aLand / Power / Maxpower: &7 %1$d/%2$d/%3$d %4$s' + BONUS: ' (bonus: ' + PENALTY: ' (penalty: ' + DEPRECIATED: (%1$s depreciated) + LANDVALUE: '&aTotal land value: &7%1$s %2$s' + BANKCONTAINS: '&aBank contains: &7%1$s' + ALLIES: 'Allies: ' + ENEMIES: 'Enemies: ' + MEMBERSONLINE: 'Members online: ' + MEMBERSOFFLINE: 'Members offline: ' + COMMANDDESCRIPTION: Show faction information + DEATHS: + TIL: + RAIDABLE: '&7DTR: %1$d' + EXEMPT: '&8(&c!&8) &7This faction is exempt and cannot be seen' + SHOWINVITES: + PENDING: 'Players with pending invites: ' + CLICKTOREVOKE: Click to revoke invite for %1$s + DESCRIPTION: Show pending faction invites + STATUS: + FORMAT: '%1$s Power: %2$s Last Seen: %3$s' + ONLINE: Online + AGOSUFFIX: ' ago' + DESCRIPTION: Show the status of a player + STUCK: + TIMEFORMAT: m 'minutes', s 'seconds' + CANCELLED: '&aTeleport cancelled because you were damaged' + OUTSIDE: '&aTeleport cancelled because you left &7%1$d &ablock radius' + EXISTS: '&aYou are already teleporting, you must wait &7%1$s' + START: '&aTeleport will commence in &7%s&a Don''t take or deal damage ' + TELEPORT: '&aTeleported safely to %1$d, %2$d, %3$d' + TOSTUCK: to safely teleport %1$s out + FORSTUCK: for %1$s initiating a safe teleport out + DESCRIPTION: Safely teleports you out of enemy faction + TAG: + TAKEN: '&8(&c!&8) &7That tag is already taken' + TOCHANGE: to change the faction tag + FORCHANGE: for changing the faction tag + FACTION: '%1$s&7 changed your faction tag to %2$s' + CHANGED: '&7The faction %1$s&7 changed their name to %2$s' + DESCRIPTION: Change the faction tag + TITLE: + TOCHANGE: to change a players title + FORCHANGE: for changing a players title + CHANGED: '%1$s&7 changed a title: %2$s' + DESCRIPTION: Set or remove a players title + TOGGLEALLIANCECHAT: + DESCRIPTION: Toggles whether or not you will see alliance chat + IGNORE: Alliance chat is now ignored + UNIGNORE: Alliance chat is no longer ignored + TOGGLESB: + DISABLED: You can't toggle scoreboards while they are disabled + TOP: + DESCRIPTION: Sort Factions to see the top of some criteria + TOP: Top Factions by %s Page %d/%d + LINE: '%d &a%s: &c%s' + INVALID: Could not sort by %s Try balance, online, members, power or land + UNBAN: + DESCRIPTION: Unban someone from your Faction + NOTBANNED: '&7%s &cisn''t banned Not doing anything' + UNBANNED: '&7%1$s &cunbanned &7%2$s' + TARGET: '&aYou were unbanned from &r%s' + UNCLAIM: + SAFEZONE: + SUCCESS: '&7Safe zone was unclaimed' + NOPERM: '&8(&c!&8) &7This is a safe zone You lack permissions to unclaim' + WARZONE: + SUCCESS: '&7War zone was unclaimed' + NOPERM: '&8(&c!&8) &7This is a war zone You lack permissions to unclaim' + UNCLAIMED: '%1$s&7 unclaimed some of your land' + UNCLAIMEDAMOUNT: '%1$s&7 unclaimed &a%2$s &7land' + UNCLAIMS: '&7You unclaimed this land' + WRONGFACTIONOTHER: '&8(&c!&8) &7Attempted to unclaim land for incorrect faction' + LOG: '%1$s unclaimed land at (%2$s) from the faction: %3$s' + WRONGFACTION: '&8(&c!&8) &7You don''t own this land' + TOUNCLAIM: to unclaim this land + FORUNCLAIM: for unclaiming this land + FACTIONUNCLAIMED: '%1$s&7 unclaimed some land' + DESCRIPTION: Unclaim the land where you are standing + UNCLAIMALL: + TOUNCLAIM: to unclaim all faction land + FORUNCLAIM: for unclaiming all faction land + UNCLAIMED: '&8(&a!&8) &7%1$s&7 unclaimed ALL of your faction''s land' + LOG: '%1$s unclaimed everything for the faction: %2$s' + DESCRIPTION: Unclaim all of your factions land + VERSION: + VERSION: '&8(&a!&8) &7You are running %1$s' + DESCRIPTION: Show plugin and translation version information + WARUNCLAIMALL: + DESCRIPTION: Unclaim all war zone land + SUCCESS: '&7You unclaimed ALL war zone land' + LOG: '%1$s unclaimed all war zones' +command: + help: + invitations: '&7You might want to close it and use invitations:' +LEAVE: + PASSADMIN: '&8(&a!&8) &7You must give the admin role to someone else first' + NEGATIVEPOWER: '&8(&c!&8) &7You cannot leave until your power is positive' + TOLEAVE: to leave your faction + FORLEAVE: for leaving your faction + LEFT: '&8(&c!&8) &7%s&7 left faction %s&7' + DISBANDED: '&8(&c!&8) &7%s&7 was disbanded' + DISBANDEDLOG: The faction %s (%s) was disbanded due to the last player (%s) leaving + DESCRIPTION: Leave your faction +CLAIM: + PROTECTED: '&8(&c!&8) &7This land is protected' + DISABLED: '&8(&c!&8) &7Sorry, this world has land claiming disabled' + CANTCLAIM: '&8(&c!&8) &7You can''t claim land for &a%s&c' + ALREADYOWN: '%s&7 already own this land' + MUSTBE: '&8(&c!&8) &7You must be &a%s&c to claim land' + MEMBERS: Factions must have at least &a%s&c members to claim land + SAFEZONE: '&8(&c!&8) &7You can not claim a safe zone' + WARZONE: '&8(&c!&8) &7You can not claim a war zone' + POWER: '&8(&c!&8) &7You can''t claim more land! You need more power!' + DTR: + LAND: '&8(&c!&8) &7You can''t claim more land!' + LIMIT: '&8(&c!&8) &7Limit reached You can''t claim more land!' + ALLY: '&8(&c!&8) &7You can''t claim the land of your allies' + CONTIGIOUS: '&8(&c!&8) &7You can only claim additional land which is connected to + your first claim or controlled by another faction!' + FACTIONCONTIGUOUS: '&8(&c!&8) &7You can only claim additional land which is connected + to your first claim!' + PEACEFUL: '%s&7 owns this land Your faction is peaceful, so you cannot claim land + from other factions' + PEACEFULTARGET: '%s&7 owns this land, and is a peaceful faction You cannot claim + land from them' + THISISSPARTA: '%s&7 owns this land and is strong enough to keep it' + BORDER: '&8(&c!&8) &7You must start claiming land at the border of the territory' + TOCLAIM: to claim this land + FORCLAIM: for claiming this land + TOOVERCLAIM: to overclaim this land + FOROVERCLAIM: for over claiming this land + CLAIMED: '&a%s&7 claimed land for &a%s&7 from &a%s&7' + CLAIMEDAMOUNT: '&a%s&7 claimed &a%s &7land for &a%s&7' + CLAIMEDLOG: '%s claimed land at (%s) for the faction: %s' + OVERCLAIM: + DISABLED: '&7Over claiming is disabled on this server' + TOOCLOSETOOTHERFACTION: '&7Your claim is too close to another Faction Buffer required + is %d' + OUTSIDEWORLDBORDER: '&7Your claim is outside the border' + OUTSIDEBORDERBUFFER: '&7Your claim is outside the border %d chunks away world edge + required' + CLICK: + TO: + CLAIM: Click to try to claim &2(%1$d, %2$d) + YOUAREHERE: You are here +GENERIC: + YOU: you + YOURFACTION: your faction + NOPERMISSION: '&8(&c!&8) &7You don''t have permission to %1$s' + DOTHAT: do that + NOPLAYERMATCH: '&8(&c!&8) &7No player match found for "&3%1$s&c"' + NOPLAYERFOUND: '&8(&c!&8) &7No player "&3%1$s&c" could not be found' + NOFACTIONMATCH: '&8(&c!&8) &7No faction match found for "&3%1$s&c"' + ARGS: + TOOFEW: '&8(&c!&8) &7Too few arguments &7Use like this:' + TOOMANY: '&8(&c!&8) &7Strange argument "&a%1$s&7" &7Use the command like this:' + DEFAULTDESCRIPTION: Default faction description... + OWNERS: 'Owner(s): %1$s' + PUBLICLAND: Public faction land + FACTIONLESS: factionless + SERVERADMIN: A server admin + DISABLED: disabled + ENABLED: enabled + INFINITY: ∞ + CONSOLEONLY: This command cannot be run as a player + PLAYERONLY: '&8(&c!&8) &7This command can only be used by ingame players' + MEMBERONLY: '&8(&c!&8) &7You are not member of any faction' + ASKYOURLEADER: '&7 Ask your leader to:' + YOUSHOULD: '&7You should:' + YOUMAYWANT: '&7You may want to: ' + DISABLEDWORLD: '&8(&c!&8) &7Factions is disabled in this world' + YOUMUSTBE: '&8(&c!&8) &7You must be &a%s&c' + TRANSLATION: + VERSION: 'Translation: %1$s(%2$s,%3$s) State: %4$s' + CONTRIBUTORS: 'Translation contributors: %1$s' + RESPONSIBLE: 'Responsible for translation: %1$s' + FACTIONTAG: + BLACKLIST: '&7That faction tag is blacklisted' + TOOSHORT: '&7The faction tag can''t be shorter than &a%1$s&7 chars' + TOOLONG: '&7The faction tag can''t be longer than &a%s&7 chars' + ALPHANUMERIC: '&7Faction tag must be alphanumeric "&a%s&7" is not allowed' + PLACEHOLDER: +PLACEHOLDER: + ROLE: + NAME: None + CUSTOM: + FACTION: '{faction} ' +COMPASS: + SHORT: + NORTH: N + EAST: E + SOUTH: S + WEST: W +CHAT: + MOD: mod chat + FACTION: faction chat + ALLIANCE: alliance chat + TRUCE: truce chat + PUBLIC: public chat +ECON: + 'OFF': no %s + FORMAT: '###,######' + DISABLED: Faction econ is disabled + OVER: + BAL: + CAP: '&4The amount &7%s &4is over Essentials'' balance cap' + BALANCE: '&a%s''s&7 balance is &a%s&7' + NOPERM: '&a%s&7 lacks permission to control &a%s''s&7 money' + CANTAFFORD: + TRANSFER: '&a%s can''t afford to transfer &a%s to %s' + AMOUNT: '&a%s&7 can''t afford &a%s&7 %s' + TRANSFER: + UNABLE: Unable to transfer %s to &a%s from &a%s + NOINVOKER: '&a%s&7 was transferred from &a%s&7 to &a%s&7' + GAVE: '&a%s&7 &agave %s&7 to &a%s&7' + TOOK: '&a%s&7 &atook %s&7 from &a%s&7' + TRANSFER: '&a%s&7 transferred &a%s&7 from &a%s&7 to &a%s&7' + GAIN: + SUCCESS: '&a%s&7 gained &a%s&7 %s' + FAILURE: '&a%s&7 would have gained &a%s&7 %s, but the deposit failed' + LOST: + SUCCESS: '&a%s&7 lost &a%s&7 %s' + FAILURE: '&a%s&7 can''t afford &a%s&7 %s' +RELATION: + MEMBER: + SINGULAR: member + PLURAL: members + ALLY: + SINGULAR: ally + PLURAL: allies + TRUCE: + SINGULAR: truce + PLURAL: truces + NEUTRAL: + SINGULAR: neutral + PLURAL: neutrals + ENEMY: + SINGULAR: enemy + PLURAL: enemies +ROLE: + ADMIN: admin + COLEADER: coleader + MODERATOR: moderator + NORMAL: normal member + RECRUIT: recruit + ALT: alt +REGION: + SAFEZONE: safezone + WARZONE: warzone + WILDERNESS: wilderness + PEACEFUL: peaceful territory +PLAYER: + CANTADDTHATITEM: '&8(&c!&8) &7You cant put that item in your f chest!' + CANTHURT: '&7You may not harm other players in %s' + SAFEAUTO: '&7This land is now a safe zone' + WARAUTO: '&7This land is now a war zone' + OUCH: '&8(&c!&8) &7Ouch, that is starting to hurt You should give it a rest' + USE: + WILDERNESS: '&8(&c!&8) &7You can''t use &a%s&c in the wilderness' + SAFEZONE: '&8(&c!&8) &7You can''t use &a%s&c in a safe zone' + WARZONE: '&8(&c!&8) &7You can''t use &a%s&c in a war zone' + TERRITORY: '&8(&c!&8) &7You can''t &a%s&c in the territory of &a%s&c' + OWNED: '&8(&c!&8) &7You can''t use &a%s&c in this territory, it is owned by: %s&c' + COMMAND: + WARZONE: '&8(&c!&8) &7You can''t use the command ''%s'' in war zone' + NEUTRAL: '&8(&c!&8) &7You can''t use the command ''%s'' in neutral territory' + ENEMY: '&8(&c!&8) &7You can''t use the command ''%s'' in enemy territory' + PERMANENT: '&8(&c!&8) &7You can''t use the command ''%s'' because you are in a + permanent faction' + ALLY: '&8(&c!&8) &7You can''t use the command ''%s'' in ally territory' + WILDERNESS: '&8(&c!&8) &7You can''t use the command ''%s'' in the wilderness' + SOTW: + NOFLY: '&8(&c!&8) &7You cannot fly during SOTW!' + PORTAL: + NOTALLOWED: '&8(&c!&8) &7Destination portal can''t be created there' + POWER: + NOLOSS: + PEACEFUL: '&7You didn''t lose any power since you are in a peaceful faction' + WORLD: '&7You didn''t lose any power due to the world you died in' + WILDERNESS: '&7You didn''t lose any power since you were in the wilderness' + WARZONE: '&7You didn''t lose any power since you were in a war zone' + LOSS: + WARZONE: |- + &cThe world you are in has power loss normally disabled, but you still lost power since you were in a war zone + &7Your power is now &a%d / %d + NOW: '&7Your power is now &a%d / %d' + PVP: + LOGIN: '&7You can''t hurt other players for %d seconds after logging in' + REQUIREFACTION: '&7You can''t hurt other players until you join a faction' + FACTIONLESS: '&7You can''t hurt players who are not currently in a faction' + PEACEFUL: '&7Peaceful players cannot participate in combat' + NEUTRAL: '&7You can''t hurt neutral factions Declare them as an enemy' + CANTHURT: '&7You can''t hurt %s&7' + NEUTRALFAIL: '&7You can''t hurt %s&7 in their own territory unless you declare + them as an enemy' + TRIED: '%s&7 tried to hurt you' +PERM: + BUILD: Building blocks + DESTROY: Breaking blocks + PAINBUILD: If allow, can build but hurts to do so + ITEM: Using items + CONTAINER: Opening any block that can store items + BUTTON: Using buttons + DOOR: Opening doors + LEVER: Using levers + PLATE: Using pressure plates + FROSTWALK: Walking on water with the frostwalk enchantment + INVITE: Inviting others to join the faction + KICK: Kicking members from the faction + BAN: Banning players from the faction + PROMOTE: Promoting members of the faction + DISBAND: Disbanding the entire faction + ECONOMY: Spending faction money + TERRITORY: Claiming or unclaiming faction territory + HOME: Visiting the faction home + REPEATER: Changing repeaters + SETHOME: Setting the faction home + LISTCLAIMS: View listed faction claims + SETWARP: Setting and unsetting faction warps + TNTDEPOSIT: Deposit TNT into faction bank + TNTWITHDRAW: Withdraw TNT from faction bank + WARP: Using faction warps + FLY: Flying in faction territory + OWNER: Set ownership of land using /f owner in faction territory + ROSTERCONTROL: Control a faction's roster + TASKS: Manage a faction's tasks + SHORT: + BUILD: build + DESTROY: destroy + PAINBUILD: painbuild + ITEM: use items + CONTAINER: open containers + BUTTON: use buttons + DOOR: open doors + LEVER: use levers + PLATE: use pressure plates + FROSTWALK: frostwalk + INVITE: invite + KICK: kick + BAN: ban + PROMOTE: promote + DISBAND: disband + ECONOMY: spend faction money + TERRITORY: manage faction territory + HOME: visit home + SETHOME: set home + LISTCLAIMS: list claims + SETWARP: set warps + TNTDEPOSIT: deposit TNT + TNTWITHDRAW: withdraw TNT + REPEATER: change repeaters + WARP: use warps + FLY: fly + OWNER: set ownership + ROSTERCONTROL: control roster + TASKS: manage tasks + DENIED: + WILDERNESS: '&8(&c!&8) &7You can''t %s in the wilderness' + SAFEZONE: '&8(&c!&8) &7>You can''t %s in a safe zone' + WARZONE: '&8(&c!&8) &7You can''t %s in a war zone' + TERRITORY: '&8(&c!&8) &7You can''t %s in the territory of %s' + PAINTERRITORY: '&8(&c!&8) &7It is painful to %s in the territory of %s' + OWNED: '&8(&c!&8) &7You can''t %s in this territory, it is owned by: %s' + PAINOWNED: '&8(&c!&8) &7It is painful to try to %s in this territory, it is owned + by: %s' +GUI: + WARPS: + ONE: + PAGE: '%s warps' + PAGE: '%1$s warps (page %2$d)' + PERMS: + RELATION: + NAME: 'Choose a relation%s:' + ONLINEOFFLINEBIT: ' (%s)' + ACTION: + NAME: 'Permissions: %1$s%2$s' + ONLINEOFFLINEBIT: ' (%s)' + LOCKED: (Locked) + ALLOW: Allow + DENY: Deny + TOGGLE: Toggle online/offline + ONLINE: online + OFFLINE: offline + BUTTON: + NEXT: NEXT + PREV: PREVIOUS + BACK: BACK +NOPAGES: '&7Sorry No Pages available' +INVALIDPAGE: '&7Invalid page Must be between 1 and %1$d' +title: '&bFactions &0|&r' +wilderness: '&2Wilderness' +wilderness-description: '' +warzone: '&4Warzone' +warzone-description: Not the safest place to be +safezone: '&aSafezone' +safezone-description: Free from pvp and monsters +toggle-sb: You now have scoreboards set to {value} +faction-leave: '&8(&a!&8) &7Leaving %1$s&7, Entering %2$s' +faction-announcement-top: '&a--Unread Faction Announcements--' +faction-announcement-bottom: '&a--Unread Faction Announcements--' +default-prefix: '{relationcolor}[{faction}] &r' +faction-login: '&7%1$s &9logged in' +faction-logout: '&7%1$s &9logged out' +nofactions-prefix: '&8[&a-&8]&r' +date-format: MM/d/yy h:ma +raidable-true: 'true' +raidable-false: 'false' +WARMUPS: + NOTIFY: + FLIGHT: '&7Flight will enable in &a%2$d &7seconds' + TELEPORT: '&7You will teleport to &a%1$s &7in &a%2$d &7seconds' + ALREADY: '&8(&c!&8) &7You are already warming up' + CANCELLED: '&8(&c!&8) &7You have cancelled your warmup' +DTR: + CANNOT: + FROZEN: '&8(&c!&8) &7Action denied due to frozen DTR' + KICK: + PENALTY: '&8(&c!&8) &7Penalty DTR lost due to kicking with frozen DTR' + FROZEN: + STATUS: + MESSAGE: '%s' + 'TRUE': Frozen + 'FALSE': Not frozen + TIME: + MESSAGE: '%s' + NOTFROZEN: '' diff --git a/Factions/src/main/resources/lang/ja_JP.yml b/Factions/src/main/resources/lang/ja_JP.yml new file mode 100644 index 0000000..7fc0bba --- /dev/null +++ b/Factions/src/main/resources/lang/ja_JP.yml @@ -0,0 +1,434 @@ +# FactionsUUID「党派・一意な利用者識別子」言語ファイル +# &為に色コード使用 +# 愛で造った〜♥ + +root: + AUTHOR: Korikisulda + RESPONSIBLE: Korikisulda + LANGUAGE: Japanese + ENCODING: UTF-8 + LOCALE: ja_JP + REQUIRESUNICODE: 'true' + DEFAULT: 'false' + STATE: partial + LOCAL: + AUTHOR: エヴェリン雪「korikisulda」 + RESPONSIBLE: 'エヴェリン雪・ツイッター、IRC:「korikisulda」' + LANGUAGE: 日本語 + REGION: 日本 + STATE: 不全 +COMMAND: + ADMIN: + NOTMEMBER: '%sは党派の員になっていませんよ・' + NOTADMIN: アドミンではありません・ + TARGETSELF: 自分はターゲットになれません・ + DEMOTES: 党派アドミンから%sをデモートしました・ + DEMOTED: 党派アドミンから%sはデモートしました・. + PROMOTES: 党派アドミンに%sをプロモートしました + PROMOTED: '%sは%sを%sの党派アドミンにあげりました・' + AUTOCLAIM: + ENABLED: %s為にオート引取っています・ + DISABLED: オート引取っていません・ + REQUIREDRANK: %sになりません・ + OTHERFACTION: %s為に引取れません・. + AUTOHELP: + HELPFOR: ヘルプ・コマンド" + BOOM: + PEACEFULONLY: 安らかじゃない党派は爆発トグルが禁止です・ + TOTOGGLE: 爆発トグルし + FORTOGGLE: 爆発トグルした + ENABLED: '%s は爆発を%sしました' + BYPASS: + ENABLE: アドミンバイパスモードで入っています + ENABLELOG: はアドミンバイパスモードで入っています + DISABLE: アドミンバイパスモードで出た + DISABLELOG: はアドミンバイパスモードで出た + CHAT: + DISABLED: 党派チャットは禁止されました・ + INVALIDMODE: 不正なチャットモード・a,fかpと入力して下さい・ + MODE: + PUBLIC: 只公開チャットモード + ALLIANCE: 只連盟チャットモード + FACTION: 只党派チャットモード + CHATSPY: + ENABLE: チャットスパイモードで入ってします + ENABLELOG: はチャットスパイモードで入ってします + DISABLE: チャットスパイモードで出た + DISABLELOG: はチャットスパイモードで出た + CLAIM: + INVALIDRADIUS: 半径を指定しますなら1以上を指定して下さい・ + DENIED: 半径で引き取る許可がありません・ + CONFIG: + NOEXIST: 設定オプション"%s"はありません・ + SET: + 'TRUE': '"オプションは正に変わりました' + 'FALSE': '"オプションは正じゃなくに変わりました' + ADDED: '"%s" set: "%s" added.' + REMOVED: '"%s" set: "%s" removed.' + OPTIONSET: '" option set to ' + COLOURSET: '" color option set to "' + INTREQUIRED: 'Cannot set "%s": An integer (whole number) value required.' + LONGREQUIRED: 'Cannot set "%s": A long integer (whole number) value required.' + DOUBLEREQUIRED: 'Cannot set "%s": A double (numeric) value required.' + FLOATREQUIRED: 'Cannot set "%s": A float (numeric) value required.' + INVALID: + COLOUR: 'Cannot set "%s": "%s" is not a valid color.' + COLLECTION: '"%s" is not a data collection type which can be modified with this command.' + MATERIAL: 'Cannot change "%s" set: "%s" is not a valid material.' + TYPESET: '"%s" is not a data type set which can be modified with this command.' + MATERIAL: + ADDED: '"%s" set: Material "%s" added.' + REMOVED: '"%s" set: Material "%s" removed.' + LOG: ' (Command was run by %s.)' + ERROR: + SETTING: Error setting configuration setting "%s" to "%s". + MATCHING: Configuration setting "%s" couldn't be matched, though it should be... please report this error. + TYPE: '''%s'' is of type ''%s'', which cannot be modified with this command.' + CREATE: + MUSTLEAVE: You must leave your current faction first. + INUSE: That tag is already in use. + TOCREATE: to create a new faction + FORCREATE: for creating a new faction + ERROR: There was an internal error while trying to create your faction. Please try again. + CREATED: %s created a new faction %s + CREATEDLOG: ' は新しい党派を造りました: ' + YOUSHOULD: 'You should now: %s' + DEINVITE: + CANDEINVITE: 'Players you can deinvite: ' + CLICKTODEINVITE: 'Click to revoke invite for %s' + ALREADYMEMBER: '%s is already a member of %s' + MIGHTWANT: 'You might want to: %s' + REVOKED: '%s revoked your invitation to %s.' + REVOKES: '%s revoked %s''s invitation.' + DELFWARP: + DELETED: Deleted warp %s + INVALID: Couldn't find warp %s + TODELETE: to delete warp + FORDELETE: for deleting warp + DESCRIPTION: + CHANGES: 'You have changed the description for %s to:' + CHANGED: 'The faction %s changed their description to:' + TOCHANGE: to change faction description + FORCHANGE: for changing faction description + DISBAND: + IMMUTABLE: You cannot disband the Wilderness, SafeZone, or WarZone. + MARKEDPERMANENT: This faction is designated as permanent, so you cannot disband it. + BROADCAST: + YOURS: %s disbanded your faction. + NOTYOURS: %s disbanded the faction %s. + HOLDINGS: You have been given the disbanded faction's bank, totaling %s. + FWARP: + CLICKTOWARP: クリック為にワープ「テレポート」! + COMMANDFORMAT: /f warp <ワープ名> + WARPED: %sにテレポートしました + INVALID: %sが見つかりません + TOWARP: ワープし + FORWARPING: ワープした + WARPS: 'ワープリスト: ' + HELP: + '404': 指定ページは不正です・ + NEXTCREATE: Learn how to create a faction on the next page. + HOME: 'And don''t forget to set your home:' + BANK: + '1': Your faction has a bank which is used to pay for certain + '2': things, so it will need to have money deposited into it. + '3': To learn more, use the money command. + PLAYERTITLES: Player titles are just for fun. No rules connected to them. + OWNERSHIP: + '1': Claimed land with ownership set is further protected so + '2': that only the owner(s), faction admin, and possibly the + '3': faction moderators have full access. + RELATIONS: + '1': Set the relation you WISH to have with another faction. + '2': Your default relation with other factions will be neutral. + '3': If BOTH factions choose "ally" you will be allies. + '4': If ONE faction chooses "enemy" you will be enemies. + '5': You can never hurt members or allies. + '6': You can not hurt neutrals in their own territory. + '7': You can always hurt enemies and players without faction. + '8': '' + '9': Damage from enemies is reduced in your own territory. + '10': When you die you lose power. It is restored over time. + '11': The power of a faction is the sum of all member power. + '12': The power of a faction determines how much land it can hold. + '13': You can claim land from factions with too little power. + PERMISSIONS: + '1': Only faction members can build and destroy in their own + '2': 'territory. Usage of the following items is also restricted:' + '3': Door, Chest, Furnace, Dispenser, Diode. + '4': '' + '5': Make sure to put pressure plates in front of doors for your + '6': guest visitors. Otherwise they can't get through. You can + '7': also use this to create member only areas. + '8': As dispensers are protected, you can create traps without + '9': worrying about those arrows getting stolen. + ADMIN: + '1': /f claim safezone claim land for the Safe Zone + '2': /f claim warzone claim land for the War Zone + '3': /f autoclaim [safezone|warzone] take a guess + MOAR: + '1': 'Finally some commands for the server admins:' + '2': 'More commands for server admins:' + '3': 'Even more commands for server admins:' + HOME: + DISABLED: 党派ホームは禁止されました・ + TELEPORTDISABLED: 党派ホームテレポートは禁止されました・ + NOHOME: '党派のホームはありません' + INENEMY: You cannot teleport to your faction home while in the territory of an enemy faction. + WRONGWORLD: You cannot teleport to your faction home while in a different world. + ENEMYNEAR: You cannot teleport to your faction home while an enemy is within %s blocks of you. + TOTELEPORT: to teleport to your faction home + FORTELEPORT: for teleporting to your faction home + INVITE: + TOINVITE: to invite someone + FORINVITE: for inviting someone + CLICKTOJOIN: Click to join! + INVITEDYOU: ' has invited you to join ' + INVITED: '%s invited %s to your faction.' + ALREADYMEMBER: '%s is already a member of %s' + JOIN: + CANNOTFORCE: You do not have permission to move other players into a faction. + SYSTEMFACTION: Players may only join normal factions. This is a system faction. + ALREADYMEMBER: %s %s already a member of %s + ATLIMIT: ' ! The faction %s is at the limit of %d members, so %s cannot + currently join.' + INOTHERFACTION: %s must leave %s current faction first. + NEGATIVEPOWER: %s cannot join a faction with a negative power level. + REQUIRESINVITATION: This faction requires invitation. + ATTEMPTEDJOIN: '%s tried to join your faction.' + TOJOIN: to join a faction + FORJOIN: for joining a faction + SUCCESS: %s successfully joined %s. + MOVED: %s moved you into the faction %s. + JOINED: %s joined your faction. + JOINEDLOG: '%s joined the faction %s.' + MOVEDLOG: '%s moved the player %s into the faction %s.' + KICK: + CANDIDATES: 'Players you can kick: ' + CLICKTOKICK: 'Click to kick ' + SELF: You cannot kick yourself. + NONE: That player is not in a faction. + NOTMEMBER: '%s is not a member of %s' + INSUFFICIENTRANK: Your rank is too low to kick this player. + NEGATIVEPOWER: You cannot kick that member until their power is positive. + TOKICK: to kick someone from the faction + FORKICK: for kicking someone from the faction + FACTION: '%s kicked %s from the faction! :O' + KICKS: You kicked %s from the faction %s! + KICKED: '%s kicked you from %s! :O' + LIST: + FACTIONLIST: 'Faction List ' + TOLIST: to list the factions + FORLIST: for listing the factions + ONLINEFACTIONLESS: 'Online factionless: ' + LOCK: + LOCKED: Factions is now locked + UNLOCKED: Factions in now unlocked + MAP: + TOSHOW: to show the map + FORSHOW: for showing the map + UPDATE: + ENABLED: Map auto update ENABLED. + DISABLED: Map auto update DISABLED. + MOD: + CANDIDATES: 'Players you can promote: ' + CLICKTOPROMOTE: 'Click to promote ' + NOTMEMBER: '%s is not a member in your faction.' + NOTADMIN: You are not the faction admin. + SELF: The target player musn't be yourself. + TARGETISADMIN: The target player is a faction admin. Demote them first. + REVOKES: You have removed moderator status from %s. + REVOKED: '%s is no longer moderator in your faction.' + PROMOTES: '%s was promoted to moderator in your faction.' + PROMOTED: You have promoted %s to moderator. + MODIFYPOWER: + ADDED: 'Added %f power to %s. New total rounded power: %d' + MONEY: + SHORT: faction money commands + LONG: The faction money commands. + MONEYBALANCE: + SHORT: show faction balance + MONEYDEPOSIT: + SHORT: deposit money + DEPOSITED: '%s deposited %s in the faction bank: %s' + MONEYTRANSFERFF: + SHORT: transfer f -> f + TRANSFER: '%s transferred %s from the faction "%s" to the faction "%s"' + MONEYTRANSFERFP: + SHORT: transfer f -> p + TRANSFER: '%s transferred %s from the faction "%s" to the player "%s"' + MONEYTRANSFERPF: + SHORT: transfer p -> f + TRANSFER: '%s transferred %s from the player "%s" to the faction "%s"' + MONEYWITHDRAW: + SHORT: withdraw money + WITHDRAW: '%s withdrew %s from the faction bank: %s' + OPEN: + TOOPEN: to open or close the faction + FOROPEN: for opening or closing the faction + OPEN: open + CLOSED: closed + CHANGES: '%s changed the faction to %s.' + CHANGED: The faction %s is now %s + OWNER: + DISABLED: Sorry, but owned areas are disabled on this server. + LIMIT: Sorry, but you have reached the server's limit of %d owned areas per faction. + WRONGFACTION: This land is not claimed by your faction, so you can't set ownership of it. + NOTCLAIMED: This land is not claimed by a faction. Ownership is not possible. + NOTMEMBER: '%s is not a member of this faction.' + CLEARED: You have cleared ownership for this claimed area. + REMOVED: You have removed ownership of this claimed land from %s. + TOSET: to set ownership of claimed land + FORSET: for setting ownership of claimed land + ADDED: You have added %s to the owner list for this claimed land. + OWNERLIST: + DISABLED: Sorry, but owned areas are disabled on this server. + WRONGFACTION: This land is not claimed by your faction. + NOTCLAIMED: This land is not claimed by any faction, thus no owners. + NONE: No owners are set here; everyone in the faction has access. + OWNERS: 'Current owner(s) of this land: %s' + POWER: + TOSHOW: to show player power info + FORSHOW: for showing player power info + POWER: '%s - Power / Maxpower: %d / %d %s' + BONUS: ' (bonus: ' + PENALTY: ' (penalty: ' + POWERBOOST: + HELP: + '1': You must specify "p" or "player" to target a player or "f" or "faction" to target a faction. + '2': ex. /f powerboost p SomePlayer 0.5 -or- /f powerboost f SomeFaction -5 + INVALIDNUM: You must specify a valid numeric value for the power bonus/penalty amount. + PLAYER: Player "%s" + FACTION: Faction "%s" + BOOST: %s now has a power bonus/penalty of %d to min and max power levels. + BOOSTLOG: '%s has set the power bonus/penalty for %s to %d.' + RELOAD: + TIME: conf.json をリロードしました・%dミリ秒〜. + SAFEUNCLAIMALL: + SHORT: Unclaim all safezone land + UNCLAIMED: You unclaimed ALL safe zone land. + UNCLAIMEDLOG: '%s unclaimed all safe zones.' + SAVEALL: Factions saved to disk! + SETFWARP: + NOTCLAIMED: You can only set warps in your faction territory. + LIMIT: Your Faction already has the max amount of warps set (%d). + SET: Set warp %s to your location. + TOSET: to set warp + FORSET: for setting warp + SETHOME: + DISABLED: 党派ホームは禁止されました・ + NOTCLAIMED: Sorry, your faction home can only be set inside your own claimed territory. + TOSET: to set the faction home + FORSET: for setting the faction home + SET: '%s set the home for your faction. You can now use:' + SETOTHER: You have set the home for the %s faction. + SHOW: + TOSHOW: to show faction information + FORSHOW: for showing faction information + DESCRIPTION: 'Description: %s' + PEACEFUL: This faction is Peaceful + PERMANENT: This faction is permanent, remaining even with no members. + JOINING: 'Joining: %s ' + INVITATION: invitation is required + UNINVITED: no invitation is needed + POWER: 'Land / Power / Maxpower: %d/%d/%d %s' + BONUS: ' (bonus: ' + PENALTY: ' (penalty: ' + DEPRECIATED: (%s depreciated) + LANDVALUE: 'トータル地価: %s%s' + BANKCONTAINS: '残高: %s' + ALLIES: 'Allies: ' + ENEMIES: 'Enemies: ' + MEMBERSONLINE: 'Members online: ' + MEMBERSOFFLINE: 'Members offline: ' + SHOWINVITES: + PENDING: 'Players with pending invites: ' + CLICKTOREVOKE: Click to revoke invite for %s + STATUS: + FORMAT: '%s パワー:%s 最終オンライン:%s' + ONLINE: オンライン + AGOSUFFIX: '間・' + TAG: + TAKEN: That tag is already taken + TOCHANGE: to change the faction tag + FORCHANGE: for changing the faction tag + FACTION: '%s changed your faction tag to %s' + CHANGED: 党派「%s」は名が%sに変わりました・ + TITLE: + TOCHANGE: to change a players title + FORCHANGE: for changing a players title + CHANGED: '%sはタイトルが変わりました: %s' + UNCLAIM: + SAFEZONE: + SUCCESS: この安全地帯は原に変わりました・ + NOPERM: This is a safe zone. You lack permissions to unclaim. + WARZONE: + SUCCESS: この戦場は原に変わりました・ + NOPERM: This is a war zone. You lack permissions to unclaim. + UNCLAIMED: '%s unclaimed some of your land.' + UNCLAIMS: You unclaimed this land. + LOG: '%s unclaimed land at (%s) from the faction: %s' + WRONGFACTION: You don't own this land. + TOUNCLAIM: to unclaim this land + FORUNCLAIM: for unclaiming this land + FACTIONUNCLAIMED: '%s unclaimed some land.' + UNCLAIMALL: + TOUNCLAIM: to unclaim all faction land + FORUNCLAIM: for unclaiming all faction land + UNCLAIMED: '%s unclaimed ALL of your faction''s land.' + LOG: '%s unclaimed everything for the faction: %s' + VERSION: + VERSION: 現在バーション %s + WARUNCLAIMALL: + SHORT: unclaim all warzone land + SUCCESS: You unclaimed ALL war zone land. + LOG: '%s unclaimed all war zones.' + RELATIONS: + ALLTHENOPE: いいえ!出来ません・ + MORENOPE: いいえ・自分は自分には関係出来ません・ + ALREADYINRELATIONSHIP: %sの関係はもうありますよ・ + TOMARRY: 関係は変わり + FORMARRY: 関係は変わった + MUTUAL: Your faction is now %s to %s + PEACEFUL: This will have no effect while your faction is peaceful. + PEACEFULOTHER: This will have no effect while their faction is peaceful. + PROPOSAL: + '1': '%s wishes to be your %s' + '2': Type /%s %s %s to accept. + SENT: '%s were informed that you wish to be %s' +command: + convert: + backend: + running: そのバックエンドは使用中です・ + invalid: バックエンドは不正です・ + help: + invitations: 'You might want to close it and use invitations:' +GENERIC: + ASKYOURLEADER: ' Ask your leader to:' + YOUSHOULD: 'You should:' + YOUMAYWANT: 'You may want to: ' + SERVERADMIN: サーバアドミン + DISABLED: ディセーブル + ENABLED: エネーブル + CONSOLEONLY: プレーヤはそのコマンド使用出来ませんよ・ + TRASLATION: + VERSION: 翻訳:%s・%s「%s」%s + CONTRIBUTORS: 翻訳者:%s + RESPONSIBLE: 翻訳の主任:%s +RELATION: + MEMBER: 員 + ALLY: 連盟 + NEUTRAL: 中立 + ENEMY: 敵 +NOPAGES: 申し訳ありません・ページはありません・ +INVALIDPAGE: 指定ページは不正です・1から%dまで・ + +title: '&b党派 &0|&r' +wilderness: '&2原' +wilderness-description: ' ' +warzone: '&4戦場' +warzone-description: 安全じゃない地帯 +safezone: '&6安全地帯' +safezone-description: プレーヤコンバットとモンスターはありません・ +toggle-sb: 今、スコアーボードは{value}になっています・ +default-prefix: '{relationcolor}[{faction}] &r' diff --git a/Factions/src/main/resources/materials.json b/Factions/src/main/resources/materials.json new file mode 100644 index 0000000..86413bb --- /dev/null +++ b/Factions/src/main/resources/materials.json @@ -0,0 +1,519 @@ +{ + "GREEN_CONCRETE_POWDER": "CONCRETE_POWDER", + "SILVERFISH_SPAWN_EGG": "MONSTER_EGG", + "ZOMBIE_HORSE_SPAWN_EGG": "MONSTER_EGG", + "ENCHANTED_GOLDEN_APPLE": "GOLDEN_APPLE", + "SHULKER_SPAWN_EGG": "MONSTER_EGG", + "GOLDEN_PICKAXE": "GOLD_PICKAXE", + "PURPLE_CARPET": "CARPET", + "ORANGE_CARPET": "CARPET", + "PINK_CARPET": "CARPET", + "WOLF_SPAWN_EGG": "MONSTER_EGG", + "POTTED_ACACIA_SAPLING": "FLOWER_POT", + "JUNGLE_PRESSURE_PLATE": "WOOD_PLATE", + "LIME_CONCRETE_POWDER": "CONCRETE_POWDER", + "PINK_BANNER": "BANNER", + "GREEN_WOOL": "WOOL", + "POPPED_CHORUS_FRUIT": "CHORUS_FRUIT_POPPED", + "STONE_BRICK_STAIRS": "SMOOTH_STAIRS", + "OAK_WOOD": "LOG", + "GRAY_STAINED_GLASS": "STAINED_GLASS", + "WHITE_TULIP": "RED_ROSE", + "BLUE_ORCHID": "RED_ROSE", + "LIGHT_BLUE_TERRACOTTA": "STAINED_CLAY", + "ZOMBIE_HEAD": "SKULL", + "BROWN_WOOL": "WOOL", + "FIRE_CHARGE": "FIREBALL", + "GUNPOWDER": "SULPHUR", + "LIME_BANNER": "BANNER", + "PINK_CONCRETE": "CONCRETE", + "MUSHROOM_STEW": "MUSHROOM_SOUP", + "CRACKED_STONE_BRICKS": "SMOOTH_BRICK", + "BRICK_SLAB": "STEP", + "JUNGLE_SLAB": "WOOD_STEP", + "PURPLE_BED": "BED", + "BEEF": "RAW_BEEF", + "JUNGLE_BUTTON": "WOOD_BUTTON", + "CLOCK": "WATCH", + "MUSIC_DISC_STRAD": "RECORD_10", + "MUSHROOM_STEM": "HUGE_MUSHROOM_1", + "DIAMOND_HORSE_ARMOR": "DIAMOND_BARDING", + "JUNGLE_PLANKS": "WOOD", + "BLUE_TERRACOTTA": "STAINED_CLAY", + "BROWN_MUSHROOM_BLOCK": "BROWN_MUSHROOM", + "CHEST_MINECART": "STORAGE_MINECART", + "TURTLE_EGG": "MONSTER_EGG", + "WOODEN_SHOVEL": "WOOD_SPADE", + "POTTED_CACTUS": "FLOWER_POT", + "CYAN_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "CHISELED_SANDSTONE": "SANDSTONE", + "TOTEM_OF_UNDYING": "TOTEM", + "POTTED_BIRCH_SAPLING": "FLOWER_POT", + "RED_WOOL": "WOOL", + "COMMAND_BLOCK": "COMMAND", + "BROWN_WALL_BANNER": "WALL_BANNER", + "GOLDEN_HOE": "GOLD_HOE", + "GREEN_BED": "BED", + "POTTED_OAK_SAPLING": "FLOWER_POT", + "WITHER_SKELETON_SPAWN_EGG": "MONSTER_EGG", + "IRON_SHOVEL": "IRON_SPADE", + "LIME_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "ORANGE_BANNER": "BANNER", + "POLISHED_ANDESITE": "STONE", + "CRAFTING_TABLE": "WORKBENCH", + "MUSIC_DISC_BLOCKS": "RECORD_3", + "CAVE_AIR": "AIR", + "GOLDEN_BOOTS": "GOLD_BOOTS", + "RED_WALL_BANNER": "WALL_BANNER", + "PINK_STAINED_GLASS": "STAINED_GLASS", + "INFESTED_COBBLESTONE": "MONSTER_EGGS", + "SPRUCE_STAIRS": "SPRUCE_WOOD_STAIRS", + "DIORITE": "STONE", + "BLUE_ICE": "PACKED_ICE", + "CAVE_SPIDER_SPAWN_EGG": "MONSTER_EGG", + "LIGHT_BLUE_CONCRETE": "CONCRETE", + "CYAN_DYE": "INK_SACK", + "HORSE_SPAWN_EGG": "MONSTER_EGG", + "SKELETON_HORSE_SPAWN_EGG": "MONSTER_EGG", + "DARK_OAK_WOOD": "LOG_2", + "POTTED_JUNGLE_SAPLING": "FLOWER_POT", + "DARK_OAK_BUTTON": "WOOD_BUTTON", + "POTTED_RED_MUSHROOM": "FLOWER_POT", + "POTTED_ORANGE_TULIP": "FLOWER_POT", + "BIRCH_BOAT": "BOAT_BIRCH", + "ATTACHED_MELON_STEM": "MELON_STEM", + "BLACK_CONCRETE_POWDER": "CONCRETE_POWDER", + "DARK_OAK_PRESSURE_PLATE": "WOOD_PLATE", + "SPRUCE_PRESSURE_PLATE": "WOOD_PLATE", + "ACACIA_LEAVES": "LEAVES_2", + "COBBLESTONE_SLAB": "STEP", + "HEAVY_WEIGHTED_PRESSURE_PLATE": "IRON_PLATE", + "PINK_CONCRETE_POWDER": "CONCRETE_POWDER", + "MELON_SLICE": "MELON", + "LIGHT_BLUE_CONCRETE_POWDER": "CONCRETE_POWDER", + "OAK_BUTTON": "WOOD_BUTTON", + "LIGHT_BLUE_DYE": "INK_SACK", + "GRANITE": "STONE", + "LAPIS_LAZULI": "INK_SACK", + "WHITE_BED": "BED", + "BROWN_TERRACOTTA": "STAINED_CLAY", + "FILLED_MAP": "MAP", + "ORANGE_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "WOODEN_AXE": "WOOD_AXE", + "WHITE_WALL_BANNER": "WALL_BANNER", + "JUNGLE_LOG": "LOG", + "INK_SAC": "INK_SACK", + "NETHER_WART": "NETHER_STALK", + "YELLOW_CARPET": "CARPET", + "SLIME_SPAWN_EGG": "MONSTER_EGG", + "ORANGE_DYE": "INK_SACK", + "BLACK_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "ALLIUM": "RED_ROSE", + "SPRUCE_SLAB": "WOOD_STEP", + "PEONY": "DOUBLE_PLANT", + "CREEPER_WALL_HEAD": "SKULL", + "OXEYE_DAISY": "RED_ROSE", + "PURPLE_STAINED_GLASS": "STAINED_GLASS", + "BROWN_CONCRETE_POWDER": "CONCRETE_POWDER", + "TERRACOTTA": "HARD_CLAY", + "POTTED_FERN": "FLOWER_POT", + "END_STONE_BRICKS": "END_BRICKS", + "YELLOW_WALL_BANNER": "WALL_BANNER", + "DROWNED_SPAWN_EGG": "MONSTER_EGG", + "COBWEB": "WEB", + "COARSE_DIRT": "DIRT", + "LIGHT_GRAY_GLAZED_TERRACOTTA": "SILVER_GLAZED_TERRACOTTA", + "OAK_LOG": "LOG", + "PUFFERFISH": "RAW_FISH", + "YELLOW_BED": "BED", + "CARROTS": "CARROT", + "PORKCHOP": "PORK", + "GLASS_PANE": "THIN_GLASS", + "ZOMBIE_PIGMAN_SPAWN_EGG": "MONSTER_EGG", + "CHICKEN_SPAWN_EGG": "MONSTER_EGG", + "CHIPPED_ANVIL": "ANVIL", + "CHISELED_QUARTZ_BLOCK": "QUARTZ_BLOCK", + "LIME_CARPET": "CARPET", + "POTTED_DARK_OAK_SAPLING": "FLOWER_POT", + "COOKED_COD": "COOKED_FISH", + "CYAN_BANNER": "BANNER", + "OAK_LEAVES": "LEAVES", + "MAGENTA_BED": "BED", + "IRON_BARS": "IRON_FENCE", + "WHITE_CONCRETE": "CONCRETE", + "RED_BED": "BED", + "POTTED_BROWN_MUSHROOM": "FLOWER_POT", + "YELLOW_WOOL": "WOOL", + "ROSE_BUSH": "DOUBLE_PLANT", + "BROWN_CARPET": "CARPET", + "WOODEN_SWORD": "WOOD_SWORD", + "REDSTONE_WALL_TORCH": "REDSTONE_TORCH_ON", + "NETHER_BRICK": "NETHER_BRICK_ITEM", + "GOLDEN_AXE": "GOLD_AXE", + "ACACIA_LOG": "LOG_2", + "CREEPER_SPAWN_EGG": "MONSTER_EGG", + "INFESTED_MOSSY_STONE_BRICKS": "MONSTER_EGGS", + "BRICKS": "BRICK", + "PISTON_HEAD": "PISTON_EXTENSION", + "MAGENTA_CONCRETE_POWDER": "CONCRETE_POWDER", + "SPIDER_SPAWN_EGG": "MONSTER_EGG", + "WET_SPONGE": "SPONGE", + "RED_CARPET": "CARPET", + "ENCHANTING_TABLE": "ENCHANTMENT_TABLE", + "PHANTOM_SPAWN_EGG": "MONSTER_EGG", + "POTATO": "POTATO_ITEM", + "YELLOW_STAINED_GLASS": "STAINED_GLASS", + "BROWN_BANNER": "BANNER", + "BAT_SPAWN_EGG": "MONSTER_EGG", + "RED_BANNER": "BANNER", + "BLUE_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "SPRUCE_LOG": "LOG", + "DOLPHIN_SPAWN_EGG": "MONSTER_EGG", + "POTTED_RED_TULIP": "FLOWER_POT", + "BONE_MEAL": "INK_SACK", + "LIME_DYE": "INK_SACK", + "OAK_DOOR": "WOODEN_DOOR", + "LILY_PAD": "WATER_LILY", + "POTTED_AZURE_BLUET": "FLOWER_POT", + "WHITE_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "LIME_STAINED_GLASS": "STAINED_GLASS", + "RED_MUSHROOM_BLOCK": "RED_MUSHROOM", + "MAGMA_BLOCK": "MAGMA", + "GOLDEN_SHOVEL": "GOLD_SPADE", + "MAGENTA_WALL_BANNER": "WALL_BANNER", + "TALL_GRASS": "DOUBLE_PLANT", + "RABBIT_SPAWN_EGG": "MONSTER_EGG", + "BLUE_CONCRETE_POWDER": "CONCRETE_POWDER", + "COD": "RAW_FISH", + "LIGHT_BLUE_CARPET": "CARPET", + "RED_STAINED_GLASS": "STAINED_GLASS", + "PINK_DYE": "INK_SACK", + "FARMLAND": "SOIL", + "SKELETON_SPAWN_EGG": "MONSTER_EGG", + "SKELETON_WALL_SKULL": "SKULL", + "LIGHT_GRAY_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "WHITE_STAINED_GLASS": "STAINED_GLASS", + "PRISMARINE_BRICKS": "PRISMARINE", + "DARK_OAK_LOG": "LOG_2", + "CACTUS_GREEN": "INK_SACK", + "MUSIC_DISC_CHIRP": "RECORD_5", + "ACACIA_TRAPDOOR": "TRAP_DOOR", + "VINDICATOR_SPAWN_EGG": "MONSTER_EGG", + "WHITE_CARPET": "CARPET", + "CHISELED_STONE_BRICKS": "SMOOTH_BRICK", + "QUARTZ_PILLAR": "QUARTZ_BLOCK", + "EVOKER_SPAWN_EGG": "MONSTER_EGG", + "PURPLE_WALL_BANNER": "WALL_BANNER", + "BIRCH_PRESSURE_PLATE": "WOOD_PLATE", + "BLACK_BED": "BED", + "VILLAGER_SPAWN_EGG": "MONSTER_EGG", + "BIRCH_SLAB": "WOOD_STEP", + "LARGE_FERN": "DOUBLE_PLANT", + "QUARTZ_SLAB": "STEP", + "SHEEP_SPAWN_EGG": "MONSTER_EGG", + "PURPLE_TERRACOTTA": "STAINED_CLAY", + "TNT_MINECART": "EXPLOSIVE_MINECART", + "WITCH_SPAWN_EGG": "MONSTER_EGG", + "GRAY_BED": "BED", + "MULE_SPAWN_EGG": "MONSTER_EGG", + "POLISHED_DIORITE": "STONE", + "GLISTERING_MELON_SLICE": "SPECKLED_MELON", + "WHITE_TERRACOTTA": "STAINED_CLAY", + "COD_BUCKET": "BUCKET", + "JUNGLE_STAIRS": "JUNGLE_WOOD_STAIRS", + "MOSSY_COBBLESTONE_WALL": "COBBLE_WALL", + "CYAN_CARPET": "CARPET", + "DARK_OAK_PLANKS": "WOOD", + "GUARDIAN_SPAWN_EGG": "MONSTER_EGG", + "SPRUCE_TRAPDOOR": "TRAP_DOOR", + "ACACIA_WOOD": "LOG_2", + "JUNGLE_BOAT": "BOAT_JUNGLE", + "SPRUCE_BOAT": "BOAT_SPRUCE", + "LIGHT_GRAY_STAINED_GLASS": "STAINED_GLASS", + "RED_SANDSTONE_SLAB": "STONE_SLAB2", + "AZURE_BLUET": "RED_ROSE", + "DEBUG_STICK": "STICK", + "POTTED_OXEYE_DAISY": "FLOWER_POT", + "HUSK_SPAWN_EGG": "MONSTER_EGG", + "PURPLE_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "TROPICAL_FISH": "RAW_FISH", + "CHARCOAL": "COAL", + "ZOMBIE_SPAWN_EGG": "MONSTER_EGG", + "OAK_PLANKS": "WOOD", + "PISTON": "PISTON_BASE", + "END_PORTAL_FRAME": "ENDER_PORTAL_FRAME", + "YELLOW_BANNER": "BANNER", + "BIRCH_SAPLING": "SAPLING", + "LIME_CONCRETE": "CONCRETE", + "STONE_SHOVEL": "STONE_SPADE", + "BEETROOTS": "BEETROOT", + "SNOWBALL": "SNOW_BALL", + "PURPLE_BANNER": "BANNER", + "PURPLE_CONCRETE_POWDER": "CONCRETE_POWDER", + "BIRCH_LOG": "LOG", + "LIGHT_GRAY_DYE": "INK_SACK", + "STRAY_SPAWN_EGG": "MONSTER_EGG", + "RED_TERRACOTTA": "STAINED_CLAY", + "MOOSHROOM_SPAWN_EGG": "MONSTER_EGG", + "ACACIA_PLANKS": "WOOD", + "MYCELIUM": "MYCEL", + "BROWN_CONCRETE": "CONCRETE", + "STONE_SLAB": "STEP", + "SALMON_BUCKET": "BUCKET", + "LIME_WALL_BANNER": "WALL_BANNER", + "BIRCH_LEAVES": "LEAVES", + "FIREWORK_ROCKET": "FIREWORK", + "NETHER_BRICK_FENCE": "NETHER_FENCE", + "STONE_BRICKS": "SMOOTH_BRICK", + "GOLDEN_LEGGINGS": "GOLD_LEGGINGS", + "BROWN_BED": "BED", + "POTTED_DANDELION": "FLOWER_POT", + "CARROT_ON_A_STICK": "CARROT_STICK", + "OCELOT_SPAWN_EGG": "RECORD_12", + "ATTACHED_PUMPKIN_STEM": "PUMPKIN_STEM", + "ACACIA_PRESSURE_PLATE": "WOOD_PLATE", + "RED_SAND": "SAND", + "MAGENTA_TERRACOTTA": "STAINED_CLAY", + "MAGENTA_BANNER": "BANNER", + "DRAGON_HEAD": "SKULL", + "SPRUCE_PLANKS": "WOOD", + "BLACK_WOOL": "WOOL", + "LIGHT_GRAY_CARPET": "CARPET", + "PURPLE_CONCRETE": "CONCRETE", + "CYAN_BED": "BED", + "MAGENTA_CARPET": "CARPET", + "REDSTONE_TORCH": "REDSTONE_TORCH_ON", + "STICKY_PISTON": "PISTON_STICKY_BASE", + "FIREWORK_STAR": "FIREWORK_CHARGE", + "PURPLE_DYE": "INK_SACK", + "COW_SPAWN_EGG": "MONSTER_EGG", + "COBBLESTONE_WALL": "COBBLE_WALL", + "ELDER_GUARDIAN_SPAWN_EGG": "MONSTER_EGG", + "BLUE_WALL_BANNER": "WALL_BANNER", + "GREEN_BANNER": "BANNER", + "LIGHT_GRAY_BANNER": "BANNER", + "BLUE_STAINED_GLASS": "STAINED_GLASS", + "ZOMBIE_VILLAGER_SPAWN_EGG": "MONSTER_EGG", + "ACACIA_SLAB": "WOOD_STEP", + "ORANGE_TERRACOTTA": "STAINED_CLAY", + "BLACK_CONCRETE": "CONCRETE", + "LIGHT_BLUE_STAINED_GLASS": "STAINED_GLASS", + "SPRUCE_SAPLING": "SAPLING", + "POTTED_POPPY": "FLOWER_POT", + "DONKEY_SPAWN_EGG": "MONSTER_EGG", + "BLACK_STAINED_GLASS": "STAINED_GLASS", + "OAK_STAIRS": "WOOD_STAIRS", + "INFESTED_CHISELED_STONE_BRICKS": "MONSTER_EGGS", + "COMPARATOR": "REDSTONE_COMPARATOR", + "BLUE_BANNER": "BANNER", + "PIG_SPAWN_EGG": "MONSTER_EGG", + "DRAGON_WALL_HEAD": "SKULL", + "OAK_SLAB": "WOOD_STEP", + "WITHER_SKELETON_SKULL": "SKULL", + "LIGHT_GRAY_TERRACOTTA": "STAINED_CLAY", + "LIGHT_BLUE_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "DARK_OAK_SAPLING": "SAPLING", + "ACACIA_BUTTON": "WOOD_BUTTON", + "GRASS_BLOCK": "GRASS", + "MUSIC_DISC_MALL": "RECORD_7", + "MAGENTA_STAINED_GLASS": "STAINED_GLASS", + "FURNACE_MINECART": "POWERED_MINECART", + "MUSIC_DISC_STAL": "RECORD_9", + "OAK_FENCE_GATE": "FENCE_GATE", + "POTTED_WHITE_TULIP": "FLOWER_POT", + "SUNFLOWER": "DOUBLE_PLANT", + "SANDSTONE_SLAB": "STEP", + "SPRUCE_BUTTON": "WOOD_BUTTON", + "LIGHT_GRAY_CONCRETE_POWDER": "CONCRETE_POWDER", + "CYAN_WOOL": "WOOL", + "GHAST_SPAWN_EGG": "MONSTER_EGG", + "GREEN_CARPET": "CARPET", + "PUFFERFISH_SPAWN_EGG": "MONSTER_EGG", + "SQUID_SPAWN_EGG": "MONSTER_EGG", + "LILAC": "DOUBLE_PLANT", + "ZOMBIE_WALL_HEAD": "SKULL", + "CREEPER_HEAD": "SKULL", + "SALMON_SPAWN_EGG": "MONSTER_EGG", + "DARK_PRISMARINE": "PRISMARINE", + "NETHER_QUARTZ_ORE": "QUARTZ_ORE", + "MUSIC_DISC_WAIT": "RECORD_11", + "BLACK_BANNER": "BANNER", + "LIGHT_BLUE_BED": "BED", + "PINK_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "END_PORTAL": "ENDER_PORTAL", + "PLAYER_WALL_HEAD": "SKULL", + "WITHER_SKELETON_WALL_SKULL": "SKULL", + "DRAGON_BREATH": "DRAGONS_BREATH", + "LIGHT_GRAY_CONCRETE": "CONCRETE", + "DARK_OAK_TRAPDOOR": "TRAP_DOOR", + "YELLOW_TERRACOTTA": "STAINED_CLAY", + "DAMAGED_ANVIL": "ANVIL", + "PINK_WALL_BANNER": "WALL_BANNER", + "LLAMA_SPAWN_EGG": "MONSTER_EGG", + "CHISELED_RED_SANDSTONE": "RED_SANDSTONE", + "GOLDEN_SWORD": "GOLD_SWORD", + "JUNGLE_LEAVES": "LEAVES", + "JUNGLE_WOOD": "LOG", + "RED_TULIP": "RED_ROSE", + "WHITE_BANNER": "BANNER", + "MOSSY_STONE_BRICKS": "SMOOTH_BRICK", + "DANDELION": "YELLOW_FLOWER", + "GOLDEN_HELMET": "GOLD_HELMET", + "SMOOTH_SANDSTONE": "SANDSTONE", + "OAK_TRAPDOOR": "TRAP_DOOR", + "YELLOW_CONCRETE_POWDER": "CONCRETE_POWDER", + "OAK_SAPLING": "SAPLING", + "MAGENTA_DYE": "INK_SACK", + "PARROT_SPAWN_EGG": "MONSTER_EGG", + "STONE_BRICK_SLAB": "STEP", + "PURPLE_WOOL": "WOOL", + "GRAY_CONCRETE": "CONCRETE", + "LIGHT_BLUE_BANNER": "BANNER", + "END_STONE": "ENDER_STONE", + "DARK_OAK_LEAVES": "LEAVES_2", + "MELON": "MELON_BLOCK", + "GREEN_CONCRETE": "CONCRETE", + "IRON_HORSE_ARMOR": "IRON_BARDING", + "ORANGE_WALL_BANNER": "WALL_BANNER", + "VOID_AIR": "AIR", + "CYAN_STAINED_GLASS": "STAINED_GLASS", + "COD_SPAWN_EGG": "MONSTER_EGG", + "CHICKEN": "RAW_CHICKEN", + "GREEN_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "ORANGE_BED": "BED", + "ORANGE_CONCRETE": "CONCRETE", + "RED_NETHER_BRICKS": "RED_NETHER_BRICK", + "MUSIC_DISC_FAR": "RECORD_6", + "CYAN_CONCRETE_POWDER": "CONCRETE_POWDER", + "BIRCH_PLANKS": "WOOD", + "WOODEN_PICKAXE": "WOOD_PICKAXE", + "NETHER_BRICK_SLAB": "STEP", + "REPEATING_COMMAND_BLOCK": "COMMAND_REPEATING", + "TURTLE_SPAWN_EGG": "MONSTER_EGG", + "CYAN_CONCRETE": "CONCRETE", + "RED_CONCRETE_POWDER": "CONCRETE_POWDER", + "RED_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "DARK_OAK_BOAT": "BOAT_DARK_OAK", + "TROPICAL_FISH_SPAWN_EGG": "MONSTER_EGG", + "COOKED_SALMON": "COOKED_FISH", + "BLUE_CARPET": "CARPET", + "GOLDEN_HORSE_ARMOR": "GOLD_BARDING", + "SMOOTH_RED_SANDSTONE": "RED_SANDSTONE", + "MUSIC_DISC_MELLOHI": "RECORD_8", + "BROWN_STAINED_GLASS": "STAINED_GLASS", + "SKELETON_SKULL": "SKULL", + "GREEN_WALL_BANNER": "WALL_BANNER", + "REPEATER": "DIODE", + "FERN": "LONG_GRASS", + "INFESTED_CRACKED_STONE_BRICKS": "MONSTER_EGGS", + "PINK_TULIP": "RED_ROSE", + "POLISHED_GRANITE": "STONE", + "JUNGLE_SAPLING": "SAPLING", + "SPRUCE_WOOD": "LOG", + "STONE_PRESSURE_PLATE": "STONE_PLATE", + "LIME_BED": "BED", + "POTTED_DEAD_BUSH": "FLOWER_POT", + "BLACK_TERRACOTTA": "STAINED_CLAY", + "POTTED_PINK_TULIP": "FLOWER_POT", + "EXPERIENCE_BOTTLE": "EXP_BOTTLE", + "COMMAND_BLOCK_MINECART": "COMMAND_MINECART", + "ORANGE_CONCRETE_POWDER": "CONCRETE_POWDER", + "LIME_WOOL": "WOOL", + "SALMON": "RAW_FISH", + "ORANGE_WOOL": "WOOL", + "PLAYER_HEAD": "SKULL", + "OAK_PRESSURE_PLATE": "WOOD_PLATE", + "LIME_TERRACOTTA": "STAINED_CLAY", + "GRAY_CARPET": "CARPET", + "WHITE_WOOL": "WOOL", + "GREEN_TERRACOTTA": "STAINED_CLAY", + "BIRCH_STAIRS": "BIRCH_WOOD_STAIRS", + "OAK_BOAT": "BOAT", + "ROSE_RED": "INK_SACK", + "BIRCH_TRAPDOOR": "TRAP_DOOR", + "ACACIA_BOAT": "BOAT_ACACIA", + "GRAY_CONCRETE_POWDER": "CONCRETE_POWDER", + "ORANGE_STAINED_GLASS": "STAINED_GLASS", + "LIGHT_GRAY_WALL_BANNER": "WALL_BANNER", + "BLAZE_SPAWN_EGG": "MONSTER_EGG", + "ENDER_EYE": "EYE_OF_ENDER", + "BLUE_CONCRETE": "CONCRETE", + "GRAY_DYE": "INK_SACK", + "REDSTONE_LAMP": "REDSTONE_LAMP_ON", + "GREEN_STAINED_GLASS": "STAINED_GLASS", + "GRAY_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "POTATOES": "POTATO", + "POTTED_BLUE_ORCHID": "FLOWER_POT", + "BLUE_WOOL": "WOOL", + "MAGENTA_WOOL": "WOOL", + "BIRCH_BUTTON": "WOOD_BUTTON", + "COCOA_BEANS": "INK_SACK", + "PINK_BED": "BED", + "POPPY": "RED_ROSE", + "CYAN_TERRACOTTA": "STAINED_CLAY", + "LIGHT_WEIGHTED_PRESSURE_PLATE": "GOLD_PLATE", + "YELLOW_CONCRETE": "CONCRETE", + "LIGHT_BLUE_WOOL": "WOOL", + "LEAD": "LEASH", + "VEX_SPAWN_EGG": "MONSTER_EGG", + "POTTED_SPRUCE_SAPLING": "FLOWER_POT", + "DANDELION_YELLOW": "INK_SACK", + "GOLDEN_CHESTPLATE": "GOLD_CHESTPLATE", + "INFESTED_STONE_BRICKS": "MONSTER_EGGS", + "LIGHT_GRAY_SHULKER_BOX": "SILVER_SHULKER_BOX", + "CARROT": "CARROT_ITEM", + "MAGMA_CUBE_SPAWN_EGG": "MONSTER_EGG", + "MUSIC_DISC_13": "GREEN_RECORD", + "MUSIC_DISC_WARD": "RECORD_12", + "MUSIC_DISC_11": "GOLD_RECORD", + "PODZOL": "DIRT", + "POTTED_ALLIUM": "FLOWER_POT", + "BLUE_BED": "BED", + "BLACK_WALL_BANNER": "WALL_BANNER", + "WOODEN_HOE": "WOOD_HOE", + "YELLOW_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "BLACK_CARPET": "CARPET", + "PINK_TERRACOTTA": "STAINED_CLAY", + "MUSIC_DISC_CAT": "RECORD_4", + "DIAMOND_SHOVEL": "DIAMOND_SPADE", + "COOKED_PORKCHOP": "GRILLED_PORK", + "SPAWNER": "MOB_SPAWNER", + "GRAY_WALL_BANNER": "WALL_BANNER", + "WHITE_CONCRETE_POWDER": "CONCRETE_POWDER", + "GRAY_TERRACOTTA": "STAINED_CLAY", + "RAIL": "RAILS", + "WRITABLE_BOOK": "BOOK_AND_QUILL", + "MAGENTA_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "NETHER_PORTAL": "PORTAL", + "SHULKER_BOX": "PURPLE_SHULKER_BOX", + "ENDERMITE_SPAWN_EGG": "MONSTER_EGG", + "POLAR_BEAR_SPAWN_EGG": "MONSTER_EGG", + "CHAIN_COMMAND_BLOCK": "COMMAND_CHAIN", + "CARVED_PUMPKIN": "PUMPKIN", + "GRAY_WOOL": "WOOL", + "PINK_WOOL": "WOOL", + "LIGHT_GRAY_WOOL": "WOOL", + "CYAN_WALL_BANNER": "WALL_BANNER", + "DARK_OAK_SLAB": "WOOD_STEP", + "RED_CONCRETE": "CONCRETE", + "WHEAT_SEEDS": "SEEDS", + "LIGHT_GRAY_BED": "BED", + "ACACIA_SAPLING": "SAPLING", + "TROPICAL_FISH_BUCKET": "BUCKET", + "NETHER_BRICKS": "NETHER_BRICK", + "OAK_FENCE": "FENCE", + "BROWN_STAINED_GLASS_PANE": "STAINED_GLASS_PANE", + "MOVING_PISTON": "PISTON_MOVING_PIECE", + "BRICK": "CLAY_BRICK", + "BIRCH_WOOD": "LOG", + "GRAY_BANNER": "BANNER", + "ENDERMAN_SPAWN_EGG": "MONSTER_EGG", + "MAGENTA_CONCRETE": "CONCRETE", + "SPRUCE_LEAVES": "LEAVES", + "LIGHT_BLUE_WALL_BANNER": "BANNER", + "JUNGLE_TRAPDOOR": "TRAP_DOOR", + "ORANGE_TULIP": "RED_ROSE", + "ANDESITE": "STONE", + "INFESTED_STONE": "MONSTER_EGGS", + "WALL_TORCH": "TORCH" +} \ No newline at end of file diff --git a/Factions/src/main/resources/plugin.yml b/Factions/src/main/resources/plugin.yml new file mode 100644 index 0000000..b282878 --- /dev/null +++ b/Factions/src/main/resources/plugin.yml @@ -0,0 +1,358 @@ +name: Factions +version: ${project.version} +main: com.massivecraft.factions.FactionsPlugin +authors: [Olof Larsson, Brett Flannigan, drtshock, CmdrKittens, Golfing8] +softdepend: [LuckPerms, CoreProtect] +api-version: 1.13 +website: https://www.spigotmc.org/resources/factionsuuid.1035/ +commands: + factions: + description: Reference command for Factions. + aliases: [f] +permissions: + factions.kit.admin: + description: All faction permissions. + children: + factions.kit.mod: true + factions.seepaypal: true + factions.essentials.bypassremoval: true + factions.sotw: true + factions.config: true + factions.claim.bypasslimit: true + factions.lock: true + factions.reload: true + factions.save: true + factions.modifypower: true + factions.ahome: true + factions.setmaxvaults: true + factions.updates: true + factions.debug: true + factions.*: + description: This is just an alias for factions.kit.admin + children: + factions.kit.admin: true + factions.kit.mod: + description: All faction permissions but configuration and persistance. + children: + factions.fly.any: true + factions.strike.manage: true + factions.claim.seeall: true + factions.kit.halfmod: true + factions.disband.any: true + factions.setpeaceful: true + factions.setpermanent: true + factions.setpermanentpower: true + factions.powerboost: true + factions.sethome.any: true + factions.money.*: true + factions.join.any: true + factions.join.others: true + factions.admin.any: true + factions.mod.any: true + factions.kit.halfmod: + description: Zones, bypassing, kicking, and chatspy + children: + factions.kit.fullplayer: true + factions.managesafezone: true + factions.managewarzone: true + factions.bypass: true + factions.kick.any: true + factions.ownershipbypass: true + factions.chatspy: true + factions.show.bypassexempt: true + factions.kit.fullplayer: + default: true + description: Can also create new factions and use title colors. + children: + factions.kit.halfplayer: true + factions.create: true + factions.setpaypal: true + factions.title.color: true + factions.kit.halfplayer: + description: Can do all but create factions. + children: + factions.missions: true + factions.admin: true + factions.strike.view: true + factions.roster: true + factions.alts: true + factions.autoclaim: true + factions.chat: true + factions.claim: true + factions.claim.line: true + factions.claim.radius: true + factions.coords: true + factions.deinvite: true + factions.description: true + factions.disband: true + factions.dtr: true + factions.help: true + factions.home: true + factions.invite: true + factions.join: true + factions.kick: true + factions.leave: true + factions.list: true + factions.map: true + factions.mod: true + factions.money.kit.standard: true + factions.noboom: true + factions.open: true + factions.owner: true + factions.ownerlist: true + factions.power: true + factions.power.any: true + factions.relation: true + factions.sethome: true + factions.delhome: true + factions.show: true + factions.stuck: true + factions.tag: true + factions.title: true + factions.setwarp: true + factions.version: true + factions.unclaim: true + factions.claimcorner: true + factions.tnt.*: true + factions.unclaimall: true + factions.scoreboard: true + factions.showinvites: true + factions.seechunk: true + factions.monitorlogins: true + factions.warp: true + factions.top: true + factions.togglealliancechat: true + factions.vault: true + factions.mapheight: true + factions.promote: true + factions.ban: true + factions.fly: true + factions.coleader: true + factions.near: true + factions.permissions: true + factions.stealth: true + factions.admin: + description: hand over your admin rights + factions.admin.any: + description: give or revoke admin status for any player in any faction + factions.announce: + description: announce things to the peasants + factions.autoclaim: + description: auto-claim land as you walk around + factions.bypass: + description: enable admin bypass mode + factions.chat: + description: change chat mode + factions.chatspy: + description: enable admin chat spy mode + factions.claim: + description: claim land where you are standing + factions.claim.radius: + description: claim land in a large radius + factions.config: + description: change a conf.json setting + factions.create: + description: create a new faction + factions.deinvite: + description: remove a pending invitation + factions.description: + description: change the faction description + factions.disband: + description: disband a faction + factions.disband.any: + description: disband another faction + factions.help: + description: display a help page + factions.home: + description: teleport to the faction home + factions.invite: + description: invite a player to your faction + factions.join: + description: join a faction + factions.join.any: + description: join any faction, bypassing invitation process for closed factions + factions.join.others: + description: specify another player in the join command, to move them to the specified faction + factions.kick: + description: kick a player from the faction + factions.kick.any: + description: kick anyone from any faction + factions.leave: + description: leave your faction + factions.list: + description: see a list of the factions + factions.lock: + description: lock all write stuff + factions.managesafezone: + description: claim land as a safe zone and build/destroy within safe zones + factions.managewarzone: + description: claim land as a war zone and build/destroy within war zones + factions.map: + description: show the territory map, and set optional auto update + factions.stealth: + description: toggle stealth mode + factions.mod: + description: give or revoke moderator rights + factions.mod.any: + description: give or revoke moderator rights for any player in any faction + factions.money.balance: + description: show your factions current money balance + factions.money.balance.any: + description: show money balance for factions other than your own + factions.money.deposit: + description: deposit money into a faction bank + factions.money.withdraw: + description: withdraw money from your faction bank + factions.money.withdraw.any: + description: withdraw money from your factions other than your own + factions.money.f2f: + description: transfer money from faction to faction + factions.money.f2p: + description: transfer money from faction to player + factions.money.p2f: + description: transfer money from player to faction + factions.money.kit.standard: + children: + factions.money.balance: true + factions.money.balance.any: true + factions.money.deposit: true + factions.money.withdraw: true + factions.money.f2f: true + factions.money.f2p: true + factions.money.p2f: true + factions.money.*: + children: + factions.money.kit.standard: true + factions.money.balance.any: true + factions.money.deposit: true + factions.money.withdraw: true + factions.money.withdraw.any: true + factions.money.f2f: true + factions.money.f2p: true + factions.money.p2f: true + factions.noboom: + description: toggle explosions (peaceful factions only) + factions.open: + description: switch if invitation is required to join + factions.owner: + description: set ownership of claimed land + factions.ownerlist: + description: list owner(s) of this claimed land + factions.ownershipbypass: + description: bypass ownership restrictions within own faction's territory + factions.promote: + description: promote a fellow member + factions.setpeaceful: + description: designate a faction as peaceful + factions.setpermanent: + description: designate a faction as permanent + factions.setpermanentpower: + description: set permanent power for a faction + factions.stuck: + description: teleports player outside a faction + factions.power: + description: show player power info + factions.power.any: + description: view an other players power level + factions.powerboost: + description: apply permanent power bonus/penalty to specified player or faction + factions.relation: + description: set relation wish to another faction + factions.reload: + description: reload data file(s) from disk + factions.save: + description: save all data to disk + factions.claimcorner: + description: claim a corner + factions.sethome: + description: set the faction home + factions.delhome: + description: unset the faction home + factions.sethome.any: + description: set faction home for another faction + factions.show: + description: show faction information + factions.show.bypassexempt: + description: show exempt faction information + factions.tag: + description: change the faction tag + factions.title: + description: set or remove a players title + factions.title.color: + description: set yours or other player's titles to be colored. + factions.version: + description: see the version of the plugin + factions.unclaim: + description: unclaim the land where you are standing + factions.unclaimall: + description: unclaim all of your factions land + factions.scoreboard: + description: ability to toggle scoreboards + factions.showinvites: + description: show pending invites to your faction + factions.seechunk: + description: see the chunk you stand in + factions.setwarp: + description: set a warp for your faction + factions.warp: + description: access your faction warps + factions.dtr: + description: view your faction's DTR + factions.modifydtr: + description: modify other factions' DTR + factions.modifypower: + description: modify other player's power + factions.monitorlogins: + description: monitor join and leaves of faction members + factions.claim.line: + description: claim in a line + factions.top: + description: sort factions + factions.togglealliancechat: + description: toggle alliance chat on and off + factions.dontlosepoweroffline: + description: Don't lose power for being offline. + factions.ahome: + description: Ability to send players to their faction home. + factions.autoleavebypass: + description: Bypass autoleave. + factions.vault: + description: Access faction vault. + factions.setmaxvault: + description: Set a faction's max vaults. + factions.mapheight: + description: Set your /f map height. + factions.ban: + description: Ban players from Factions + factions.fly: + description: Allow use of /f fly + factions.fly.auto: + description: Allow use of /f fly auto + factions.coleader: + description: Allow use of /f coleader + factions.near: + description: Allow use of /f near to show nearby faction members + factions.updates: + description: Be informed of available updates to the plugin + factions.permissions: + description: Use /f perms + factions.debug: + description: Use /f debug + factions.tnt.info: + description: Get TNT information + factions.tnt.deposit: + description: Deposit to TNT bank + factions.tnt.withdraw: + description: Withdraw from TNT bank + factions.tnt.fill: + description: Use TNT fill command + factions.tnt.siphon: + description: Use TNT siphon command + factions.coords: + description: Send coordinates to your teammates + factions.listclaims: + description: List claims + factions.listclaims.other: + description: List claims of other factions + factions.alts: + description: Usage for the alt commands diff --git a/Factions/src/test/java/com/massivecraft/factions/config/file/ConfigTest.java b/Factions/src/test/java/com/massivecraft/factions/config/file/ConfigTest.java new file mode 100644 index 0000000..a9e3836 --- /dev/null +++ b/Factions/src/test/java/com/massivecraft/factions/config/file/ConfigTest.java @@ -0,0 +1,46 @@ +package com.massivecraft.factions.config.file; + +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +public class ConfigTest { + @Test + public void testMainConfig() { + testConfig(new MainConfig()); + } + + @Test + public void testPerms() { + testConfig(new DefaultPermissionsConfig()); + } + + private void testConfig(Object o) { + try { + assertNotNull(o, o.getClass()); + } catch (IllegalAccessException e) { + throw new AssertionError("Couldn't even check the class!"); + } + } + + private void assertNotNull(Object o, Class clazz) throws IllegalAccessException { + System.out.println(clazz); + for (Field field : clazz.getDeclaredFields()) { + if (field.isSynthetic() || Modifier.isTransient(field.getModifiers())) { + continue; + } + assertNotNull(o, field); + } + } + + private void assertNotNull(Object o, Field field) throws IllegalAccessException { + field.setAccessible(true); + Object oo = field.get(o); + Assert.assertNotNull(field.getName() + " was null", oo); + if (oo.getClass().getPackage().getName().startsWith("com.massivecraft.factions.config")) { + assertNotNull(oo, oo.getClass()); + } + } +} diff --git a/Gambling/pom.xml b/Gambling/pom.xml new file mode 100644 index 0000000..2168213 --- /dev/null +++ b/Gambling/pom.xml @@ -0,0 +1,48 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Gambling + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + Core + net.crankedpvp + + + net.astropvp + FactionsKore + 0.1 + system + ${project.basedir}/../.lib/FactionsKore-1.3.431.jar + + + com.massivecraft + Factions + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/GamblingCommand.java b/Gambling/src/main/java/net/crankedpvp/gambling/GamblingCommand.java new file mode 100644 index 0000000..73486d3 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/GamblingCommand.java @@ -0,0 +1,24 @@ +package net.crankedpvp.gambling; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("gambling") +public class GamblingCommand extends CommandBase { + + private GamblingPlugin plugin; + public GamblingCommand(GamblingPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + + GamblingInventory gamblingInventory = new GamblingInventory(player); + gamblingInventory.getUI().open(player); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/GamblingInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/GamblingInventory.java new file mode 100644 index 0000000..32bd45c --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/GamblingInventory.java @@ -0,0 +1,90 @@ +package net.crankedpvp.gambling; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.bombs.inventory.BombsInformationInventory; +import net.crankedpvp.gambling.crash.inventory.CrashInventory; +import net.crankedpvp.gambling.dice.inventory.DiceInventory; +import net.crankedpvp.gambling.mines.inventory.MinesInformationInventory; +import net.crankedpvp.gambling.tower.inventory.TowerInformationInventory; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class GamblingInventory { + + + private final Gui gamblingInventory; + + public Gui getUI() { + return this.gamblingInventory; + } + + + public GamblingInventory(Player player) { + this.gamblingInventory = new Gui(1, "Cranked Gambling"); + this.gamblingInventory.setDefaultClickAction(event -> event.setCancelled(true)); + ItemBuilder crashBuilder = new ItemBuilder(Material.NETHER_STAR, "&c&lCrash", + "&7Click to enter the crash menu"); + ItemBuilder diceBuilder = new ItemBuilder(Material.NETHER_STAR, "&d&lDice", + "&7Click to enter the dice menu"); + //ItemBuilder bombsBuilder = new ItemBuilder(Material.TNT, "&4&lBombs", + //"&7Click to enter the bombs menu"); + //ItemBuilder minesBuilder = new ItemBuilder(Material.STONE_PLATE, "&e&lMines", + //"&7Click to enter the mines menu"); + ItemBuilder towerBuilder = new ItemBuilder(Material.ARMOR_STAND, "&d&lTowers", + "&7Click to enter the towers menu"); + //ItemBuilder rouletteBuilder = new ItemBuilder(Material.STONE_BUTTON, "&a&lRoulette", + //"&7Click to enter the roulette menu"); + + ItemBuilder coinflipBuilder = new ItemBuilder(Material.GOLD_INGOT, "&b&lCoinflip", + "&7Click to enter the coinflip menu"); + ItemBuilder jackpotBuilder = new ItemBuilder(Material.DOUBLE_PLANT, "&6&lJackpot", + "&7Click to enter the jackpot menu"); + + this.gamblingInventory.addItem(new GuiItem(crashBuilder.colorize().build(), event -> { + CrashInventory crashInventory = new CrashInventory(player); + crashInventory.getUI().open(player); + })); + this.gamblingInventory.addItem(new GuiItem(diceBuilder.colorize().build(), event -> { + DiceInventory diceInventory = new DiceInventory(player); + diceInventory.getUI().open(player); + })); + /* + this.gamblingInventory.addItem(new GuiItem(bombsBuilder.colorize().build(), event -> { + BombsInformationInventory bombsInformationInventory = new BombsInformationInventory(player); + bombsInformationInventory.getUI().open(player); + })); + + */ + /* + this.gamblingInventory.addItem(new GuiItem(minesBuilder.colorize().build(), event -> { + MinesInformationInventory minesInformationInventory = new MinesInformationInventory(player); + minesInformationInventory.getUI().open(player); + })); + */ + this.gamblingInventory.addItem(new GuiItem(towerBuilder.colorize().build(), event -> { + TowerInformationInventory towerInformationInventory = new TowerInformationInventory(player); + towerInformationInventory.getUI().open(player); + })); + + /* + this.gamblingInventory.addItem(new GuiItem(rouletteBuilder.colorize().build(), event -> { + RouletteInformationInventory rouletteInformationInventory = new RouletteInformationInventory(player); + rouletteInformationInventory.getUI().open(player); + })); + + */ + + this.gamblingInventory.addItem(new GuiItem(coinflipBuilder.colorize().build())); + this.gamblingInventory.addItem(new GuiItem(jackpotBuilder.colorize().build())); + + + this.gamblingInventory.setItem(8, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit gambling menu").colorize().build(); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/GamblingPlugin.java b/Gambling/src/main/java/net/crankedpvp/gambling/GamblingPlugin.java new file mode 100644 index 0000000..fcd2656 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/GamblingPlugin.java @@ -0,0 +1,137 @@ +package net.crankedpvp.gambling; + +import lombok.Getter; +import lombok.Setter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import net.crankedpvp.gambling.coinflip.commands.CommandCoinFlip; +import net.crankedpvp.gambling.coinflip.listeners.InventoryListener; +import net.crankedpvp.gambling.coinflip.listeners.PlayerListener; +import net.crankedpvp.gambling.coinflip.struct.CoinFlipManager; +import net.crankedpvp.gambling.crash.commands.CrashCommand; +import net.crankedpvp.gambling.crash.listeners.CrashListener; +import net.crankedpvp.gambling.crash.manager.CrashManager; +import net.crankedpvp.gambling.crash.tasks.CrashTask; +import net.crankedpvp.gambling.data.GambleManager; +import net.crankedpvp.gambling.dice.commands.DiceCommand; +import net.crankedpvp.gambling.jackpot.commands.CommandJackpot; +import net.crankedpvp.gambling.jackpot.listeners.JackpotListener; +import net.crankedpvp.gambling.jackpot.struct.JackpotManager; +import net.crankedpvp.gambling.tower.commands.TowerCommand; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.IOException; + +@Getter +public class GamblingPlugin extends JavaPlugin { + + @Getter + private static GamblingPlugin instance; + + private GambleManager gambleManager; + private CoinFlipManager coinFlipManager; + private JackpotManager jackpotManager; + private CrashManager crashManager; + + private CommandManager commandManager; + + @Getter @Setter + private long overallCrashLosings; + @Getter @Setter + private long overallCrashWinnings; + @Getter @Setter + private long overallDiceLosings; + @Getter @Setter + private long overallDiceWinnings; + @Getter @Setter + private long overallTowerLosings; + @Getter @Setter + private long overallTowerWinnings; + @Getter @Setter + private long overallMinesLosings; + @Getter @Setter + private long overallMinesWinnings; + @Getter @Setter + private long overallBombsLosings; + @Getter @Setter + private long overallBombsWinnings; + + @Override + public void onEnable() { + instance = this; + this.commandManager = new CommandManager(this); + this.registerCommandParameters(); + this.commandManager.register(new CrashCommand(this)); + //this.commandManager.register(new BombsCommand(this)); + //this.commandManager.register(new MinesCommand(this)); + this.commandManager.register(new GamblingCommand(this)); + this.commandManager.register(new TowerCommand(this)); + this.commandManager.register(new DiceCommand(this)); + //this.commandManager.register(new RouletteCommand(this)); + this.gambleManager = new GambleManager(this); + this.coinFlipManager = new CoinFlipManager(); + //this.jackpotManager = new JackpotManager(); + this.crashManager = new CrashManager(this); + this.crashManager.setupLastBigCrashes(); + //jackpotManager.startNewJackpot(); + gambleManager.loadAll(); + PluginUtils.registerListeners(this, new InventoryListener(), new PlayerListener(), new JackpotListener()); + getCommand("coinflip").setExecutor(new CommandCoinFlip()); + //getCommand("jackpot").setExecutor(new CommandJackpot()); + + getServer().getPluginManager().registerEvents(new CrashListener(this), this); + //this.getServer().getScheduler().scheduleAsyncRepeatingTask(this, () -> this.jackpotManager.onJackpotTick(), 20L, 20L); + + this.crashManager.randomizeFinalCrashX(); + this.getServer().getScheduler().runTaskLater(this, () -> new CrashTask(this).initializeGame(), 60L); + + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, ()-> { + gambleManager.saveAll(); + }, 60L, 10*20*60); + + this.setOverallCrashLosings(getConfig().getLong("CRASH-LOSINGS")); + this.setOverallCrashWinnings(getConfig().getLong("CRASH-WINNINGS")); + this.setOverallTowerLosings(getConfig().getLong("TOWER-LOSINGS")); + this.setOverallTowerWinnings(getConfig().getLong("TOWER-WINNINGS")); + this.setOverallBombsLosings(getConfig().getLong("BOMBS-LOSINGS")); + this.setOverallBombsWinnings(getConfig().getLong("BOMBS-WINNINGS")); + this.setOverallMinesLosings(getConfig().getLong("MINES-LOSINGS")); + this.setOverallMinesWinnings(getConfig().getLong("MINES-WINNINGS")); + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(OfflinePlayer.class, argument -> { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(argument.toString()); + if(offlinePlayer == null) return new TypeResult(argument); + return new TypeResult(offlinePlayer, argument); + }); + } + + @Override + public void onDisable() { + this.getConfig().set("CRASH-WINNINGS", this.overallCrashWinnings); + this.getConfig().set("CRASH-LOSINGS", this.overallCrashLosings); + this.getConfig().set("DICE-WINNINGS", this.overallDiceWinnings); + this.getConfig().set("DICE-LOSINGS", this.overallDiceLosings); + this.getConfig().set("TOWER-WINNINGS", this.overallTowerWinnings); + this.getConfig().set("TOWER-LOSINGS", this.overallTowerLosings); + this.getConfig().set("BOMBS-WINNINGS", this.overallBombsWinnings); + this.getConfig().set("BOMBS-LOSINGS", this.overallBombsLosings); + this.getConfig().set("MINES-WINNINGS", this.overallMinesWinnings); + this.getConfig().set("MINES-LOSINGS", this.overallMinesLosings); + try { + this.getConfig().save(this.getDataFolder() + "/config.yml"); + } catch (IOException e) { + e.printStackTrace(); + } + coinFlipManager.onDisable(); + gambleManager.saveAll(); + instance = null; + + } + + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/bombs/commands/BombsCommand.java b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/commands/BombsCommand.java new file mode 100644 index 0000000..114844a --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/commands/BombsCommand.java @@ -0,0 +1,60 @@ +package net.crankedpvp.gambling.bombs.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.bombs.inventory.BombsDifficultySelectionInventory; +import net.crankedpvp.gambling.bombs.inventory.BombsInformationInventory; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.text.DecimalFormat; + +@Command("bombs") +public class BombsCommand extends CommandBase { + + private final GamblingPlugin plugin; + public BombsCommand(GamblingPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender, @Optional Double bet) { + Player player = (Player) commandSender; + if(bet == null) { + BombsInformationInventory bombsInformationInventory = new BombsInformationInventory(player); + bombsInformationInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + return; + } + + if(bet < 1) { + player.sendMessage(CC.translate("&cBet cannot be less than $1")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(EconomyUtils.hasBalance(player, bet)) { + BombsDifficultySelectionInventory bombsDifficultySelectionInventory = new BombsDifficultySelectionInventory(player, bet); + bombsDifficultySelectionInventory.getUI().open(player); + return; + } + + player.sendMessage(CC.translate("&cYou cannot afford this bet")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + @SubCommand("adminstats") + @Alias({"as", "adminstats"}) + @Permission("cranked.admin") + public void adminStatsCommand(CommandSender commandSender) { + commandSender.sendMessage("Overall Winnings: " + moneyFormat.format(this.plugin.getOverallBombsWinnings())); + commandSender.sendMessage("Overall Losings: " + moneyFormat.format(this.plugin.getOverallBombsLosings())); + commandSender.sendMessage("Overall Server Profit: " + moneyFormat.format(this.plugin.getOverallBombsWinnings() - this.plugin.getOverallBombsLosings())); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/bombs/enums/DifficultyType.java b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/enums/DifficultyType.java new file mode 100644 index 0000000..abe61f3 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/enums/DifficultyType.java @@ -0,0 +1,14 @@ +package net.crankedpvp.gambling.bombs.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@AllArgsConstructor @Getter +public enum DifficultyType { + EASY(4), + MEDIUM(18), + HARD(49), + ; + + private final int bombs; +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsDifficultySelectionInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsDifficultySelectionInventory.java new file mode 100644 index 0000000..e5b2119 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsDifficultySelectionInventory.java @@ -0,0 +1,61 @@ +package net.crankedpvp.gambling.bombs.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.bombs.enums.DifficultyType; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class BombsDifficultySelectionInventory { + + + private final Gui mineInventory; + + public Gui getUI() { + return this.mineInventory; + } + + + public BombsDifficultySelectionInventory(Player player, double bet) { + this.mineInventory = new Gui(GuiType.HOPPER, "Cranked Bombs Difficulty"); + this.mineInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemBuilder easyBuilder = new ItemBuilder(Material.WOOL, 1, (short) 5, + "&a&lEASY", + "&7An easy landfield...", + "&7A simple 3x3 grid with 4 bombs!"); + ItemBuilder mediumBuilder = new ItemBuilder(Material.WOOL, 1, (short) 4, + "&e&lMEDIUM", + "&7An intermediate landfield...", + "&7A 4x7 grid with 18 bombs!"); + ItemBuilder hardBuilder = new ItemBuilder(Material.WOOL, 1, (short) 14, + "&c&lHARD", + "&7A difficult landfield...", + "&7A 6x9 grid with 49 bombs!"); + this.mineInventory.setItem(1, new GuiItem(easyBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + BombsGameInventory minesGameInventory = new BombsGameInventory(player, DifficultyType.EASY, bet); + minesGameInventory.getUI().open(player); + })); + this.mineInventory.setItem(2, new GuiItem(mediumBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + BombsGameInventory minesGameInventory = new BombsGameInventory(player, DifficultyType.MEDIUM, bet); + minesGameInventory.getUI().open(player); + })); + this.mineInventory.setItem(3, new GuiItem(hardBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + BombsGameInventory minesGameInventory = new BombsGameInventory(player, DifficultyType.HARD, bet); + minesGameInventory.getUI().open(player); + })); + this.mineInventory.setItem(4, new GuiItem(createExitItem(), event -> player.closeInventory())); + this.mineInventory.setItem(0, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit bomb menu").colorize().build(); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsGameInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsGameInventory.java new file mode 100644 index 0000000..9ccfa58 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsGameInventory.java @@ -0,0 +1,142 @@ +package net.crankedpvp.gambling.bombs.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import net.crankedpvp.gambling.bombs.enums.DifficultyType; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class BombsGameInventory { + + private final GambleUser gambleUser; + + @Setter + private boolean hasLost = false; + + private Gui bombInventory; + public Gui getUI() { + return this.bombInventory; + } + + + public BombsGameInventory(Player player, DifficultyType difficultyType, double bet) { + + EconomyUtils.withdrawBalance(player, bet); + this.gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + + + this.bombInventory = new Gui(GuiType.CHEST, difficultyType.name()); + this.bombInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(!hasLost) { + EconomyUtils.depositBalance(player, bet); + player.sendMessage(CC.translate("&aYour money has been returned to you as you closed the GUI")); + } + }); + + switch(difficultyType) { + case EASY: + openEasyMinesGame(player, bet); + break; + case MEDIUM: + openMediumMinesGame(player, bet); + break; + case HARD: + openHardMinesGame(player, bet); + break; + } + + this.bombInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + } + + private void openEasyMinesGame(Player player, double bet) { + this.bombInventory = new Gui(GuiType.DISPENSER, "Easy Bomb Game"); + ItemBuilder unknownBuilder = new ItemBuilder(Material.ENDER_CHEST, "&f&l???"); + for(int i = 0; i < 9; i++) { + this.bombInventory.setItem(i, new GuiItem(unknownBuilder.colorize().build(), event -> { + if(Math.random() >= 0.44) { + setHasLost(true); + this.gambleUser.addBombsLoss(bet); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.EXPLODE, 5.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&c&lBOOM!"), CC.translate("&7You clicked a bomb!"), 1, 3, 1); + } else { + setHasLost(true); + this.gambleUser.addBombsWin(bet*2); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&a&lSAFE!"), CC.translate("&7You're safe from exploding..."), 1, 3, 1); + EconomyUtils.depositBalance(player, bet*2); + } + })); + } + } + + private void openMediumMinesGame(Player player, double bet) { + this.bombInventory = new Gui(6, "Medium Bomb Game"); + this.bombInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + ItemBuilder unknownBuilder = new ItemBuilder(Material.ENDER_CHEST, "&f&l???"); + for(int i = 0; i < 28; i++) { + this.bombInventory.addItem(new GuiItem(unknownBuilder.colorize().build(), event -> { + if(Math.random() >= 0.29) { + setHasLost(true); + this.gambleUser.addBombsLoss(bet); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.EXPLODE, 5.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&c&lBOOM!"), CC.translate("&7You clicked a bomb!"), 1, 3, 1); + } else { + setHasLost(true); + this.gambleUser.addBombsWin(bet*3); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&a&lSAFE!"), CC.translate("&7You're safe from exploding..."), 1, 3, 1); + EconomyUtils.depositBalance(player, bet*3); + } + })); + } + } + + private void openHardMinesGame(Player player, double bet) { + this.bombInventory = new Gui(6, "Medium Bomb Game"); + ItemBuilder unknownBuilder = new ItemBuilder(Material.ENDER_CHEST, "&f&l???"); + for(int i = 0; i < 54; i++) { + this.bombInventory.addItem(new GuiItem(unknownBuilder.colorize().build(), event -> { + if(Math.random() >= 0.15) { + setHasLost(true); + this.gambleUser.addBombsLoss(bet); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.EXPLODE, 5.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&c&lBOOM!"), CC.translate("&7You clicked a bomb!"), 1, 3, 1); + } else { + setHasLost(true); + this.gambleUser.addBombsWin(bet*5); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&a&lSAFE!"), CC.translate("&7You're safe from exploding..."), 1, 3, 1); + EconomyUtils.depositBalance(player, bet*5); + } + })); + } + } + + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsInformationInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsInformationInventory.java new file mode 100644 index 0000000..8491e3f --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/bombs/inventory/BombsInformationInventory.java @@ -0,0 +1,68 @@ +package net.crankedpvp.gambling.bombs.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class BombsInformationInventory { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + + private final Gui mineInventory; + + public Gui getUI() { + return this.mineInventory; + } + + + public BombsInformationInventory(Player player) { + this.mineInventory = new Gui(GuiType.HOPPER, "Cranked Bombs"); + this.mineInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, + "&cBombs Gambling", + "&7The game is &fsimple. &7It's a", + "&clandfield, &7filled with &cbombs", + "&7Choose a slot that contains a &cbomb,", + "&7and your &amoney &cblows up&7, poof.", + "&7otherwise, be fortunate and &fincrease", + "&7your &amoney &7generously", + "", + "&fUse &c/bombs &fto enter the game" + ).colorize().build(); + + GambleUser gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + List playerStatsLore = new ArrayList<>(); + playerStatsLore.add("&fWins: &a" + gambleUser.getBombsWins()); + playerStatsLore.add("&fWinnings: &a$" + moneyFormat.format(gambleUser.getBombsWinnings())); + playerStatsLore.add("&fLosses: &c" + gambleUser.getBombsLosses()); + playerStatsLore.add("&fLosings: &c$" + moneyFormat.format(gambleUser.getBombsLosings())); + playerStatsLore.add("&fRatio: &7[" + gambleUser.getMinesWinLossRatio(":") + "]"); + ItemBuilder playerStatsItemBuilder = new ItemBuilder(Material.PAPER, + "&cBombs Stats", + playerStatsLore); + + this.mineInventory.setItem(3, new GuiItem(playerStatsItemBuilder.setGlowing().colorize().build())); + this.mineInventory.setItem(2, new GuiItem(info)); + + this.mineInventory.setItem(4, new GuiItem(createExitItem(), event -> player.closeInventory())); + this.mineInventory.setItem(0, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit bombs menu").colorize().build(); + } + + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/commands/CommandCoinFlip.java b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/commands/CommandCoinFlip.java new file mode 100644 index 0000000..eabee36 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/commands/CommandCoinFlip.java @@ -0,0 +1,130 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * net.minecraft.util.org.apache.commons.lang3.StringUtils + * org.bukkit.ChatColor + * org.bukkit.OfflinePlayer + * org.bukkit.command.Command + * org.bukkit.command.CommandExecutor + * org.bukkit.command.CommandSender + * org.bukkit.entity.Player + * org.bukkit.me.astropvp.cratekeys.inventory.Inventory + * org.bukkit.metadata.FixedMetadataValue + * org.bukkit.metadata.MetadataValue + * org.bukkit.plugin.Plugin + */ +package net.crankedpvp.gambling.coinflip.commands; + + +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.coinflip.struct.CoinFlipManager; +import net.crankedpvp.gambling.coinflip.struct.CoinFlipMatch; +import net.crankedpvp.gambling.data.GambleUser; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.metadata.FixedMetadataValue; + +import java.text.DecimalFormat; + +public class CommandCoinFlip +implements CommandExecutor { + private final DecimalFormat decimalFormat = new DecimalFormat("#,###.##"); + + public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { + if (!(sender instanceof Player)) { + return true; + } + CoinFlipManager manager = GamblingPlugin.getInstance().getCoinFlipManager(); + Player player = (Player)sender; + if (args.length == 1) { + if (args[0].equalsIgnoreCase("help")) { + player.sendMessage(ChatColor.YELLOW.toString() + ChatColor.BOLD + ChatColor.UNDERLINE + "Coin Flip Help"); + player.sendMessage(ChatColor.YELLOW + "/coinflip"); + player.sendMessage(ChatColor.GRAY + "View all active Coin Flip matches."); + player.sendMessage(ChatColor.YELLOW + "/coinflip "); + player.sendMessage(ChatColor.GRAY + "Start a Coin Flip match with the given wager."); + player.sendMessage(ChatColor.YELLOW + "/coinflip cancel"); + player.sendMessage(ChatColor.GRAY + "Cancel the pending Coin Flip match."); + player.sendMessage(ChatColor.YELLOW + "/coinflip toggle"); + player.sendMessage(ChatColor.GRAY + "Toggle Coin Flip win notifications."); + player.sendMessage(ChatColor.YELLOW + "/coinflip stats"); + player.sendMessage(ChatColor.GRAY + "View your current Coin Flip stats."); + return true; + } + if (args[0].equalsIgnoreCase("stats")) { + GambleUser gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + sender.sendMessage(""); + sender.sendMessage(ChatColor.YELLOW + ChatColor.BOLD.toString() + "Coin Flip Stats"); + String format = ChatColor.YELLOW + ChatColor.UNDERLINE.toString() + "%s" + ChatColor.GRAY + " - " + ChatColor.YELLOW + ChatColor.BOLD.toString() + "$%s"; + sender.sendMessage(ChatColor.YELLOW + "Total Wins: " + String.format(format, gambleUser.getCoinflipWins(), this.decimalFormat.format(gambleUser.getCoinflipWinnings()))); + sender.sendMessage(ChatColor.YELLOW + "Total Losses: " + String.format(format, gambleUser.getCoinflipLosses(), this.decimalFormat.format(gambleUser.getCoinflipLosings()))); + sender.sendMessage(ChatColor.YELLOW + "Taxes Paid: " + ChatColor.YELLOW + ChatColor.BOLD.toString() + "$" + this.decimalFormat.format(gambleUser.getCoinFlipTaxesPaid())); + sender.sendMessage(""); + return true; + } + + if (args[0].equalsIgnoreCase("stfu") || args[0].equalsIgnoreCase("toggle") || args[0].equalsIgnoreCase("notifications")) { + //toggle notis + return true; + } + + CoinFlipMatch match = manager.getMatch(player); + if (match != null) { + if (args[0].equalsIgnoreCase("cancel")) { + if (match.getMatchState() == CoinFlipMatch.MatchState.WAITING) { + EconomyUtils.depositBalance(player, match.getWager()); + match.setMatchState(CoinFlipMatch.MatchState.DONE); + manager.getCoinFlipMatches().remove(match); + player.sendMessage(ChatColor.RED + "You left your Coin Flip Match!"); + return true; + } + sender.sendMessage(ChatColor.RED + "You can not leave the match at this time."); + return true; + } + sender.sendMessage(ChatColor.RED + "You are already in a Coin Flip Match!"); + return true; + } + String number = args[0].replace("k", "000").replace("m", "000000").replace("b", "000000000"); + if (StringUtils.isNumeric(number)) { + double val = Double.parseDouble(number); + if (val <= 0.0) { + sender.sendMessage(ChatColor.RED + "You must enter a valid amount to bet!"); + return true; + } + if (!EconomyUtils.hasBalance(player, val)) { + sender.sendMessage(ChatColor.RED + "You do not have that much money to bet!"); + return true; + } + if (val < 10000.0) { + sender.sendMessage(ChatColor.RED + "You must bet atleast $10,000!"); + return true; + } + player.setMetadata("coinFlipWage", new FixedMetadataValue(GamblingPlugin.getInstance(), val)); + Inventory flip = manager.getCoinFlipSelectMenu(val, null); + player.openInventory(flip); + } else { + sender.sendMessage(ChatColor.RED + "You must enter a valid amount to bet!"); + } + return true; + } else { + if (args.length == 0) { + ((Player)sender).openInventory(manager.getLobbyInventory((Player)sender)); + return true; + } + sender.sendMessage(ChatColor.GREEN + "/coinflip"); + sender.sendMessage(ChatColor.WHITE + "View all active Coin Flip Matches."); + sender.sendMessage(""); + sender.sendMessage(ChatColor.GREEN + "/coinflip "); + sender.sendMessage(ChatColor.WHITE + "Create a Coin Flip Match to vs another player!"); + } + return true; + } +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/listeners/InventoryListener.java b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/listeners/InventoryListener.java new file mode 100644 index 0000000..0d93c15 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/listeners/InventoryListener.java @@ -0,0 +1,182 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * net.minecraft.server.v1_7_R4.ItemStack + * net.minecraft.server.v1_7_R4.NBTTagCompound + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.Material + * org.bukkit.OfflinePlayer + * org.bukkit.craftbukkit.v1_7_R4.me.astropvp.cratekeys.inventory.CraftItemStack + * org.bukkit.entity.Player + * org.bukkit.event.Event$Result + * org.bukkit.event.EventHandler + * org.bukkit.event.EventPriority + * org.bukkit.event.Listener + * org.bukkit.event.me.astropvp.cratekeys.inventory.InventoryClickEvent + * org.bukkit.event.me.astropvp.cratekeys.inventory.InventoryCloseEvent + * org.bukkit.event.player.PlayerInteractEntityEvent + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.metadata.FixedMetadataValue + * org.bukkit.metadata.MetadataValue + * org.bukkit.plugin.Plugin + */ +package net.crankedpvp.gambling.coinflip.listeners; + +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.coinflip.struct.CoinColor; +import net.crankedpvp.gambling.coinflip.struct.CoinFlipManager; +import net.crankedpvp.gambling.coinflip.struct.CoinFlipMatch; +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class InventoryListener +implements Listener { + private final Map choosingColors = new HashMap(); + + @EventHandler + public void onPLayerClose(InventoryCloseEvent event) { + Player player = (Player)event.getPlayer(); + this.choosingColors.remove(player.getUniqueId()); + } + + @EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true) + public void onPlayerInteract(PlayerInteractEntityEvent event) { + Player clicked; + if (event.getRightClicked() instanceof Player && (clicked = (Player)event.getRightClicked()).getName().endsWith("Coin Flipper") && clicked.hasMetadata("NPC")) { + event.setCancelled(true); + event.getPlayer().chat("/cf"); + } + } + + @EventHandler + public void onPlayerClick(InventoryClickEvent event) { + Player player = (Player)event.getWhoClicked(); + if (event.getInventory().getName().startsWith("Coin Flip Match") && !event.getInventory().getName().equals("Coin Flip Matches")) { + event.setCancelled(true); + return; + } + if (event.getInventory().getName().equals("Choose a Color")) { + double amount; + event.setCancelled(true); + event.setResult(Event.Result.DENY); + CoinFlipManager manager = GamblingPlugin.getInstance().getCoinFlipManager(); + CoinFlipMatch joining = this.choosingColors.get(player.getUniqueId()); + boolean joiningMatch = joining != null; + CoinFlipMatch activeMatch = manager.getMatch(player); + if (activeMatch != null && !joiningMatch) { + player.sendMessage(ChatColor.RED + "You already have a pending coin flip!"); + return; + } + if (!(player.hasMetadata("coinFlipWage") && player.getMetadata("coinFlipWage").size() > 0 || joiningMatch)) { + return; + } + ItemStack item = event.getCurrentItem(); + if (item == null || item.getType() != Material.WOOL) { + return; + } + CoinColor chosen = CoinColor.getFromDyeColor(item.getDurability()); + if (chosen == null) { + return; + } + double d = amount = joiningMatch ? joining.getWager() : player.getMetadata("coinFlipWage").get(0).asDouble(); + if (EconomyUtils.hasBalance(player, amount)) { + if (joiningMatch) { + if (joining.getMatchState() != CoinFlipMatch.MatchState.WAITING) { + player.closeInventory(); + player.sendMessage(ChatColor.RED + "Coin Flip match no longer valid!"); + return; + } + if (!manager.getCoinFlipMatches().contains(joining)) { + player.sendMessage(ChatColor.RED + "Coin flip match no longer valid."); + player.closeInventory(); + return; + } + if (chosen == joining.getFirstColor()) { + player.sendMessage(ChatColor.RED + "Color already taken!"); + return; + } + joining.setSecondColor(chosen); + joining.onAcceptMatch(player); + return; + } + CoinFlipMatch newMatch = new CoinFlipMatch(player, amount, chosen); + player.closeInventory(); + manager.getCoinFlipMatches().add(newMatch); + player.sendMessage(ChatColor.GREEN + ChatColor.BOLD.toString() + "(!) " + ChatColor.GREEN + "Coin Flip queued, waiting for opponent to /coinflip."); + player.sendMessage(ChatColor.GRAY + "To cancel your Coin Flip match, use /coinflip cancel"); + } else { + player.sendMessage(ChatColor.RED + "You do not have $" + amount + " anymore!"); + } + player.removeMetadata("coinFlipWage", GamblingPlugin.getInstance()); + } else if (event.getInventory().getName().equals("Coin Flip Matches")) { + event.setCancelled(true); + event.setResult(Event.Result.DENY); + if (event.getRawSlot() <= event.getInventory().getSize() - 1 && event.getCurrentItem() != null) { + String name; + Player pl; + NBTTagCompound tag; + ItemStack item = event.getCurrentItem(); + if (item == null || item.getType() == Material.AIR) { + return; + } + if (item.getType() == Material.CHEST) { + Long cd; + Long l = cd = player.hasMetadata("cf_refresh") && player.getMetadata("cf_refresh").size() > 0 ? player.getMetadata("cf_refresh").get(0).asLong() : null; + if (cd != null && cd > System.currentTimeMillis()) { + player.sendMessage(ChatColor.RED + "Please wait 3 seconds in between refreshes!"); + return; + } + player.closeInventory(); + player.setMetadata("cf_refresh", new FixedMetadataValue(GamblingPlugin.getInstance(), System.currentTimeMillis() + 3000L)); + Bukkit.getScheduler().scheduleSyncDelayedTask(GamblingPlugin.getInstance(), () -> player.openInventory(GamblingPlugin.getInstance().getCoinFlipManager().getLobbyInventory(player)), 1L); + return; + } + net.minecraft.server.v1_8_R3.ItemStack nmsItem = CraftItemStack.asNMSCopy(item); + if (nmsItem.hasTag() && (tag = nmsItem.getTag()) != null && tag.hasKey("wager") && (pl = Bukkit.getPlayer(name = tag.getString("wager"))) != null) { + CoinFlipManager manager = GamblingPlugin.getInstance().getCoinFlipManager(); + CoinFlipMatch match = manager.getMatch(pl); + if (match == null) { + event.getInventory().removeItem(item); + } else if (match.getMatchState() == CoinFlipMatch.MatchState.WAITING) { + if (manager.getMatch(player) != null) { + player.sendMessage(ChatColor.RED + "You are already in a Coin Flip Match!"); + player.closeInventory(); + return; + } + if (EconomyUtils.hasBalance(player, match.getWager())) { + player.closeInventory(); + this.choosingColors.put(player.getUniqueId(), match); + player.openInventory(manager.getCoinFlipSelectMenu(match.getWager(), match.getFirstColor())); + } else { + player.sendMessage(ChatColor.RED + "You do not have enough money to accept that wager!"); + } + } else { + player.sendMessage(ChatColor.RED + "Match no longer valid..."); + event.getInventory().removeItem(item); + } + } + } + } + } +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/listeners/PlayerListener.java b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/listeners/PlayerListener.java new file mode 100644 index 0000000..4fb4dc2 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/listeners/PlayerListener.java @@ -0,0 +1,48 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.event.EventHandler + * org.bukkit.event.Listener + * org.bukkit.event.player.PlayerJoinEvent + * org.bukkit.event.player.PlayerQuitEvent + */ +package net.crankedpvp.gambling.coinflip.listeners; + +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.coinflip.struct.CoinFlipManager; +import net.crankedpvp.gambling.coinflip.struct.CoinFlipMatch; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class PlayerListener +implements Listener { + public static Map ipAddresses = new HashMap<>(); + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + ipAddresses.put(event.getPlayer().getUniqueId(), event.getPlayer().getAddress().getHostString()); + } + + @EventHandler + public void onPlayerLeave(PlayerQuitEvent event) { + CoinFlipManager coinFlipManager = GamblingPlugin.getInstance().getCoinFlipManager(); + CoinFlipMatch match = coinFlipManager.getMatch(event.getPlayer()); + if (match != null) { + match.onPlayerLogout(event.getPlayer()); + } + } + + public static boolean hasSameIP(UUID uuid, UUID other) { + String first = ipAddresses.get(uuid); + String second = ipAddresses.get(other); + return first != null && first.equals(second); + } +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinColor.java b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinColor.java new file mode 100644 index 0000000..7e64ce5 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinColor.java @@ -0,0 +1,61 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.DyeColor + */ +package net.crankedpvp.gambling.coinflip.struct; + +import org.bukkit.ChatColor; +import org.bukkit.DyeColor; + +public enum CoinColor { + PURPLE(ChatColor.LIGHT_PURPLE + ChatColor.BOLD.toString() + "Purple", ChatColor.LIGHT_PURPLE, DyeColor.PURPLE), + BLUE(ChatColor.AQUA + ChatColor.BOLD.toString() + "Blue", ChatColor.AQUA, DyeColor.LIGHT_BLUE), + RED(ChatColor.RED + ChatColor.BOLD.toString() + "Red", ChatColor.RED, DyeColor.RED), + GREEN(ChatColor.GREEN + ChatColor.BOLD.toString() + "Green", ChatColor.GREEN, DyeColor.LIME), + BLACK(ChatColor.DARK_GRAY + ChatColor.BOLD.toString() + "Black", ChatColor.DARK_GRAY, DyeColor.BLACK), + YELLOW(ChatColor.YELLOW + ChatColor.BOLD.toString() + "Yellow", ChatColor.YELLOW, DyeColor.YELLOW), + ORANGE(ChatColor.GOLD + ChatColor.BOLD.toString() + "Orange", ChatColor.GOLD, DyeColor.ORANGE), + WHITE(ChatColor.WHITE + ChatColor.BOLD.toString() + "White", ChatColor.WHITE, DyeColor.WHITE), + GRAY(ChatColor.GRAY + ChatColor.BOLD.toString() + "Gray", ChatColor.GRAY, DyeColor.GRAY); + + private final String name; + private final ChatColor chatColor; + private final DyeColor dyeColor; + + public CoinColor getOppositeColor() { + if (this == PURPLE) { + return BLUE; + } + return PURPLE; + } + + public static CoinColor getFromDyeColor(short dura) { + for (CoinColor color : CoinColor.values()) { + if (color.getDyeColor().getData() != dura) continue; + return color; + } + return null; + } + + CoinColor(String name, ChatColor chatColor, DyeColor dyeColor) { + this.name = name; + this.chatColor = chatColor; + this.dyeColor = dyeColor; + } + + public String getName() { + return this.name; + } + + public ChatColor getChatColor() { + return this.chatColor; + } + + public DyeColor getDyeColor() { + return this.dyeColor; + } +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinFlipManager.java b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinFlipManager.java new file mode 100644 index 0000000..a946f35 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinFlipManager.java @@ -0,0 +1,112 @@ +package net.crankedpvp.gambling.coinflip.struct; + + +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.SlotUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; +import java.util.*; + +@Getter +public class CoinFlipManager { + private final Set coinFlipMatches = new HashSet<>(); + private final Map previousOpponent = new HashMap(); + private int alertAmount = 10000; + private final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private final DecimalFormat format = new DecimalFormat("#,###"); + + public CoinFlipMatch getMatch(Player player) { + for (CoinFlipMatch match : this.coinFlipMatches) { + if (!match.getStarterPlayer().equals(player) && (match.getSecondPlayer() == null || !match.getSecondPlayer().equals(player))) continue; + return match; + } + return null; + } + + public void addWin(UUID uuid, double winnings, double tax) { + GambleUser gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(uuid); + gambleUser.addCoinflipTax(tax); + gambleUser.addCoinflipWin(winnings); + } + + public void addLoss(UUID uuid, double lost) { + GambleUser gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(uuid); + gambleUser.addCoinflipLoss(lost); + } + + public Inventory getLobbyInventory(Player player) { + Inventory inventory = Bukkit.createInventory(null, SlotUtils.fitSlots((int)this.coinFlipMatches.stream().filter(match -> match.getMatchState() == CoinFlipMatch.MatchState.WAITING).count() + 2), "Coin Flip Matches"); + this.updateInventory(player, inventory); + return inventory; + } + + public void updateInventory(Player player, Inventory inventory) { + inventory.clear(); + this.coinFlipMatches.forEach(match -> { + if (match.getMatchState() != CoinFlipMatch.MatchState.WAITING) { + return; + } + double balance = EconomyUtils.getBalance(player); + GambleUser gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(match.getStarterPlayer().getUniqueId()); + String winLoss = gambleUser == null ? "0 (0:0)" : (gambleUser.getCoinflipLosses() == 0 ? Integer.valueOf(gambleUser.getCoinflipWins()) : this.decimalFormat.format((double) gambleUser.getCoinflipWins() / (double) gambleUser.getCoinflipLosses())) + " (" + gambleUser.getCoinflipWins() + ":" + gambleUser.getCoinflipLosses() + ")"; + ItemStack stack = new ItemBuilder(SkullUtils.getSkullFromPlayer(match.getStarterPlayer())) + .setName(FactionUtils.getFactionTag(player, match.getStarterPlayer()) + " " + ChatColor.BOLD.toString() + match.getStarterPlayer().getDisplayName()) + .setLore("", ChatColor.YELLOW + ChatColor.BOLD.toString() + "Wager", ChatColor.GRAY + " " + ChatColor.GRAY + ChatColor.BOLD + "$" + ChatColor.GRAY + this.format.format(match.getWager()), ChatColor.GRAY + ChatColor.ITALIC.toString() + " -5% Tax " + ChatColor.GRAY + "($" + this.format.format(match.getTax()) + ")", "", ChatColor.YELLOW + ChatColor.BOLD.toString() + "Color Chosen", match.getFirstColor().getName(), "", ChatColor.YELLOW + ChatColor.BOLD.toString() + "Total Win/Loss Ratio", ChatColor.GRAY + " " + winLoss, "", balance >= match.getWager() ? ChatColor.GRAY + "Click to accept this coin flip wager" : ChatColor.GRAY + "You can " + ChatColor.RED + ChatColor.BOLD + "NOT" + ChatColor.GRAY + " afford this wager!") + .build(); + net.minecraft.server.v1_8_R3.ItemStack item = CraftItemStack.asNMSCopy(stack); + NBTTagCompound tag = item.getTag(); + if (tag == null) { + tag = new NBTTagCompound(); + item.setTag(tag); + } + tag.setString("wager", match.getStarterPlayer().getName()); + inventory.addItem(CraftItemStack.asCraftMirror(item)); + }); + inventory.setItem(inventory.getSize() - 2, new ItemBuilder(Material.BOOK, ChatColor.GREEN.toString() + ChatColor.BOLD + "Coin Flip Help", "", ChatColor.YELLOW + "/coinflip", ChatColor.GRAY + "View all active Coin Flip matches.", "", ChatColor.YELLOW + "/coinflip ", ChatColor.GRAY + "Start a Coin Flip match with the given wager.", "", ChatColor.YELLOW + "/coinflip cancel", ChatColor.GRAY + "Cancel the pending Coin Flip match.", "", ChatColor.YELLOW + "/coinflip toggle", ChatColor.GRAY + "Toggle Coin Flip win notifications.", "", ChatColor.YELLOW + "/coinflip stats", ChatColor.GRAY + "View your Coinflip stats with /coinflip stats").build()); + inventory.setItem(inventory.getSize() - 1, new ItemBuilder(Material.CHEST, ChatColor.GREEN + ChatColor.BOLD.toString() + "Refresh", ChatColor.GRAY + "Click to refresh coinflip matches.").build()); + } + + public Inventory getCoinFlipSelectMenu(double wage, CoinColor picked) { + Inventory inventory = Bukkit.createInventory(null, SlotUtils.fitSlots(CoinColor.values().length), "Choose a Color"); + for (CoinColor color : CoinColor.values()) { + if (color.equals(picked)) continue; + inventory.addItem(new ItemBuilder(Material.WOOL, 1, color.getDyeColor().getWoolData(), color.getName(), ChatColor.GRAY + "Click to select this color", ChatColor.GRAY + "and start the coin clip for", ChatColor.GREEN + ChatColor.BOLD.toString() + "$" + ChatColor.GREEN + this.format.format(wage)).build()); + } + return inventory; + } + + public void onDisable() { + for (CoinFlipMatch active : getCoinFlipMatches()) { + if (active.getMatchState() == CoinFlipMatch.MatchState.WAITING) { + if (active.getStarterPlayer() == null) continue; + EconomyUtils.depositBalance(active.getStarterPlayer(), active.getWager()); + Bukkit.getLogger().info("Depositing $" + active.getWager() + " to " + active.getStarterPlayer().getName() + " due to reload..."); + continue; + } + if (active.getMatchState() == CoinFlipMatch.MatchState.DONE) continue; + if (active.getStarterPlayer() != null) { + EconomyUtils.depositBalance(active.getStarterPlayer(), active.getWager()); + Bukkit.getLogger().info("Depositing $" + active.getWager() + " to " + active.getStarterPlayer().getName() + " due to reload..."); + } + if (active.getSecondPlayer() == null) continue; + EconomyUtils.depositBalance(active.getSecondPlayer(), active.getWager()); + Bukkit.getLogger().info("Depositing $" + active.getWager() + " to " + active.getSecondPlayer().getName() + " due to reload..."); + } + getCoinFlipMatches().clear(); + } +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinFlipMatch.java b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinFlipMatch.java new file mode 100644 index 0000000..92058eb --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/coinflip/struct/CoinFlipMatch.java @@ -0,0 +1,280 @@ +package net.crankedpvp.gambling.coinflip.struct; + + +import com.golfing8.kore.FactionsKore; +import com.golfing8.kore.feature.OutpostFeature; +import com.google.common.collect.Lists; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitRunnable; + +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +@Getter +@Setter +public class CoinFlipMatch { + private final Player starterPlayer; + private Player secondPlayer; + private CoinColor firstColor; + private CoinColor secondColor; + private CoinColor winningColor; + private MatchState matchState = MatchState.WAITING; + private double wager; + public static double TAX = 0.05; + private Inventory coinFlipMenu; + private boolean gavePrize = false; + private final String playerName; + private String player2Name; + private final UUID playerUUID; + private UUID player2UUID; + private static final Map defaultHeadStacks = new HashMap(); + private CoinColor previousColor; + private final DecimalFormat format = new DecimalFormat("#,###"); + private final OutpostFeature outpostFeature; + + public CoinFlipMatch(Player starter, double wager, CoinColor firstColor) { + this.wager = wager; + this.starterPlayer = starter; + this.previousColor = firstColor; + this.playerUUID = starter.getUniqueId(); + this.playerName = starter.getDisplayName(); + this.firstColor = firstColor; + this.outpostFeature = FactionsKore.get().getFeature(OutpostFeature.class); + EconomyUtils.withdrawBalance(starter, this.wager); + starter.sendMessage(ChatColor.RED.toString() + ChatColor.BOLD + "- $" + ChatColor.RED + this.format.format(this.wager)); + } + + public double getTax() { + return TAX * this.wager; + } + + public ItemStack getSkull(Player player, Player other) { + ItemStack defaultSkill = defaultHeadStacks.computeIfAbsent(player.getUniqueId(), k -> SkullUtils.getSkullFromPlayer(player)); + ItemStack skull = defaultSkill.clone(); + ItemMeta im = skull.getItemMeta(); + im.setDisplayName(FactionUtils.getFactionTag(other, player) + ChatColor.BOLD.toString() + " " + player.getDisplayName()); + im.setLore(Lists.newArrayList(ChatColor.GREEN + "Balance: " + ChatColor.GREEN + ChatColor.BOLD + "$" + ChatColor.GREEN + this.format.format(EconomyUtils.getBalance(player)))); + skull.setItemMeta(im); + return skull; + } + + public void buildFlipMenu() { + String title = "Coin Flip Match - $" + this.format.format(this.wager * 2.0); + if (title.length() >= 32) { + title = title.substring(0, 31); + } + this.coinFlipMenu = Bukkit.createInventory(null, 9, title); + this.coinFlipMenu.setItem(0, this.getSkull(this.getStarterPlayer(), this.getSecondPlayer())); + this.coinFlipMenu.setItem(1, new ItemBuilder(Material.STAINED_GLASS_PANE, 1, this.getFirstColor().getDyeColor().getWoolData(), this.getFirstColor().getChatColor() + this.getStarterPlayer().getName() + "'s Color", "").build()); + this.coinFlipMenu.setItem(7, new ItemBuilder(Material.STAINED_GLASS_PANE, 1, this.getSecondColor().getDyeColor().getWoolData(), this.getSecondColor().getChatColor() + this.getSecondPlayer().getName() + "'s Color", "").build()); + this.coinFlipMenu.setItem(8, this.getSkull(this.getSecondPlayer(), this.getStarterPlayer())); + this.matchState = MatchState.STARTING; + this.coinFlipMenu.setItem(4, new ItemBuilder(Material.STAINED_GLASS_PANE, 5, DyeColor.LIME.getWoolData(), ChatColor.GREEN + ChatColor.BOLD.toString() + 5, ChatColor.GRAY + "Rolling in " + 5 + "s").build()); + new BukkitRunnable() { + int timer = 0; + + public void run() { + ++this.timer; + if (this.timer >= 5) { + this.cancel(); + CoinFlipMatch.this.startRoll(); + return; + } + for (Player pl : CoinFlipMatch.this.getPlayers()) { + if (pl == null || !pl.isOnline()) { + this.cancel(); + return; + } + pl.playSound(pl.getLocation(), Sound.NOTE_PIANO, 1.0f, 1.4f); + } + CoinFlipMatch.this.coinFlipMenu.setItem(4, new ItemBuilder(Material.STAINED_GLASS_PANE, 5 - this.timer, this.timer <= 2 ? DyeColor.LIME.getWoolData() : (this.timer <= 4 ? DyeColor.YELLOW.getWoolData() : DyeColor.RED.getWoolData()), ChatColor.GREEN + ChatColor.BOLD.toString() + (5 - this.timer), ChatColor.GRAY + "Rolling in " + (5 - this.timer) + "s").build()); + } + }.runTaskTimer(GamblingPlugin.getInstance(), 20L, 20L); + } + + public void startRoll() { + this.matchState = MatchState.FLIPPING; + (new BukkitRunnable() { + int ticks = 0; + + final int maxTicks = 70 + ThreadLocalRandom.current().nextInt(2) + ThreadLocalRandom.current().nextInt(2) + ThreadLocalRandom.current().nextInt(2); + + public void run() { + if (CoinFlipMatch.this.gavePrize) { + cancel(); + return; + } + if (this.ticks >= this.maxTicks) { + cancel(); + ItemStack winner = CoinFlipMatch.this.coinFlipMenu.getItem(4); + if (winner != null && winner.getType() == Material.WOOL) { + CoinFlipMatch.this.winningColor = CoinColor.getFromDyeColor(winner.getDurability()); + CoinFlipMatch.this.endCoinFlip(RemoveReason.WON, (CoinFlipMatch.this.getFirstColor() == CoinFlipMatch.this.winningColor) ? CoinFlipMatch.this.getStarterPlayer() : CoinFlipMatch.this.getSecondPlayer()); + UUID loser = (CoinFlipMatch.this.getFirstColor() == CoinFlipMatch.this.winningColor) ? CoinFlipMatch.this.getSecondPlayer().getUniqueId() : CoinFlipMatch.this.getStarterPlayer().getUniqueId(); + GamblingPlugin.getInstance().getCoinFlipManager().addLoss(loser, CoinFlipMatch.this.wager); + } + return; + } + this.ticks++; + boolean lastTick = (this.ticks == this.maxTicks); + if (!lastTick && this.ticks >= 20 && ((this.ticks >= 50 && this.ticks % 2 == 0) || (this.ticks >= 40 && this.ticks % 3 == 0) || (this.ticks >= 30 && this.ticks % 4 == 0))) + return; + for (Player player : CoinFlipMatch.this.getPlayers()) { + if (player == null || !player.isOnline()) { + cancel(); + return; + } + player.playSound(player.getLocation(), Sound.NOTE_PLING, 1.0F, 1.1F); + } + CoinColor color = !lastTick ? ((CoinFlipMatch.this.previousColor == CoinFlipMatch.this.getFirstColor()) ? CoinFlipMatch.this.getSecondColor() : CoinFlipMatch.this.getFirstColor()) : CoinFlipMatch.this.getWinnerColor(); + String winnerName = (lastTick && color.equals(CoinFlipMatch.this.getFirstColor())) ? (CoinFlipMatch.this.getFirstColor().getChatColor() + ChatColor.BOLD.toString() + CoinFlipMatch.this.getStarterPlayer().getName()) : ((lastTick && color.equals(CoinFlipMatch.this.getSecondColor())) ? (CoinFlipMatch.this.getSecondColor().getChatColor() + ChatColor.BOLD.toString() + CoinFlipMatch.this.getSecondPlayer().getName()) : null); + CoinFlipMatch.this.previousColor = color; + CoinFlipMatch.this.coinFlipMenu.setItem(4, new ItemBuilder(Material.WOOL, 1, color.getDyeColor().getWoolData(), (winnerName != null) ? winnerName : color.getName(), (winnerName != null) ? (winnerName + ChatColor.GRAY + " has won the Coin Flip!") : (ChatColor.GRAY + "Rolling...")).build()); + for (Player pl : CoinFlipMatch.this.getPlayers()) { + if (pl != null) + pl.updateInventory(); + } + } + }).runTaskTimer(GamblingPlugin.getInstance(), 20L, 2L); + } + + public CoinColor getWinnerColor() { + if (ThreadLocalRandom.current().nextBoolean()) { + return this.getFirstColor(); + } + return this.getSecondColor(); + } + + public void endCoinFlip(RemoveReason reason, Player forceWinner) { + if (this.matchState == MatchState.DONE) { + return; + } + this.matchState = MatchState.DONE; + GamblingPlugin.getInstance().getCoinFlipManager().getCoinFlipMatches().remove(this); + if (reason == RemoveReason.LEAVE) { + Player loser; + Player winner; + winner = ThreadLocalRandom.current().nextBoolean() ? this.starterPlayer : this.secondPlayer; + if (winner != null) { + this.givePrize(winner); + } + loser = winner != null && winner.equals(this.starterPlayer) ? this.secondPlayer : this.starterPlayer; + if (loser != null && winner != null) { + GamblingPlugin.getInstance().getCoinFlipManager().addLoss(loser.getUniqueId(), this.getWager()); + } + } else if (reason == RemoveReason.WON && forceWinner != null) { + for (Player player : this.getPlayers()) { + if (player == null) continue; + player.sendMessage(ChatColor.GREEN + ChatColor.BOLD.toString() + "(!) " + ChatColor.GREEN + forceWinner.getName() + " has won the Coin Flip with " + this.winningColor.getName() + ChatColor.GREEN + "!"); + } + this.givePrize(forceWinner); + } + } + + public void onAcceptMatch(Player player) { + this.secondPlayer = player; + this.player2Name = player.getDisplayName(); + this.player2UUID = player.getUniqueId(); + EconomyUtils.withdrawBalance(player, this.wager); + this.buildFlipMenu(); + player.sendMessage(ChatColor.RED.toString() + ChatColor.BOLD + "- $" + ChatColor.RED + this.format.format(this.wager)); + for (Player pl : this.getPlayers()) { + pl.playSound(pl.getLocation(), Sound.NOTE_PIANO, 1.0f, 1.1f); + pl.sendMessage(ChatColor.RED + player.getName() + " has accepted the Coin Flip Wager!"); + pl.openInventory(this.coinFlipMenu); + } + this.coinFlipMenu.setItem(0, this.getSkull(this.getStarterPlayer(), this.getSecondPlayer())); + this.coinFlipMenu.setItem(8, this.getSkull(this.getSecondPlayer(), this.getStarterPlayer())); + } + + public void givePrize(Player player) { + if (this.gavePrize) { + return; + } + this.gavePrize = true; + UUID loser = player.getUniqueId().equals(this.playerUUID) ? this.player2UUID : this.playerUUID; + double totalWines = this.wager * 2.0; + double taxRate = TAX; + double win; + + + if (this.outpostFeature.hasOutpost("demonic", FactionUtils.getFactionId(player))) { + player.sendMessage(CC.translate("&6&lStrongholds &8" + Arrow.arrow() + "&7 The coinflip tax was not applied as you control the stronghold")); + taxRate = 0; + } + + //Here tax is recuced from the win + win = totalWines * (1.0 - taxRate); + + CoinFlipManager manager = GamblingPlugin.getInstance().getCoinFlipManager(); + manager.addWin(player.getUniqueId(), win, taxRate * this.wager); + EconomyUtils.depositBalance(player, win); + player.sendMessage(ChatColor.GREEN.toString() + ChatColor.BOLD + "+ $" + this.format.format(win)); + GambleUser gambleUserWinner = GamblingPlugin.getInstance().getGambleManager().getGambleUser(playerUUID); + GambleUser gambleUserLoser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(loser); + + for (Player pl : Bukkit.getOnlinePlayers()) { + //if (GamblingPlugin.getInstance().getCoinFlipManager().getToggledNotifications().contains(pl.getUniqueId())) + //continue; + pl.sendMessage(""); + pl.sendMessage(ChatColor.GREEN.toString() + ChatColor.BOLD + "Coin Flip " + ChatColor.DARK_GRAY + "➥ " + this.getColorChosen(player.getUniqueId()).getChatColor() + "\u25a0 " + FactionUtils.getFactionTag(pl, player) + ChatColor.GREEN + " " + player.getDisplayName() + ChatColor.GRAY + " (" + gambleUserWinner.getCoinflipWinLossRatio("-") + ") has defeated " + ChatColor.RED + this.getColorChosen(loser).getChatColor() + "\u25a0 " + FactionUtils.getFactionTag(pl, Bukkit.getPlayer(loser)) + " " + ChatColor.RED + (player.getDisplayName().equals(this.playerName) ? this.player2Name : this.playerName) + ChatColor.GRAY + " (" + gambleUserLoser.getCoinflipWinLossRatio("-") + ") in a " + ChatColor.GRAY + ChatColor.UNDERLINE + "$" + this.format.format(totalWines) + ChatColor.GRAY + " /coinflip"); + pl.sendMessage(""); + } + + } + + public CoinColor getColorChosen(UUID uuid) { + if (this.playerUUID.equals(uuid)) { + return this.getFirstColor(); + } + return this.getSecondColor(); + } + + public List getPlayers() { + return Lists.newArrayList(this.starterPlayer, this.secondPlayer); + } + + public void onPlayerLogout(Player player) { + if (this.matchState == MatchState.FLIPPING || this.matchState == MatchState.STARTING) { + this.endCoinFlip(RemoveReason.LEAVE, null); + } else if (this.matchState == MatchState.WAITING && this.getSecondPlayer() == null) { + this.matchState = MatchState.DONE; + EconomyUtils.depositBalance(player, this.wager); + Bukkit.getLogger().info("Returning wager of " + this.wager + " to " + player.getName()); + GamblingPlugin.getInstance().getCoinFlipManager().getCoinFlipMatches().remove(this); + } + } + + public enum MatchState { + WAITING, + STARTING, + FLIPPING, + DONE + + } + + public enum RemoveReason { + LEAVE, + WON + + } +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/CrashAPI.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/CrashAPI.java new file mode 100644 index 0000000..be32798 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/CrashAPI.java @@ -0,0 +1,123 @@ +package net.crankedpvp.gambling.crash; + +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.crash.inventory.CrashInventory; +import net.crankedpvp.gambling.crash.manager.CrashManager; +import net.crankedpvp.gambling.crash.struct.CrashGame; +import net.crankedpvp.gambling.crash.struct.CrashPlayer; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.stream.Collectors; + +public class CrashAPI { + + public static final String prefix = "&6&lCRASH &8➥ "; + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + public static List getFixedCrashOpenInventoryList() { + List players = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach(player -> { + if(playerHasCrashGUIOpen(player)) players.add(player); + }); + return players.stream().distinct().collect(Collectors.toList()); + } + + public static boolean playerHasCrashGUIOpen(Player player) { + return player.getOpenInventory().getTopInventory().getTitle().equals("Cranked Crash"); + } + + public static CrashPlayer getPlayerFromCrashGame(OfflinePlayer player, CrashGame crashGame) { + return getPlayerFromCrashGame(player.getUniqueId(), crashGame); + } + + public static boolean isPlayerInCrashGame(UUID uuid, CrashGame crashGame) { + for(CrashPlayer player : crashGame.getPlayers()) { + if(Objects.equals(player.getPlayerUUID().toString(), uuid.toString())) { + return true; + } + } + return false; + } + + public static CrashPlayer getPlayerFromCrashGame(UUID uuid, CrashGame crashGame) { + if(!isPlayerInCrashGame(uuid, crashGame)) { + return new CrashPlayer(uuid, 0D, null, crashGame.getCrashX()); + }; + + crashGame.getPlayers().forEach(crashPlayer -> Bukkit.getOfflinePlayer(crashPlayer.getPlayerUUID()).getName()); + for(CrashPlayer crashPlayer : crashGame.getPlayers()) { + if(Objects.equals(crashPlayer.getPlayerUUID().toString(), uuid.toString())) { + return crashPlayer; + } + } + return new CrashPlayer(uuid, 0D, null, crashGame.getCrashX()); + } + + + public static void tryBet(Player player, double bet) { + + if(bet < 100) { + player.sendMessage(CC.translate(CrashAPI.prefix + "&cYou cannot bet less than $100")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + GamblingPlugin plugin = GamblingPlugin.getInstance(); + if(plugin.getCrashManager().hasBetted(player) || plugin.getCrashManager().getWaitingToJoinCrash().containsKey(player)) { + player.sendMessage(CC.translate(CrashAPI.prefix + "&cYou have already betted for that round")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(plugin.getCrashManager().isActive()) { + plugin.getCrashManager().getWaitingToJoinCrash().put(player, bet); + player.sendMessage(CC.translate(CrashAPI.prefix + "&aYou will be entered into next game if you have enough money")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + return; + } + + if(!EconomyUtils.hasBalance(player, bet)) { + player.sendMessage(CC.translate(CrashAPI.prefix + "&cYou do not have sufficient funds for that")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + EconomyUtils.withdrawBalance(player, bet); + CrashManager crashManager = plugin.getCrashManager(); + crashManager.getBets().put(player, bet); + crashManager.getLastBets().put(player, bet); + player.sendMessage(CC.translate(CrashAPI.prefix + "&aYou have joined the crash game with $" + moneyFormat.format(bet))); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + + CrashAPI.getFixedCrashOpenInventoryList().forEach(loopPlayer -> { + ItemBuilder itemBuilder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) 3, + "&fPlayer: &a" + player.getName(), + "&fBet: &a$" + moneyFormat.format(bet)).setSkullOwner(player.getName()); + loopPlayer.getOpenInventory().getTopInventory().addItem(itemBuilder.colorize().build()); + loopPlayer.updateInventory(); + + }); + + if(CrashAPI.playerHasCrashGUIOpen(player)) return; + + CrashInventory crashInventory = new CrashInventory(player); + crashInventory.getUI().open(player); + + + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/commands/CrashCommand.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/commands/CrashCommand.java new file mode 100644 index 0000000..92494e7 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/commands/CrashCommand.java @@ -0,0 +1,73 @@ +package net.crankedpvp.gambling.crash.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.crash.CrashAPI; +import net.crankedpvp.gambling.crash.inventory.CrashInventory; +import net.crankedpvp.gambling.crash.inventory.CrashStatsInventory; +import org.bukkit.OfflinePlayer; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.text.DecimalFormat; + +@Command("crash") +public class CrashCommand extends CommandBase { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final GamblingPlugin plugin; + public CrashCommand(GamblingPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender, @Optional Double bet) { + Player player = (Player)commandSender; + if(bet == null) { + CrashInventory crashInventory = new CrashInventory(player); + crashInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + return; + } + + CrashAPI.tryBet(player, bet); + } + + @SubCommand("setpayout") + @Alias({"payout", "autopayout", "setautopayout"}) + public void setAutoPayoutCommand(CommandSender commandSender, Double autoPayout) { + Player player = (Player) commandSender; + if(autoPayout < 1) { + player.sendMessage(CC.translate(CrashAPI.prefix + "&cYou cannot set your auto payout below 1x")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + plugin.getGambleManager().getGambleUser(player.getUniqueId()).setCrashAutoPayout(autoPayout); + player.sendMessage(CC.translate(CrashAPI.prefix + "&7Your new auto payout is: " + autoPayout)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + + @SubCommand("stats") + @WrongUsage("/crash stats ") + public void statsCommand(CommandSender commandSender, OfflinePlayer player) { + Player sender = (Player) commandSender; + CrashStatsInventory statsInventory = new CrashStatsInventory(sender, player); + statsInventory.getUI().open(sender); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @SubCommand("adminstats") + @Alias({"as", "adminstats"}) + @Permission("cranked.admin") + public void adminStatsCommand(CommandSender commandSender) { + commandSender.sendMessage("Overall Winnings: " + moneyFormat.format(this.plugin.getOverallCrashWinnings())); + commandSender.sendMessage("Overall Losings: " + moneyFormat.format(this.plugin.getOverallCrashLosings())); + commandSender.sendMessage("Overall Player Profit: " + moneyFormat.format(this.plugin.getOverallCrashWinnings() - this.plugin.getOverallCrashLosings())); + } + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashGameInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashGameInventory.java new file mode 100644 index 0000000..9b30ee3 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashGameInventory.java @@ -0,0 +1,97 @@ +package net.crankedpvp.gambling.crash.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.crash.struct.CrashGame; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class CrashGameInventory { + + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final Gui crashGameInventory; + + public Gui getUI() { + return this.crashGameInventory; + } + + + public CrashGameInventory(Player player, CrashGame crashGame) { + this.crashGameInventory = new Gui(6, "Crash Game: " + String.valueOf(crashGame.getCrashGameID()).split("-")[0]); + this.crashGameInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.crashGameInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + + crashGame.getPlayers().forEach(crashPlayer -> { + OfflinePlayer crashPlayerAsPlayer = Bukkit.getOfflinePlayer(crashPlayer.getPlayerUUID()); + + List lore = new ArrayList<>(); + String line = crashGame.getCrashX() >= 1.98D ? "&fCrashed: &a" + decimalFormat.format(crashGame.getCrashX()) + "x" : "&fCrashed: &c" + decimalFormat.format(crashGame.getCrashX()) + "x"; + lore.add(line); + + ItemBuilder itemBuilder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) 3).setSkullOwner(crashPlayerAsPlayer.getName()); + + if(crashPlayer.isWinner()) { + itemBuilder.setName("&fCrash Win: &a" + crashPlayerAsPlayer.getName()); + lore.add("&fCashout: &a" + decimalFormat.format(crashPlayer.getCashout()) + "x"); + lore.add("&fBet: &a$" + moneyFormat.format(crashPlayer.getMoney())); + lore.add("&fProfit: &a$" + moneyFormat.format((crashPlayer.getCashout() * crashPlayer.getMoney()) - crashPlayer.getMoney())); + itemBuilder.setLore(lore); + } else { + itemBuilder.setName("&fCrash Lose: &c" + crashPlayerAsPlayer.getName()); + lore.add("&fCashout: &cBUST"); + lore.add("&fBet: &a$" + moneyFormat.format(crashPlayer.getMoney())); + lore.add("&fProfit: &c$0.0"); + itemBuilder.setLore(lore); + } + + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&7Click to view player crash stats"); + + this.crashGameInventory.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + player.closeInventory(); + CrashStatsInventory statsInventory = new CrashStatsInventory(player, Bukkit.getOfflinePlayer(crashPlayer.getPlayerUUID())); + statsInventory.getUI().open(player); + })); + + }); + + this.crashGameInventory.setItem(6, 9, new GuiItem(createExitItem(), event -> { + player.closeInventory(); + CrashStatsInventory menu = new CrashStatsInventory(player, player); + menu.getUI().open(player); + })); + + this.crashGameInventory.setItem(6, 1, new GuiItem(createExitItem(), event -> { + player.closeInventory(); + CrashStatsInventory menu = new CrashStatsInventory(player, player); + menu.getUI().open(player); + })); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cGo back to your stats").colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(" "); + item.setItemMeta(meta); + return item; + } + + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashInventory.java new file mode 100644 index 0000000..5ceca86 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashInventory.java @@ -0,0 +1,238 @@ +package net.crankedpvp.gambling.crash.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.crash.CrashAPI; +import net.crankedpvp.gambling.crash.manager.CrashManager; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class CrashInventory { + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final GamblingPlugin plugin = GamblingPlugin.getInstance(); + private final CrashManager crashManager = GamblingPlugin.getInstance().getCrashManager(); + + + private final Gui crashInventory; + + public Gui getUI() { + return this.crashInventory; + } + + public CrashInventory(Player player) { + this.crashInventory = new Gui(6, "Cranked Crash"); + this.crashInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.crashInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + + addLast10CrashesToGui(); + addStatsToGui(player); + addInfoToGui(); + addAutoCashOutToGui(player); + addReEnterBetToGui(player); + addSoundToggleToGui(player); + addLast100XToGui(); + + updateCrashStar(this.crashManager.getCurrentCrashX()); + + addPlayersToInventory(); + + } + + private void addLast100XToGui() { + ItemBuilder lastX = new ItemBuilder(Material.DIAMOND, "&6&lRecent High Crashes"); + lastX.addLoreLine("&fThe following lines show the last time"); + lastX.addLoreLine("&feach crash multiplier has crashed at"); + for(int bigX : new int[] {5, 10, 25, 50, 100, 250, 500, 1000}) + lastX.addLoreLine(" &f" + moneyFormat.format(bigX) + "x: &e" + moneyFormat.format(this.crashManager.getLastBigCrashes().get(bigX)) + " &fGames ago"); + lastX.setGlowing(); + this.crashInventory.setItem(1, 9, new GuiItem(lastX.colorize().build())); + } + + private void addPlayersToInventory() { + this.crashManager.getBets().forEach((player, bet) -> { + ItemBuilder itemBuilder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) 3, + "&fPlayer: &a" + player.getName(), + "&fBet: &a$" + moneyFormat.format(bet)).setSkullOwner(player.getName()); + this.crashInventory.addItem(new GuiItem(itemBuilder.colorize().build())); + }); + + if(!crashManager.isActive()) { + this.crashManager.getWaitingToJoinCrash().forEach((player, bet) -> { + ItemBuilder itemBuilder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) 3, + "&fPlayer: &a" + player.getName(), + "&fBet: &a$" + moneyFormat.format(bet)).setSkullOwner(player.getName()); + this.crashInventory.addItem(new GuiItem(itemBuilder.colorize().build())); + }); + } + + this.crashManager.getCashedAt().forEach((player, pair) -> { + List lore = new ArrayList<>(); + lore.add("&fBet: &a$" + moneyFormat.format(pair.getRight())); + lore.add("&fCashed Out: &a" + decimalFormat.format(pair.getLeft()) + "x"); + lore.add("&fCashed Amount: &a$" + moneyFormat.format(pair.getLeft() * pair.getRight())); + ItemBuilder cashedOutBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short) 5, + "&fPlayer: &a" + player.getName()); + cashedOutBuilder.setLore(lore); + cashedOutBuilder.setGlowing(); + + this.crashInventory.addItem(new GuiItem(cashedOutBuilder.colorize().build())); + }); + } + + + public void updateCrashStar(double newCrashAmount) { + if(!crashManager.isActive()) { + + String crashStarName = "&c&lCRASH @ " + decimalFormat.format(crashManager.getFinalCrashX()) + "x"; + + ItemStack crashStar = new ItemBuilder(Material.BARRIER, + crashStarName, + "&7&oA new game will be starting soon...").colorize().build(); + + this.crashInventory.updateItem(49, new GuiItem(crashStar)); + return; + } + + String crashStarName = newCrashAmount < 1.98 + ? "&fCashout: &c" + decimalFormat.format(newCrashAmount) + "x" + : "&fCashout: &a" + decimalFormat.format(newCrashAmount) + "x"; + + + ItemStack crashStar = new ItemBuilder(Material.NETHER_STAR, + crashStarName).colorize().build(); + this.crashInventory.updateItem(49, new GuiItem(crashStar)); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate(" ")); + item.setItemMeta(meta); + return item; + } + + private void addInfoToGui() { + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, + "&6Crash Gambling", + "&7Crash is a gambling game where", + "&7a crash &6multiplier &7quickly &fincreases", + "&7starting at &61.00x. &7The multiplier (if you cash", + "&7out), determines how much &aprofit &7you make!", + "", + "&cBe careful, &7the game can &cend &7at any time,", + "&7and if you haven't &fcashed out &7by then", + "&7you get &cnothing.", + "", + "&7This crash game has an &fauto cashout", + "&7feature, which &eautomatically &7cashes out", + "&7at the multiplier value set by the user", + "&f/crash setautopayout ", + "", + "&7You can view the crash &fstats &7of", + "&7other players using /crash stats ", + "", + "&6&lTIP: &fUse &e/crash &fto enter the game" + ).colorize().build(); + + this.crashInventory.updateItem(1, 5, new GuiItem(info)); + } + + private void addLast10CrashesToGui() { + ItemBuilder itemBuilder = new ItemBuilder(Material.REDSTONE, + "&6Last 10 Crashes"); + itemBuilder.addLoreLine("&7The most recent crash is at the top"); + + for (int crashNumber = this.crashManager.getRecentCrashes().size(); crashNumber > 1; crashNumber--) { + double crash = this.crashManager.getRecentCrashes().get(crashNumber-1); + String line = crash > 1.98 ? "&fCrash #" + (crashNumber-1) + ": &a" + decimalFormat.format(crash) + "x" : "&fCrash #" + (crashNumber-1) + ": &c" + decimalFormat.format(crash) + "x"; + itemBuilder.addLoreLine(line); + } + + this.crashInventory.setItem(3, 9, new GuiItem(itemBuilder.colorize().build())); + } + + private void addStatsToGui(Player player) { + ItemStack stats = new ItemBuilder(Material.SIGN, + "&6Crash Statistics", + "&7Click to view stats").colorize().build(); + this.crashInventory.setItem(3, 1, new GuiItem(stats, event -> { + player.closeInventory(); + CrashStatsInventory statsInventory = new CrashStatsInventory(player, player); + statsInventory.getUI().open(player); + })); + } + + private void addReEnterBetToGui(Player player) { + String lastBet = crashManager.getLastBets().containsKey(player) ? "&a$" + moneyFormat.format(crashManager.getLastBets().get(player)) : "&cNot Entered"; + ItemBuilder reenterBuilder = new ItemBuilder(Material.MINECART, "&6&lRe Enter Bet", + "&fLast Bet: " + lastBet, + "&fBalance: &a$" + moneyFormat.format(EconomyUtils.getBalance(player))); + this.crashInventory.updateItem(6, 9, new GuiItem(reenterBuilder.colorize().setGlowing().build(), event -> { + if(crashManager.getLastBets().containsKey(player)) CrashAPI.tryBet(player, crashManager.getLastBets().get(player)); + })); + + } + + private void addAutoCashOutToGui(Player player) { + GambleUser gambleUser = plugin.getGambleManager().getGambleUser(player.getUniqueId()); + this.crashInventory.updateItem(6, 1, new GuiItem(buildAutoCrashPayoutItem(gambleUser), event -> { + + if(event.isLeftClick()) + gambleUser.setCrashAutoPayout(gambleUser.getCrashAutoPayout() + 1); + + if(event.isRightClick() && gambleUser.getCrashAutoPayout() >= 2) + gambleUser.setCrashAutoPayout(gambleUser.getCrashAutoPayout() + - 1); + + addAutoCashOutToGui(player); + + })); + } + + private ItemStack buildAutoCrashPayoutItem(GambleUser gambleUser) { + ItemBuilder autoCashOut = new ItemBuilder(Material.GOLD_INGOT, "&d&lAuto Cash Out", + "&7The value set here will be the", + "&7multiplier that is automatically cashed", + "&7out at when you join the crash game", + "", + "&fAuto Payout: &d" + gambleUser.getCrashAutoPayout() + "x"); + + return autoCashOut.colorize().build(); + } + + private void addSoundToggleToGui(Player player) { + GambleUser gambleUser = this.plugin.getGambleManager().getGambleUser(player.getUniqueId()); + this.crashInventory.updateItem(1, 1, new GuiItem(getSoundToggleItem(gambleUser), event -> { + player.playSound(player.getLocation(), Sound.CLICK, 2.0F, 2.0F); + gambleUser.setCrashSound(!gambleUser.isCrashSound()); + this.crashInventory.updateItem(1, 1, getSoundToggleItem(gambleUser)); + })); + + } + + private ItemStack getSoundToggleItem(GambleUser gambleUser) { + boolean hasSound = gambleUser.isCrashSound(); + String sound = hasSound ? "&a&lON" : "&c&lOFF"; + + ItemBuilder soundToggleBuilder = new ItemBuilder(Material.REDSTONE_TORCH_ON, "&dToggle Crash Sounds", + "&fToggled: " + sound); + + return soundToggleBuilder.colorize().build(); + } + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashStatsInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashStatsInventory.java new file mode 100644 index 0000000..fa4cb06 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/inventory/CrashStatsInventory.java @@ -0,0 +1,120 @@ +package net.crankedpvp.gambling.crash.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.crash.CrashAPI; +import net.crankedpvp.gambling.crash.manager.CrashManager; +import net.crankedpvp.gambling.crash.struct.CrashPlayer; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class CrashStatsInventory { + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + + private final PaginatedGui statsMenu; + + public PaginatedGui getUI() { + return this.statsMenu; + } + + + public CrashStatsInventory(Player player, OfflinePlayer statsOf) { + this.statsMenu = new PaginatedGui(6, 28, "Crash Stats: " + statsOf.getName()); + this.statsMenu.setDefaultClickAction(event -> event.setCancelled(true)); + this.statsMenu.getFiller().fillBorder(new GuiItem(createFillerItem())); + + List statsLore = new ArrayList<>(); + GamblingPlugin gamblingPlugin = GamblingPlugin.getInstance(); + GambleUser gambleUser = gamblingPlugin.getGambleManager().getGambleUser(statsOf.getUniqueId()); + statsLore.add("&fOverall Wins: &a" + gambleUser.getCrashWins()); + statsLore.add("&fOverall Losses: &c" + gambleUser.getCrashLosses()); + statsLore.add("&fMoney Won: &a$" + NumberUtils.coolFormat(gambleUser.getCrashWinnings())); + statsLore.add("&fMoney Lost: &c$" + NumberUtils.coolFormat(gambleUser.getCrashLosings())); + double profit = gambleUser.getCrashWinnings() - gambleUser.getCrashLosings(); + String netProfit = profit >= 0 ? "&fNet Profit: &a$" + NumberUtils.coolFormat(profit) : "&fNet Profit: &c$" + NumberUtils.coolFormat(profit); + statsLore.add(netProfit); + + ItemStack info = new ItemBuilder(Material.SKULL_ITEM, 1, (short) 3, "&c" + statsOf.getName() + " Stats") + .setSkullOwner(statsOf.getName()).setLore(statsLore).colorize().build(); + + ItemStack prevPage = new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.").colorize().build(); + ItemStack nextPage = new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.").colorize().build(); + + this.statsMenu.setItem(6, 1, new GuiItem(prevPage, event -> { + this.statsMenu.previous(); + event.setCancelled(true); + })); + this.statsMenu.setItem(6, 9, new GuiItem(nextPage, event -> { + this.statsMenu.next(); + event.setCancelled(true); + })); + + this.statsMenu.setItem(6, 5, new GuiItem(createExitItem(), event -> { + player.closeInventory(); + CrashInventory menu = new CrashInventory(player); + menu.getUI().open(player); + })); + + this.statsMenu.setItem(4, new GuiItem(info)); + CrashManager crashManager = GamblingPlugin.getInstance().getCrashManager(); + if(crashManager.getPlayerCrashGraphMap().containsKey(statsOf.getUniqueId()) && !crashManager.getPlayerCrashGraphMap().get(statsOf.getUniqueId()).getCrashGames().isEmpty()) { + crashManager.getPlayerCrashGraphMap().get(statsOf.getUniqueId()).getCrashGames().forEach(crashGame -> { + ItemStack itemStack; + List lore = new ArrayList<>(); + CrashPlayer crashPlayer = CrashAPI.getPlayerFromCrashGame(statsOf, crashGame); + String line = crashGame.getCrashX() >= 1.98D ? "&fCrashed: &a" + decimalFormat.format(crashGame.getCrashX()) + "x" : "&fCrashed: &c" + decimalFormat.format(crashGame.getCrashX()) + "x"; + lore.add(line); + if(crashPlayer.isWinner()) { + ItemBuilder itemBuilder = new ItemBuilder(Material.SUGAR, "&aCrash Win"); + lore.add("&fCashout: &a" + decimalFormat.format(crashPlayer.getCashout()) + "x"); + lore.add("&fBet: &a$" + moneyFormat.format(crashPlayer.getMoney())); + lore.add("&fProfit: &a$" + moneyFormat.format((crashPlayer.getCashout() * crashPlayer.getMoney()) - crashPlayer.getMoney())); + itemBuilder.setLore(lore); + itemStack = itemBuilder.colorize().build(); + } else { + ItemBuilder itemBuilder = new ItemBuilder(Material.REDSTONE, "&cCrash Lose"); + lore.add("&fCashout: &cBUST"); + lore.add("&fBet: &a$" + moneyFormat.format(crashPlayer.getMoney())); + lore.add("&fProfit: &c$0.0"); + itemBuilder.setLore(lore); + itemStack = itemBuilder.colorize().build(); + } + + this.statsMenu.addItem(new GuiItem(itemStack, event -> { + CrashGameInventory crashGameInventory = new CrashGameInventory(player, crashGame); + crashGameInventory.getUI().open(player); + })); + + }); + } + + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cGo back to Crash Menu").colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/listeners/CrashListener.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/listeners/CrashListener.java new file mode 100644 index 0000000..dfd8c62 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/listeners/CrashListener.java @@ -0,0 +1,83 @@ +package net.crankedpvp.gambling.crash.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.Pair; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.crash.CrashAPI; +import net.crankedpvp.gambling.crash.manager.CrashManager; +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class CrashListener implements Listener { + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final GamblingPlugin plugin; + private final CrashManager crashManager; + public CrashListener(GamblingPlugin plugin) { + this.plugin = plugin; + this.crashManager = plugin.getCrashManager(); + } + + @EventHandler + public void inventoryClickCheck(InventoryClickEvent event) { + + if(!Objects.equals(event.getInventory().getTitle(), "Cranked Crash")) return; + if(event.getSlot() != 49) return; + + if(!crashManager.isActive()) return; + Player player = (Player) event.getWhoClicked(); + if(!crashManager.hasBetted(player)) return; + double amount = Double.parseDouble(StringUtils.chop(ChatColor.stripColor(event.getCurrentItem().getItemMeta().getDisplayName()).split("Cashout: ")[1])); + if(amount <= crashManager.getFinalCrashX()) { + double moneyBetted = crashManager.getBets().get(player); + double cashedOutAmount = moneyBetted * amount; + crashManager.getBets().remove(player); + EconomyUtils.depositBalance(player, cashedOutAmount); + player.sendMessage(CC.translate(CrashAPI.prefix + "&eYou have cashed out for &a$" + moneyFormat.format(cashedOutAmount))); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 3.0F, 3.0F); + crashManager.getCashedAt().put(player, new Pair<>(amount, moneyBetted)); + + List lore = new ArrayList<>(); + lore.add("&fBet: &a$" + moneyFormat.format(moneyBetted)); + lore.add("&fCashed Out: &a" + decimalFormat.format(amount) + "x"); + lore.add("&fCashed Amount: &a$" + moneyFormat.format(cashedOutAmount)); + ItemBuilder itemBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short) 5, + "&fPlayer: &a" + player.getName()); + itemBuilder.setLore(lore); + itemBuilder.setGlowing(); + + CrashAPI.getFixedCrashOpenInventoryList().forEach(loopPlayer -> { + Inventory inventory = loopPlayer.getOpenInventory().getTopInventory(); + for(int i = 0; i < 50; i++) { + if(inventory.getItem(i) == null || inventory.getItem(i).getType() == Material.AIR) continue; + String toLookIn = ChatColor.stripColor(inventory.getItem(i).getItemMeta().getDisplayName()); + if(!toLookIn.contains(":")) continue; + toLookIn = toLookIn.split(": ")[1]; + if(Objects.equals(toLookIn, player.getName())) { + inventory.setItem(i, itemBuilder.colorize().build()); + loopPlayer.updateInventory(); + } + } + }); + } + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/manager/CrashManager.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/manager/CrashManager.java new file mode 100644 index 0000000..1073e51 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/manager/CrashManager.java @@ -0,0 +1,149 @@ +package net.crankedpvp.gambling.crash.manager; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.Pair; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.crash.struct.CrashGraph; +import org.bukkit.entity.Player; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +public class CrashManager { + + private final GamblingPlugin plugin; + public CrashManager(GamblingPlugin plugin) { + this.plugin = plugin; + } + + @Getter + private final Map playerCrashGraphMap = new HashMap<>(); + + @Getter @Setter + private boolean active; + + @Getter @Setter + private double currentCrashX; + + @Getter @Setter + private double finalCrashX; + + @Getter + private final Map bets = new HashMap<>(); + + @Getter + private final Map waitingToJoinCrash = new HashMap<>(); + + @Getter + private final Map> cashedAt = new HashMap<>(); + + @Getter + private final LinkedList recentCrashes = new LinkedList<>(); + + @Getter + private final Map lastBets = new HashMap<>(); + + @Getter + private final Map lastBigCrashes = new HashMap<>(); + + + public void setupLastBigCrashes() { + this.lastBigCrashes.put(1000, 0); + this.lastBigCrashes.put(500, 0); + this.lastBigCrashes.put(250, 0); + this.lastBigCrashes.put(100, 0); + this.lastBigCrashes.put(50, 0); + this.lastBigCrashes.put(25, 0); + this.lastBigCrashes.put(10, 0); + this.lastBigCrashes.put(5, 0); + } + + public void randomizeFinalCrashX() { + if(Math.random() > 0.97) { + this.setFinalCrashX(1.0D); + return; + } + + if(Math.random() > 0.9997) { + this.setFinalCrashX(ThreadLocalRandom.current().nextDouble(351, 1250)); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 90) { + this.setFinalCrashX(1 + (Math.random() / 3)); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 50) { + this.setFinalCrashX(1 + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 50) { + this.setFinalCrashX(2 + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 45) { + this.setFinalCrashX(3 + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 40) { + this.setFinalCrashX(ThreadLocalRandom.current().nextDouble(4, 7)); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 35) { + this.setFinalCrashX(ThreadLocalRandom.current().nextDouble(8, 17)); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 30) { + this.setFinalCrashX(ThreadLocalRandom.current().nextDouble(18, 41) + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 25) { + this.setFinalCrashX(ThreadLocalRandom.current().nextDouble(42, 101) + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 20) { + this.setFinalCrashX(ThreadLocalRandom.current().nextDouble(102, 254) + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 15) { + this.setFinalCrashX(ThreadLocalRandom.current().nextDouble(255, 498) + Math.random()); + return; + } + + this.setFinalCrashX(ThreadLocalRandom.current().nextInt(499, 1250) + Math.random()); + } + + public boolean hasBetted(Player player) { + return bets.containsKey(player); + } + + + /* + public void save() { + for (Map.Entry entry : playerCrashGraphMap.entrySet()) { + UUID uuid = entry.getKey(); + CrashGraph graph = entry.getValue(); + plugin.getGambleManager().getGambleUser(uuid).setCrashGraph(graph); + } + } + + public void load() { + for (GambleUser gambleUser : plugin.getGambleManager().getCacheValues()) { + playerCrashGraphMap.put(gambleUser.getUuid(), gambleUser.getCrashGraph()); + } + } + */ + + + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CounterSpeed.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CounterSpeed.java new file mode 100644 index 0000000..3d2eb11 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CounterSpeed.java @@ -0,0 +1,30 @@ +package net.crankedpvp.gambling.crash.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@AllArgsConstructor @Getter +public enum CounterSpeed { + + + LAST(null, 3.84D, 2L, 5000D), + TWELTH(CounterSpeed.LAST, 1.77D, 2L, 500D), + ELEVENTH(CounterSpeed.TWELTH, 0.782D, 2L, 250D), + TENTH(CounterSpeed.ELEVENTH, 0.45D, 2L, 64D), + NINTH(CounterSpeed.LAST, 0.219D, 2L, 37D), + EIGTH(CounterSpeed.NINTH, 0.136D, 2L, 22D), + SEVENTH(CounterSpeed.EIGTH, 0.051D, 1L, 15D), + SIXTH(CounterSpeed.SEVENTH, 0.032D, 1L, 9D), + FIFTH(CounterSpeed.SIXTH, 0.018D, 1L, 5.7D), + FOURTH(CounterSpeed.FIFTH, 0.017D, 2L, 3.3D), + THIRD(CounterSpeed.FOURTH, 0.01D, 2L, 2.05D), + SECOND(CounterSpeed.THIRD, 0.01D, 3L, 1.5D), + FIRST(CounterSpeed.SECOND, 0.01D, 4L, 1.15D), + ; + + private final CounterSpeed nextCounterSpeed; + private final double multiplier; + private final long ticks; + private final double threshold; + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashGame.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashGame.java new file mode 100644 index 0000000..dd7c257 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashGame.java @@ -0,0 +1,15 @@ +package net.crankedpvp.gambling.crash.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.io.Serializable; +import java.util.List; +import java.util.UUID; + +@Getter @AllArgsConstructor +public class CrashGame { + private UUID crashGameID; + private List players; + private double crashX; +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashGraph.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashGraph.java new file mode 100644 index 0000000..d76b400 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashGraph.java @@ -0,0 +1,17 @@ +package net.crankedpvp.gambling.crash.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; +import java.util.UUID; + +@Getter @AllArgsConstructor +public class CrashGraph { + + private UUID playerUUID; + @Setter + private List crashGames; + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashPlayer.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashPlayer.java new file mode 100644 index 0000000..a8399a5 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/struct/CrashPlayer.java @@ -0,0 +1,25 @@ +package net.crankedpvp.gambling.crash.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.io.Serializable; +import java.util.UUID; + +@Getter @AllArgsConstructor +public class CrashPlayer { + private UUID playerUUID; + private Double money; + private Double cashout; + private Double crashGameCrashX; + + public boolean isWinner() { + if(cashout == null) return false; + return cashout <= crashGameCrashX; + } + + public Double getWinnings() { + if(!isWinner()) return null; + return money * cashout; + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/crash/tasks/CrashTask.java b/Gambling/src/main/java/net/crankedpvp/gambling/crash/tasks/CrashTask.java new file mode 100644 index 0000000..d53d504 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/crash/tasks/CrashTask.java @@ -0,0 +1,313 @@ +package net.crankedpvp.gambling.crash.tasks; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.Pair; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.crash.CrashAPI; +import net.crankedpvp.gambling.crash.manager.CrashManager; +import net.crankedpvp.gambling.crash.struct.CounterSpeed; +import net.crankedpvp.gambling.crash.struct.CrashGame; +import net.crankedpvp.gambling.crash.struct.CrashGraph; +import net.crankedpvp.gambling.crash.struct.CrashPlayer; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; +import java.util.*; + +public class CrashTask { + + private final GamblingPlugin plugin; + private final CrashManager crashManager; + private UUID crashGameUUID; + + public CrashTask(GamblingPlugin plugin) { + this.plugin = plugin; + this.crashManager = plugin.getCrashManager(); + } + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private int crashTaskID; + + public void initializeGame() { + this.crashGameUUID = UUID.randomUUID(); + this.crashManager.setActive(true); + this.crashManager.randomizeFinalCrashX(); + crashManager.setCurrentCrashX(1.0D); + plugin.getServer().getScheduler().cancelTask(this.crashTaskID); + this.startCounter(CounterSpeed.FIRST); + } + + + private void startCounter(CounterSpeed counterSpeed) { + this.crashTaskID = plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, () -> { + if(crashManager.getCurrentCrashX() >= crashManager.getFinalCrashX()) { + setGameFinished(); + return; + } + + if(crashManager.getCurrentCrashX() >= counterSpeed.getThreshold()) { + plugin.getServer().getScheduler().cancelTask(this.crashTaskID); + startCounter(counterSpeed.getNextCounterSpeed()); + return; + } + + finalizeCounter(counterSpeed.getMultiplier()); + }, 0L, counterSpeed.getTicks()); + } + + + private void finalizeCounter(double multiplier) { + crashManager.setCurrentCrashX(crashManager.getCurrentCrashX() + multiplier); + + String crashStarName = crashManager.getCurrentCrashX() < 1.98 + ? "&cCashout: &f" + decimalFormat.format(crashManager.getCurrentCrashX()) + "x" + : "&aCashout: &f" + decimalFormat.format(crashManager.getCurrentCrashX()) + "x"; + + ItemBuilder itemBuilder = new ItemBuilder(Material.NETHER_STAR, + crashStarName); + + for(Player player : CrashAPI.getFixedCrashOpenInventoryList()) { + if(CrashAPI.playerHasCrashGUIOpen(player)) { + if(crashManager.hasBetted(player) && !crashManager.getCashedAt().containsKey(player)) { + itemBuilder.setLore(Collections.singletonList("&aCashout: $" + moneyFormat.format(crashManager.getCurrentCrashX() * crashManager.getBets().get(player)))); + } + player.getOpenInventory().setItem(49, itemBuilder.colorize().build()); + player.updateInventory(); + } + } + + crashManager.getBets().entrySet().removeIf(this::checkIfPlayerIsAtAutoPayout); + + } + + private boolean checkIfPlayerIsAtAutoPayout(Map.Entry playerDoubleEntry) { + Player player = playerDoubleEntry.getKey(); + GambleUser gamblePlayer = plugin.getGambleManager().getGambleUser(player.getUniqueId()); + if(crashManager.getCurrentCrashX() >= gamblePlayer.getCrashAutoPayout()) { + + + double moneyBetted = crashManager.getBets().get(player); + double cashedOutAmount = moneyBetted * gamblePlayer.getCrashAutoPayout(); + EconomyUtils.depositBalance(player, cashedOutAmount); + player.sendMessage(CC.translate("&6Crash &8| &eYou have cashed out for &a$" + moneyFormat.format(cashedOutAmount) + " &eusing auto payout")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 3.0F, 3.0F); + crashManager.getCashedAt().put(player, new Pair<>(gamblePlayer.getCrashAutoPayout(), moneyBetted)); + + List lore = new ArrayList<>(); + lore.add("&fBet: &a$" + moneyFormat.format(moneyBetted)); + lore.add("&fCashed Out: &a" + decimalFormat.format(gamblePlayer.getCrashAutoPayout()) + "x"); + lore.add("&fCashed Amount: &a$" + moneyFormat.format(cashedOutAmount)); + ItemBuilder cashedOutBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short) 5, + "&fPlayer: &a" + player.getName()); + cashedOutBuilder.setLore(lore); + cashedOutBuilder.setGlowing(); + + setPlayerCashedOutInGUI(player, cashedOutBuilder.colorize().build()); + + return true; + } + + return false; + } + + private void setPlayerCashedOutInGUI(Player player, ItemStack itemStack) { + CrashAPI.getFixedCrashOpenInventoryList().forEach(loopPlayer -> { + if(CrashAPI.playerHasCrashGUIOpen(loopPlayer)) { + Inventory inventory = loopPlayer.getOpenInventory().getTopInventory(); + for(int i = 0; i < 50; i++) { + if(inventory.getItem(i) == null || inventory.getItem(i).getType() == Material.AIR) continue; + String toLookIn = ChatColor.stripColor(inventory.getItem(i).getItemMeta().getDisplayName()); + if(!toLookIn.contains(":")) continue; + toLookIn = toLookIn.split(": ")[1]; + if(Objects.equals(toLookIn, player.getName())) { + inventory.setItem(i, itemStack); + loopPlayer.updateInventory(); + } + } + } + }); + } + + private void check(int[] checks) { + for(int check : checks) { + if(crashManager.getFinalCrashX() >= check) { + this.crashManager.getLastBigCrashes().put(check, 0); + } else { + this.crashManager.getLastBigCrashes().put(check, this.crashManager.getLastBigCrashes().get(check) + 1); + } + } + } + + private void addLast100XToGui() { + ItemBuilder lastX = new ItemBuilder(Material.DIAMOND, "&c&lRecent High Crashes"); + lastX.addLoreLine("&fThe following lines show the last time"); + lastX.addLoreLine("&feach crash multiplier has crashed at"); + for(int bigX : new int[] {5, 10, 25, 50, 100, 250, 500, 1000}) + lastX.addLoreLine(" &f" + moneyFormat.format(bigX) + "x: &c" + moneyFormat.format(this.crashManager.getLastBigCrashes().get(bigX)) + " &fGames ago"); + lastX.setGlowing(); + + CrashAPI.getFixedCrashOpenInventoryList().forEach(player -> { + player.getOpenInventory().setItem(8, lastX.colorize().build()); + player.updateInventory(); + }); + } + + private void setGameFinished() { + + check(new int[] {5, 10, 25, 50, 100, 250, 500, 1000}); + + plugin.getServer().getScheduler().cancelTask(this.crashTaskID); + plugin.getServer().getScheduler().runTaskLater(plugin, this::initializeGame, 20 * 6L); // 6 seconds + addLast100XToGui(); + setupCrashGame(); + //ifFinalCrashOver(10); + + crashManager.getRecentCrashes().add(crashManager.getFinalCrashX()); + if(crashManager.getRecentCrashes().size() >= 12) crashManager.getRecentCrashes().remove(0); + + this.crashManager.setActive(false); + crashedGUI(); + + } + + private void ifFinalCrashOver(int over) { + if(crashManager.getFinalCrashX() < over) return; + int playersEntered = 0; + int playersCashedOut = 0; + playersEntered += crashManager.getBets().size(); + playersEntered += crashManager.getCashedAt().size(); + playersCashedOut += crashManager.getCashedAt().size(); + + Bukkit.broadcastMessage(""); + Bukkit.broadcastMessage(CC.translate("&c&lCranked Crash &7&o(Game Seed: &f" + this.crashGameUUID.toString().split("-")[0] + "&7)")); + String lastCrash = crashManager.getFinalCrashX() > 100 ? " &8● &7Last Crash: &4" : " &8● &7Last Crash: &a"; + Bukkit.broadcastMessage(CC.translate( lastCrash + decimalFormat.format(crashManager.getFinalCrashX()) + "x")); + Bukkit.broadcastMessage(CC.translate(" &8● &7Entered: &c" + playersEntered)); + Bukkit.broadcastMessage(CC.translate(" &8● &7Cashed Out: &c" + playersCashedOut)); + Bukkit.broadcastMessage(""); + } + + private void crashedGUI() { + String crashStarName = "&c&lCRASH @ " + decimalFormat.format(crashManager.getFinalCrashX()) + "x"; + + ItemStack crashStar = new ItemBuilder(Material.BARRIER, + crashStarName, + "&7&oA new game will be starting soon...").colorize().build(); + + ItemBuilder itemBuilder = new ItemBuilder(Material.REDSTONE, + "&cLast 10 Crashes"); + for (int crashNumber = this.crashManager.getRecentCrashes().size(); crashNumber > 1; crashNumber--) { + double crash = this.crashManager.getRecentCrashes().get(crashNumber-1); + String line = crash > 1.98 ? "&fCrash #" + (crashNumber-1) + ": &a" + decimalFormat.format(crash) + "x" : "&fCrash #" + (crashNumber-1) + ": &c" + decimalFormat.format(crash) + "x"; + itemBuilder.addLoreLine(line); + } + + CrashAPI.getFixedCrashOpenInventoryList().forEach(player -> { + if(CrashAPI.playerHasCrashGUIOpen(player)) { + player.getOpenInventory().setItem(49, crashStar); + player.getOpenInventory().setItem(26, itemBuilder.colorize().build()); + int[] toEmptySlot = new int[]{10, 11, 12, 13, 14, 15, 16, + 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43}; + for(int emptySlot : toEmptySlot) { + player.getOpenInventory().setItem(emptySlot, null); + } + player.updateInventory(); + } + }); + CrashAPI.getFixedCrashOpenInventoryList().forEach(player -> { + crashManager.getBets().forEach((loopPlayer, loopBet) -> { + ItemBuilder testBuilder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) 3, + "&fPlayer: &a" + loopPlayer.getName(), + "&fBet: &a$" + moneyFormat.format(loopBet)).setSkullOwner(loopPlayer.getName()); + player.getOpenInventory().getTopInventory().addItem(testBuilder.colorize().build()); + player.updateInventory(); + }); + }); + } + + private void setupCrashGame() { + List crashPlayers = new ArrayList<>(); + crashManager.getCashedAt().forEach((player, pair) -> { + CrashPlayer crashPlayer = new CrashPlayer( + player.getUniqueId(), + pair.getRight(), + pair.getLeft(), + crashManager.getFinalCrashX()); + crashPlayers.add(crashPlayer); + + GambleUser gambleUser = plugin.getGambleManager().getGambleUser(player.getUniqueId()); + gambleUser.addCrashWin(crashPlayer.getWinnings() - crashPlayer.getMoney()); + }); + + crashManager.getBets().forEach((player, bet) -> { + CrashPlayer crashPlayer = new CrashPlayer(player.getUniqueId(), bet, null, crashManager.getFinalCrashX()); + crashPlayers.add(crashPlayer); + GambleUser gambleUser = plugin.getGambleManager().getGambleUser(player.getUniqueId()); + gambleUser.addCrashLoss(crashPlayer.getMoney()); + }); + + List crashGames = new ArrayList<>(); + CrashGame crashGame = new CrashGame(UUID.randomUUID(), crashPlayers, crashManager.getFinalCrashX()); + crashGames.add(crashGame); + this.crashGameUUID = crashGame.getCrashGameID(); + + crashPlayers.stream() + .filter(crashPlayer -> crashPlayer.getMoney() != null) + .map(CrashPlayer::getPlayerUUID) + .forEach(playerUUID -> { + + if(crashManager.getPlayerCrashGraphMap().containsKey(playerUUID)) { + if(!crashManager.getPlayerCrashGraphMap().get(playerUUID).getCrashGames().isEmpty()) { + crashManager.getPlayerCrashGraphMap().get(playerUUID).getCrashGames().add(crashGame); + return; + } + crashManager.getPlayerCrashGraphMap().get(playerUUID).setCrashGames(crashGames); + return; + } + crashManager.getPlayerCrashGraphMap().put(playerUUID, new CrashGraph(playerUUID, crashGames)); + }); + + crashManager.getBets().keySet().forEach(player -> { + if(CrashAPI.playerHasCrashGUIOpen(player)) { + player.closeInventory(); + } + + GambleUser gambleUser = plugin.getGambleManager().getGambleUser(player.getUniqueId()); + if(gambleUser.isCrashSound()) player.playSound(player.getLocation(), Sound.ITEM_BREAK, 4.0F, 4.0F); + TitleUtils.sendTitle(player, CC.translate("&c&lCRASHED @ " + decimalFormat.format(crashManager.getFinalCrashX()) + "x"), CC.translate("&7&oBetter luck next time..."), 1, 3, 1); + + }); + crashManager.getBets().clear(); + crashManager.getCashedAt().clear(); + + crashManager.getWaitingToJoinCrash().forEach((player, bet) -> { + if(player.isOnline()) { + if(EconomyUtils.hasBalance(player, bet)) { + + EconomyUtils.withdrawBalance(player, bet); + crashManager.getBets().put(player, bet); + crashManager.getLastBets().put(player, bet); + + player.sendMessage(CC.translate(CrashAPI.prefix + "&aYou have joined the crash game with $" + moneyFormat.format(bet))); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + } + }); + crashManager.getWaitingToJoinCrash().clear(); + } + + + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/data/GambleManager.java b/Gambling/src/main/java/net/crankedpvp/gambling/data/GambleManager.java new file mode 100644 index 0000000..6086da5 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/data/GambleManager.java @@ -0,0 +1,21 @@ +package net.crankedpvp.gambling.data; + +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; + +import java.util.UUID; + +public class GambleManager extends SaveLoadManager { + public GambleManager(GamblingPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "data/", GambleUser.class); + } + + public GambleUser getGambleUser(UUID uuid) { + if (!containsKey(uuid.toString())) { + GambleUser gambleUser = new GambleUser(uuid); + addToCache(gambleUser); + } + return getFromCache(uuid.toString()); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/data/GambleUser.java b/Gambling/src/main/java/net/crankedpvp/gambling/data/GambleUser.java new file mode 100644 index 0000000..8439bae --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/data/GambleUser.java @@ -0,0 +1,277 @@ +package net.crankedpvp.gambling.data; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.storageutils.utils.KeyToSave; + +import java.text.DecimalFormat; +import java.util.UUID; + +@Getter +@Setter +public class GambleUser implements KeyToSave { + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + + private UUID uuid; + + private int coinflipWins; + private long coinflipWinnings; + private int coinflipLosses; + private long coinflipLosings; + private long coinFlipTaxesPaid; + + private double jackpotWins; + private long jackpotWinnings; + private double jackpotTicketsPurchased; + + private int bombsWins; + private int bombsLosses; + private double bombsWinnings; + private double bombsLosings; + + private int minesWins; + private int minesLosses; + private double minesWinnings; + private double minesLosings; + + private int rouletteWins; + private int rouletteLosses; + private double rouletteWinnings; + private double rouletteLosings; + + private int towerWins; + private int towerLosses; + private double towerWinnings; + private double towerLosings; + + private int crashWins; + private int crashLosses; + private double crashWinnings; + private double crashLosings; + private double crashAutoPayout; + private boolean crashSound; + + + private double diceWager; + private double diceTargetMultiplier; + private transient double diceLastMulti; + private int diceWins; + private int diceLosses; + private double diceWinnings; + private double diceLosings; + + //private CrashGraph crashGraph; + + public GambleUser(UUID uuid) { + this.uuid = uuid; + + this.coinflipWins = 0; + this.coinflipWinnings = 0; + this.coinflipLosses = 0; + this.coinflipLosings = 0; + + this.minesWins = 0; + this.minesWinnings = 0; + this.minesLosings = 0; + this.minesLosses = 0; + + this.towerWins = 0; + this.towerWinnings = 0; + this.towerLosings = 0; + this.towerLosses = 0; + + + this.bombsWins = 0; + this.bombsWinnings = 0; + this.bombsLosings = 0; + this.bombsLosses = 0; + + this.crashWins = 0; + this.crashWinnings = 0; + this.crashLosings = 0; + this.crashLosses = 0; + this.crashAutoPayout = 2; + this.crashSound = true; + + this.diceWins = 0; + this.diceWinnings = 0; + this.diceLosings = 0; + this.diceLosses = 0; + this.diceWager = 100; + this.diceTargetMultiplier = 2; + this.diceLastMulti = 1; + + this.rouletteWins = 0; + this.rouletteWinnings = 0; + this.rouletteLosings = 0; + this.rouletteLosses = 0; + + this.jackpotTicketsPurchased = 0; + this.jackpotWinnings = 0; + this.jackpotWins = 0; + //this.crashGraph = new CrashGraph(uuid, new ArrayList<>()); + } + + + public void addJackpotWin(double amountWon) { + this.jackpotWins++; + this.jackpotWinnings+=amountWon; + } + + public void addJackpotTickets(int tickets) { + this.jackpotTicketsPurchased+=tickets; + } + + public void addCoinflipWin(double amountWon) { + this.coinflipWins++; + this.coinflipWinnings+=amountWon; + } + + public void addCoinflipLoss(double amountLost) { + this.coinflipLosses++; + this.coinflipLosings+=amountLost; + } + + public String getCoinflipWinLossRatio(String delimeter) { + return getCoinflipWins() + delimeter + getCoinflipLosses(); + } + + + + + public void addBombsWin(double amountWon) { + this.bombsWins++; + this.bombsWinnings +=amountWon; + GamblingPlugin.getInstance().setOverallBombsWinnings(Math.round(GamblingPlugin.getInstance().getOverallBombsWinnings() + amountWon)); + } + + public void addBombsLoss(double amountLost) { + this.bombsLosses++; + this.bombsLosings +=amountLost; + GamblingPlugin.getInstance().setOverallBombsLosings(Math.round(GamblingPlugin.getInstance().getOverallBombsLosings() + amountLost)); + } + + public String getBombsWinLossRatio(String delimeter) { + return this.getBombsWins() + delimeter + this.getBombsLosses(); + } + + + + + + + public void addTowerWin(double amountWon) { + this.towerWins++; + this.towerWinnings +=amountWon; + GamblingPlugin.getInstance().setOverallTowerWinnings(Math.round(GamblingPlugin.getInstance().getOverallTowerWinnings() + amountWon)); + } + + public void addTowerLoss(double amountLost) { + this.towerLosses++; + this.towerLosings +=amountLost; + GamblingPlugin.getInstance().setOverallTowerLosings(Math.round(GamblingPlugin.getInstance().getOverallTowerLosings() + amountLost)); + } + + public String getTowerWinLossRatio(String delimeter) { + return this.getTowerWins() + delimeter + this.getTowerLosses(); + } + + + + + + + + public void addMinesWin(double amountWon) { + this.minesWins++; + this.minesWinnings +=amountWon; + GamblingPlugin.getInstance().setOverallMinesWinnings(Math.round(GamblingPlugin.getInstance().getOverallMinesWinnings() + amountWon)); + } + + public void addMinesLoss(double amountLost) { + this.minesLosses++; + this.minesLosings +=amountLost; + GamblingPlugin.getInstance().setOverallMinesLosings(Math.round(GamblingPlugin.getInstance().getOverallMinesLosings() + amountLost)); + } + + public String getMinesWinLossRatio(String delimeter) { + return this.getMinesWins() + delimeter + this.getMinesLosses(); + } + + + + public void setCrashAutoPayout(double payout) { + this.crashAutoPayout = payout; + } + + public void addCrashWin(double amountWon) { + this.crashWins++; + this.crashWinnings += amountWon; + GamblingPlugin.getInstance().setOverallCrashWinnings(Math.round(GamblingPlugin.getInstance().getOverallCrashWinnings() + amountWon)); + } + + public void addCrashLoss(double amountLost) { + this.crashLosses++; + this.crashLosings += amountLost; + GamblingPlugin.getInstance().setOverallCrashLosings(Math.round(GamblingPlugin.getInstance().getOverallCrashLosings() + amountLost)); + } + + public String getCrashWinLossRatio(String delimeter) { + return this.getCrashWins() + delimeter + this.getCrashLosses(); + } + + + + public void addDiceWin(double amountWon) { + this.diceWins++; + this.diceWinnings += amountWon; + GamblingPlugin.getInstance().setOverallCrashWinnings(Math.round(GamblingPlugin.getInstance().getOverallCrashWinnings() + amountWon)); + } + + public void addDiceLoss(double amountLost) { + this.diceLosses++; + this.diceLosings += amountLost; + GamblingPlugin.getInstance().setOverallCrashLosings(Math.round(GamblingPlugin.getInstance().getOverallCrashLosings() + amountLost)); + } + + public String getLastMultiAsString() { + return decimalFormat.format(this.getDiceLastMulti()) + "x"; + } + + + public void addRouletteWin(double amountWon) { + this.rouletteWins++; + this.rouletteWinnings += amountWon; + } + + public void addRouletteLoss(double amountLost) { + this.rouletteLosses++; + this.rouletteLosings += amountLost; + } + + public String getRouletteWinLossRatio(String delimeter) { + return this.getRouletteWins() + delimeter + this.getRouletteLosses(); + } + + + + + + + public void addCoinflipTax(double tax) { + this.coinFlipTaxesPaid+=tax; + } + + @Override + public String getKey() { + return uuid.toString(); + } + + @Override + public void setKey(String s) { + this.uuid = UUID.fromString(s); + } + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/dice/DiceAPI.java b/Gambling/src/main/java/net/crankedpvp/gambling/dice/DiceAPI.java new file mode 100644 index 0000000..60db971 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/dice/DiceAPI.java @@ -0,0 +1,5 @@ +package net.crankedpvp.gambling.dice; + +public class DiceAPI { + public static final String prefix = "&b&lDICE &8➥ "; +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/dice/commands/DiceCommand.java b/Gambling/src/main/java/net/crankedpvp/gambling/dice/commands/DiceCommand.java new file mode 100644 index 0000000..7c93124 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/dice/commands/DiceCommand.java @@ -0,0 +1,79 @@ +package net.crankedpvp.gambling.dice.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.crash.inventory.CrashStatsInventory; +import net.crankedpvp.gambling.dice.DiceAPI; +import net.crankedpvp.gambling.dice.inventory.DiceInventory; +import org.bukkit.OfflinePlayer; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.text.DecimalFormat; + +@Command("dice") +@Alias({"bustadice", "dices"}) +public class DiceCommand extends CommandBase { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final GamblingPlugin plugin; + public DiceCommand(GamblingPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender, @Optional Double bet) { + Player player = (Player)commandSender; + if(bet == null) { + DiceInventory diceInventory = new DiceInventory(player); + diceInventory.getUI().open(player); + return; + } + + DiceInventory diceInventory = new DiceInventory(player, bet); + diceInventory.getUI().open(player); + } + + @SubCommand("bet") + public void betCommand(CommandSender commandSender, Double bet) { + Player player = (Player)commandSender; + if(bet == null) { + DiceInventory diceInventory = new DiceInventory(player); + diceInventory.getUI().open(player); + return; + } + + DiceInventory diceInventory = new DiceInventory(player, bet); + diceInventory.getUI().open(player); + + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("target") + @Alias({"multi", "targetmultiplier", "setautopayout", "payout", "autopayout", "tm", "multiplier"}) + public void setAutoPayoutCommand(CommandSender commandSender, Double autoPayout) { + Player player = (Player) commandSender; + if(autoPayout < 1) { + player.sendMessage(CC.translate(DiceAPI.prefix + "&cYou cannot set your target multiplier below 1x")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + plugin.getGambleManager().getGambleUser(player.getUniqueId()).setDiceTargetMultiplier(autoPayout); + player.sendMessage(CC.translate(DiceAPI.prefix + "&7Your new target multiplier is: " + autoPayout)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @SubCommand("adminstats") + @Alias({"as", "adminstats"}) + @Permission("cranked.admin") + public void adminStatsCommand(CommandSender commandSender) { + commandSender.sendMessage("Overall Winnings: " + moneyFormat.format(this.plugin.getOverallDiceWinnings())); + commandSender.sendMessage("Overall Losings: " + moneyFormat.format(this.plugin.getOverallDiceLosings())); + commandSender.sendMessage("Overall Player Profit: " + moneyFormat.format(this.plugin.getOverallDiceWinnings() - this.plugin.getOverallDiceLosings())); + } + +} \ No newline at end of file diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/dice/inventory/DiceInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/dice/inventory/DiceInventory.java new file mode 100644 index 0000000..7258cf8 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/dice/inventory/DiceInventory.java @@ -0,0 +1,298 @@ +package net.crankedpvp.gambling.dice.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import net.crankedpvp.gambling.dice.DiceAPI; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.text.DecimalFormat; +import java.util.Arrays; +import java.util.concurrent.ThreadLocalRandom; + +public class DiceInventory { + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + @Setter @Getter + private long lastBet = System.currentTimeMillis(); + + private final Player player; + private final GambleUser gambleUser; + + @Getter @Setter + private double diceMultiplier; + + private final Gui diceInventory; + + public Gui getUI() { + return this.diceInventory; + } + + public DiceInventory(Player player) { + this.player = player; + this.diceInventory = new Gui(3, "Cranked Dice"); + this.diceInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + + this.gambleUser.setDiceWager(0); + this.setupInventory(); + } + + public DiceInventory(Player player, double bet) { + this.player = player; + this.diceInventory = new Gui(3, "Cranked Dice"); + this.diceInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + + this.gambleUser.setDiceWager(bet); + this.setupInventory(); + } + + private void setupInventory() { + this.addInformationButton(); + this.addMainButton(); + this.addWagerButton(); + this.addTargetMultiplierButton(); + this.addDoubleBetButton(); + this.addHalfBetButton(); + this.updateMaxBetButton(); + this.setSurroundingPanes((short) 15); + } + + private void addInformationButton() { + ItemStack itemStack = new ItemBuilder(Material.SIGN, "&b&lDice Information", + "&bDice &7is a game of luck that involves", + "&7setting a &eTarget Multiplier &7and a", + "&bWager&7. Your wager is the amount of money", + "&7you are betting in each turn. Your target", + "&7multiplier is the amount you intend to", + "&7multiply your money by", + "", + "&7To set your &eTarget Multiplier&7, simply", + "&7type &f/dice target &7. For", + "&7example you could set your target to 4x", + "&fvia &f/dice target 4", + "", + "&7To set your &bWager&7, you similarly do", + "&f/dice &7, e.g &f/dice 5000", + "&7Meaning that each bet will now cost $5,000", + "", + "&7To play, set your desired wager and target", + "&7multiplier, then click the BET button in", + "&7the middle of the inventory.", + "", + "&7Red surrounding glass panes means you have", + "&c&lLOST&7, whereas green glass panes means", + "&7that you have &a&lWON&7. Best of luck!").colorize().build(); + this.diceInventory.setItem(2, 1, new GuiItem(itemStack)); + } + + private void addWagerButton() { + ItemStack itemStack = new ItemBuilder(Material.PAPER, "&b&lWAGER", "&fCurrent Wager: &b$" + moneyFormat.format(this.gambleUser.getDiceWager()), "", "&e&lTIP &fUse /dice to edit your wager").colorize().build(); + this.diceInventory.setItem(1, 1, new GuiItem(itemStack)); + } + + private void updateWagerButton() { + ItemStack itemStack = new ItemBuilder(Material.PAPER, "&b&lWAGER", "&fCurrent Wager: &b$" + moneyFormat.format(this.gambleUser.getDiceWager()), "", "&e&lTIP &fUse /dice to edit your wager").colorize().build(); + this.diceInventory.updateItem(1, 1, new GuiItem(itemStack)); + } + + private void addTargetMultiplierButton() { + ItemStack itemStack = new ItemBuilder(Material.DOUBLE_PLANT, "&e&lMULTIPLIER", "&fCurrent Target Multiplier: &e" + decimalFormat.format(this.gambleUser.getDiceTargetMultiplier()) + "x", "", "&e&lTIP &fUse /dice target to edit your target").colorize().build(); + this.diceInventory.setItem(3, 1, new GuiItem(itemStack)); + } + + private void reAddBetModifierButtons() { + this.addDoubleBetButton(); + this.addHalfBetButton(); + } + + private void addDoubleBetButton() { + ItemStack itemStack = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short)5, "&a&lDOUBLE WAGER", "&f$" + moneyFormat.format(this.gambleUser.getDiceWager() * 2)).colorize().build(); + this.diceInventory.updateItem(1, 9, new GuiItem(itemStack, event -> { + double doubledWager = this.gambleUser.getDiceWager() * 2; + if(!EconomyUtils.hasBalance(player, doubledWager)) { + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + player.sendMessage(CC.translate(DiceAPI.prefix + "&cYou cannot afford this wager")); + return; + } + + this.gambleUser.setDiceWager(doubledWager); + this.updateWagerButton(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0f, 2.0f); + player.sendMessage(CC.translate(DiceAPI.prefix + "&aYou have doubled your wager")); + + this.reAddBetModifierButtons(); + })); + } + + private void addHalfBetButton() { + ItemStack itemStack = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short)14, "&c&lHALF WAGER", "&f$" + moneyFormat.format(this.gambleUser.getDiceWager() / 2)).colorize().build(); + this.diceInventory.updateItem(3, 9, new GuiItem(itemStack, event -> { + double halvedWager = this.gambleUser.getDiceWager() / 2; + if(halvedWager < 1) { + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + player.sendMessage(CC.translate(DiceAPI.prefix + "&cYou cannot wager lower than $1")); + return; + } + + this.gambleUser.setDiceWager(halvedWager); + this.updateWagerButton(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0f, 2.0f); + player.sendMessage(CC.translate(DiceAPI.prefix + "&aYou have halved your wager")); + + this.reAddBetModifierButtons(); + })); + } + + private void updateMaxBetButton() { + ItemStack itemStack = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short)2, "&d&lMAX WAGER", "&f$" + moneyFormat.format(EconomyUtils.getBalance(this.player))).colorize().build(); + this.diceInventory.updateItem(2, 9, new GuiItem(itemStack, event -> { + this.gambleUser.setDiceWager(EconomyUtils.getBalance(player)); + this.updateWagerButton(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0f, 2.0f); + player.sendMessage(CC.translate(DiceAPI.prefix + "&aYou are now wagering all of your money")); + this.reAddBetModifierButtons(); + })); + } + + + private void addMainButton() { + String colour = this.gambleUser.getDiceTargetMultiplier() <= this.getDiceMultiplier() ? "&a&lBET" : "&c&lBET"; + Material material = this.gambleUser.getDiceTargetMultiplier() <= this.getDiceMultiplier() ? Material.SLIME_BALL : Material.FIREBALL; + ItemStack itemStack = new ItemBuilder(material, colour, "&fLast Multi: " + this.gambleUser.getLastMultiAsString()).colorize().build(); + this.diceInventory.updateItem(2, 5, new GuiItem(itemStack, event -> { + + if(this.getLastBet() + 500 > System.currentTimeMillis()) { + this.setLastBet(System.currentTimeMillis()); + player.sendMessage(CC.translate(DiceAPI.prefix + "&cPlease do not spam bet")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + return; + } + if(!EconomyUtils.hasBalance(player, this.gambleUser.getDiceWager())) { + player.sendMessage(CC.translate(DiceAPI.prefix + "&cYou cannot afford this wager")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0f, 2.0f); + event.setCancelled(true); + return; + } + + EconomyUtils.withdrawBalance(player, this.gambleUser.getDiceWager()); + if(this.gambleUser.getDiceTargetMultiplier() <= this.getRandomMulti()) { + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0f, 2.0f); + EconomyUtils.depositBalance(player, this.gambleUser.getDiceWager() * this.gambleUser.getDiceTargetMultiplier()); + this.setSurroundingPanes((short) 5); + this.gambleUser.addDiceWin(this.gambleUser.getDiceWager() * this.gambleUser.getDiceTargetMultiplier()); + } else { + player.playSound(player.getLocation(), Sound.FIZZ, 2.0f, 2.0f); + this.setSurroundingPanes((short) 14); + this.gambleUser.addDiceLoss(this.gambleUser.getDiceWager()); + } + this.updateMaxBetButton(); + this.addMainButton(); + })); + } + + public double getRandomMulti() { + this.generateAndSetRandomMultiplier(); + this.gambleUser.setDiceLastMulti(this.getDiceMultiplier()); + return this.getDiceMultiplier(); + } + + public void generateAndSetRandomMultiplier() { + if(Math.random() > 0.97) { + this.setDiceMultiplier(1.0D); + return; + } + + if(Math.random() > 0.9997) { + this.setDiceMultiplier(ThreadLocalRandom.current().nextDouble(351, 1250)); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 90) { + this.setDiceMultiplier(1 + (Math.random() / 3)); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 50) { + this.setDiceMultiplier(1 + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 50) { + this.setDiceMultiplier(2 + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 45) { + this.setDiceMultiplier(3 + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 40) { + this.setDiceMultiplier(ThreadLocalRandom.current().nextDouble(4, 7)); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 35) { + this.setDiceMultiplier(ThreadLocalRandom.current().nextDouble(8, 17)); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 30) { + this.setDiceMultiplier(ThreadLocalRandom.current().nextDouble(18, 41) + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 25) { + this.setDiceMultiplier(ThreadLocalRandom.current().nextDouble(42, 101) + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 20) { + this.setDiceMultiplier(ThreadLocalRandom.current().nextDouble(102, 254) + Math.random()); + return; + } + + if(ThreadLocalRandom.current().nextInt(100) > 15) { + this.setDiceMultiplier(ThreadLocalRandom.current().nextDouble(255, 498) + Math.random()); + return; + } + + this.setDiceMultiplier(ThreadLocalRandom.current().nextInt(499, 1250) + Math.random()); + } + + private void setSurroundingPanes(short colour) { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, colour); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("")); + item.setItemMeta(meta); + for(int num : Arrays.asList(4, 12, 14, 22)) { + this.diceInventory.updateItem(num, new GuiItem(item)); + } + } + + + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate(" ")); + item.setItemMeta(meta); + return item; + } + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/commands/CommandJackpot.java b/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/commands/CommandJackpot.java new file mode 100644 index 0000000..220652a --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/commands/CommandJackpot.java @@ -0,0 +1,114 @@ + +package net.crankedpvp.gambling.jackpot.commands; + +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import net.crankedpvp.gambling.jackpot.struct.Jackpot; +import net.crankedpvp.gambling.jackpot.struct.JackpotManager; +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.metadata.FixedMetadataValue; + +public class CommandJackpot + implements CommandExecutor { + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + JackpotManager manager = GamblingPlugin.getInstance().getJackpotManager(); + if (args.length == 0) { + Jackpot current = GamblingPlugin.getInstance().getJackpotManager().getCurrentJackpot(); + if (current == null) { + sender.sendMessage(ChatColor.RED + "It seems there is no jackpot currently running!"); + return true; + } + sender.sendMessage(""); + sender.sendMessage(ChatColor.DARK_RED + ChatColor.BOLD.toString() + "Cranked Jackpot"); + sender.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + " Jackpot Value: " + ChatColor.DARK_RED + ChatColor.BOLD + "$" + ChatColor.DARK_RED + manager.getMoneyFormat().format(current.getPlayerWinnings()) + ChatColor.GRAY + " (-" + (int) (Jackpot.TAX * 100.0) + "% tax)"); + sender.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + " Tickets Sold: " + ChatColor.YELLOW + manager.getMoneyFormat().format(current.getTicketsSold())); + sender.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + " Your Tickets: " + ChatColor.GREEN + current.getTicketsPurchased((Player) sender) + ChatColor.GRAY + " (" + manager.getMoneyFormat().format(current.getPercentHolder((Player) sender)) + "%)"); + sender.sendMessage(""); + sender.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + "(!) " + ChatColor.RED + "Next Winner in " + ChatColor.RED + ChatColor.UNDERLINE + TimeUtils.formatSeconds(current.getSecondsLeft())); + sender.sendMessage(""); + return true; + } + if ((args.length == 2 || args.length == 1) && args[0].equalsIgnoreCase("buy")) { + Jackpot current = manager.getCurrentJackpot(); + if (args[0].equalsIgnoreCase("buy")) { + String arg; + Player player = (Player) sender; + arg = args.length == 2 ? args[1] : "1"; + if (!StringUtils.isNumeric(arg)) { + sender.sendMessage(ChatColor.RED + "Please enter a valid amount of tickets to purchase!"); + return true; + } + int tickets = Integer.parseInt(arg); + if (tickets < 1 || tickets > 1000000) { + sender.sendMessage(ChatColor.RED + "Please enter a ticket amount between 0 and 1,000,000!"); + return true; + } + double totalPrice = tickets * current.getTicketPrice(); + if (EconomyUtils.getBalance(player) < totalPrice) { + sender.sendMessage(ChatColor.RED + "You cannot afford the total price of $" + manager.getMoneyFormat().format(totalPrice) + " for " + tickets + " tickets!"); + return true; + } + sender.sendMessage(""); + sender.sendMessage(ChatColor.GREEN + "Confirm purchase of " + ChatColor.AQUA + ChatColor.BOLD + ChatColor.UNDERLINE + tickets + ChatColor.GREEN + " Jackpot Ticket(s)"); + sender.sendMessage(ChatColor.GREEN + "for " + ChatColor.AQUA + ChatColor.BOLD + "$" + ChatColor.AQUA + manager.getMoneyFormat().format(totalPrice) + (tickets > 1 ? ChatColor.GREEN + " at " + ChatColor.AQUA + ChatColor.BOLD + "$" + ChatColor.AQUA + manager.getMoneyFormat().format(current.getTicketPrice()) + "/ea" : "!")); + sender.sendMessage(""); + player.setMetadata("jackpotTicket", new FixedMetadataValue(GamblingPlugin.getInstance(), tickets)); + player.openInventory(manager.getJackpotConfirmMenu(tickets, totalPrice)); + return true; + } + + } + if (args[0].equalsIgnoreCase("draw") && sender.isOp()) { + sender.sendMessage(ChatColor.RED + "Forcing Jackpot winner!"); + manager.drawWinner(); + return true; + } + if (args[0].equalsIgnoreCase("count") && sender.isOp()) { + sender.sendMessage(ChatColor.RED + "Forcing countdown."); + manager.getCurrentJackpot().setSecondsLeft(61); + return true; + } + if (args[0].equalsIgnoreCase("stats")) { + Player pl = (Player) sender; + GambleUser history = GamblingPlugin.getInstance().getGambleManager().getGambleUser(pl.getUniqueId()); + sender.sendMessage(""); + sender.sendMessage(ChatColor.DARK_RED + ChatColor.BOLD.toString() + "Cranked Jackpot Stats"); + String moneyString = ChatColor.LIGHT_PURPLE.toString() + ChatColor.BOLD + "$" + ChatColor.DARK_RED + "%s"; + sender.sendMessage(ChatColor.RED + "Total Winnings: " + String.format(moneyString, manager.getMoneyFormat().format(history.getJackpotWinnings()))); + sender.sendMessage(ChatColor.RED + "Total Tickets Purchased: " + ChatColor.DARK_RED + manager.getMoneyFormat().format(history.getJackpotTicketsPurchased())); + sender.sendMessage(ChatColor.RED + "Total Jackpot Wins: " + ChatColor.DARK_RED + manager.getMoneyFormat().format(history.getJackpotWins())); + sender.sendMessage(""); + return true; + } + if (args[0].equalsIgnoreCase("toggle") || args[0].equalsIgnoreCase("notifications") || args[0].equalsIgnoreCase("stfu")) { + //toggle messages + return true; + + } + + sender.sendMessage(""); + sender.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + "Jackpot Commands"); + sender.sendMessage(ChatColor.WHITE + "/jackpot"); + sender.sendMessage(ChatColor.GRAY + "View current Jackpot information."); + sender.sendMessage(""); + sender.sendMessage(ChatColor.WHITE + "/jackpot buy "); + sender.sendMessage(ChatColor.GRAY + "Buy X tickets for the current Jackpot."); + sender.sendMessage(""); + sender.sendMessage(ChatColor.WHITE + "/jackpot stats"); + sender.sendMessage(ChatColor.GRAY + "View your Jackpot stats!"); + sender.sendMessage(""); + sender.sendMessage(ChatColor.WHITE + "/jackpot notifications"); + sender.sendMessage(ChatColor.GRAY + "Toggle Jackpot countdown notifications!"); + sender.sendMessage(""); + return false; + } +} + + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/listeners/JackpotListener.java b/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/listeners/JackpotListener.java new file mode 100644 index 0000000..9906aa6 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/listeners/JackpotListener.java @@ -0,0 +1,125 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.cosmicpvp.cosmicutils.CosmicUtils + * com.cosmicpvp.cosmicutils.customevents.CustomCosmicPlayerEvent + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.CC + * com.cosmicpvp.cosmicutils.me.astropvp.cratekeys.net.astropvp.armorsets.utils.HCFOutpostUtils + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.DyeColor + * org.bukkit.Material + * org.bukkit.OfflinePlayer + * org.bukkit.Sound + * org.bukkit.command.CommandSender + * org.bukkit.entity.Player + * org.bukkit.event.Event + * org.bukkit.event.Event$Result + * org.bukkit.event.EventHandler + * org.bukkit.event.EventPriority + * org.bukkit.event.Listener + * org.bukkit.event.me.astropvp.cratekeys.inventory.InventoryClickEvent + * org.bukkit.event.player.AsyncPlayerChatEvent + * org.bukkit.event.player.PlayerQuitEvent + * org.bukkit.me.astropvp.cratekeys.inventory.ItemStack + * org.bukkit.metadata.MetadataValue + * org.bukkit.plugin.Plugin + */ +package net.crankedpvp.gambling.jackpot.listeners; + + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import net.crankedpvp.gambling.jackpot.struct.Jackpot; +import net.crankedpvp.gambling.jackpot.struct.JackpotManager; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; + +public class JackpotListener +implements Listener { + @EventHandler + public void onPlayerLeave(PlayerQuitEvent event) { + event.getPlayer().removeMetadata("jackpotTicket", GamblingPlugin.getInstance()); + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + if (event.getInventory().getName().equalsIgnoreCase("Confirm Ticket Purchase")) { + event.setCancelled(true); + event.setResult(Event.Result.DENY); + ItemStack clicked = event.getCurrentItem(); + if (clicked == null || clicked.getType() != Material.STAINED_GLASS_PANE) { + return; + } + Player player = (Player)event.getWhoClicked(); + if (!player.hasMetadata("jackpotTicket") || player.getMetadata("jackpotTicket").size() <= 0) { + player.closeInventory(); + return; + } + int ticketsToPurchase = player.getMetadata("jackpotTicket").get(0).asInt(); + player.removeMetadata("jackpotTicket", GamblingPlugin.getInstance()); + short data = clicked.getData().getData(); + if (data == DyeColor.LIME.getWoolData()) { + player.closeInventory(); + this.confirmPurchase(player, ticketsToPurchase); + } else if (data == DyeColor.RED.getWoolData()) { + player.closeInventory(); + player.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + "(!) " + ChatColor.RED + "Jackpot Ticket Purchase cancelled."); + } + } + } + + @EventHandler(priority=EventPriority.LOWEST) + public void onPlayerTalk(AsyncPlayerChatEvent event) { + Player player = event.getPlayer(); + if (player.hasMetadata("jackpotTicket") && player.getMetadata("jackpotTicket").size() > 0) { + int ticketsToPurchase = player.getMetadata("jackpotTicket").get(0).asInt(); + player.removeMetadata("jackpotTicket", GamblingPlugin.getInstance()); + if (ticketsToPurchase < 0) { + return; + } + event.setCancelled(true); + if (!ChatColor.stripColor(event.getMessage()).equalsIgnoreCase("confirm")) { + player.sendMessage(ChatColor.RED + ChatColor.BOLD.toString() + "(!) " + ChatColor.RED + "Jackpot Ticket Purchase cancelled."); + return; + } + event.setMessage(""); + this.confirmPurchase(player, ticketsToPurchase); + } + } + + private void confirmPurchase(Player player, int ticketsToPurchase) { + JackpotManager manager = GamblingPlugin.getInstance().getJackpotManager(); + Jackpot current = manager.getCurrentJackpot(); + double price = ticketsToPurchase * current.getTicketPrice(); + if (EconomyUtils.getBalance(player) < price) { + player.sendMessage(ChatColor.RED + "You no longer have $" + manager.getMoneyFormat().format(price) + " required to purchase " + ticketsToPurchase + " tickets!"); + return; + } + int adjustedTickets = ticketsToPurchase; + + current.purchaseTicket(player, ticketsToPurchase, adjustedTickets); + player.sendMessage(ChatColor.GREEN + "You have purchased " + ticketsToPurchase + " ticket" + (ticketsToPurchase > 1 ? "s" : "") + " for " + ChatColor.GREEN + ChatColor.BOLD.toString() + "$" + ChatColor.GREEN + manager.getMoneyFormat().format(price) + "!"); + if (adjustedTickets != ticketsToPurchase) { + player.sendMessage(CC.Green + "You have received " + CC.GreenB + (adjustedTickets - ticketsToPurchase) + CC.Green + " bonus ticket(s)! " + CC.GreenB + "(SRC: " + CC.Green + "Frozen Stronghold" + CC.GreenB + ")"); + player.sendMessage(""); + } + player.sendMessage(ChatColor.GRAY + "Use " + ChatColor.GRAY + ChatColor.UNDERLINE.toString() + "/jackpot" + ChatColor.GRAY + " to view current Jackpot information!"); + player.sendMessage(""); + player.playSound(player.getLocation(), Sound.LEVEL_UP, 1.0f, 1.4f); + GambleUser history = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + history.addJackpotTickets(ticketsToPurchase); + } +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/struct/Jackpot.java b/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/struct/Jackpot.java new file mode 100644 index 0000000..efb2d89 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/struct/Jackpot.java @@ -0,0 +1,120 @@ +/* + * Decompiled with CFR 0.150. + * + * Could not load the following classes: + * com.google.common.collect.Lists + * net.milkbowl.vault.economy.EconomyResponse + * org.bukkit.Bukkit + * org.bukkit.OfflinePlayer + * org.bukkit.entity.Player + */ +package net.crankedpvp.gambling.jackpot.struct; + +import com.google.common.collect.Lists; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.milkbowl.vault.economy.EconomyResponse; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; + +@Getter +@Setter +public class Jackpot { + public static transient double TAX = 0.1; + private Map entries = new ConcurrentHashMap<>(); + private long totalWinnings = 1; + private int secondsLeft; + + public String toString() { + return this.totalWinnings + " - " + this.secondsLeft + " " + this.entries.size() + " entries."; + } + + public Jackpot(int timer) { + this.secondsLeft = timer; + } + + public void purchaseTicket(Player player, int tickets, int adjustedTickets) { + double cost = tickets * this.getTicketPrice(); + EconomyResponse removed = EconomyUtils.getEconomy().withdrawPlayer(player, cost); + if (!removed.transactionSuccess()) { + Bukkit.getLogger().info("Transaction not successful for " + player.getName() + " for $" + cost + " with " + tickets + " tickets purchased!"); + return; + } + UUID uuid = player.getUniqueId(); + Integer current = this.entries.get(uuid); + Bukkit.getLogger().info("(CrankedJackpot) Purchasing " + tickets + " ticket(s) for " + player.getName() + (current != null ? " with " + current + " current total." : "0 current") + " adjusted=" + adjustedTickets); + if (adjustedTickets != tickets) { + tickets = adjustedTickets; + } + this.entries.put(uuid, (current == null ? 0 : current) + tickets); + this.totalWinnings = (long)((double)this.totalWinnings + cost); + } + + public double getPercentHolder(Player player) { + return this.getPercentHolder(player.getUniqueId()); + } + + public double getPercentHolder(UUID uuid) { + int ticketsOwned = this.getTicketsPurchased(uuid); + if (ticketsOwned <= 0) { + return 0.0; + } + int totalTickets = this.getTicketsSold(); + if (totalTickets <= 0) { + return 0.0; + } + return (double)ticketsOwned / (double)totalTickets * 100.0; + } + + public int getTicketsPurchased(Player player) { + return this.getTicketsPurchased(player.getUniqueId()); + } + + public int getTicketsPurchased(UUID uuid) { + int found = 0; + for (Map.Entry entries : this.entries.entrySet()) { + if (!entries.getKey().equals(uuid)) continue; + found += entries.getValue(); + } + return found; + } + + public int getTicketPrice() { + return 10000; + } + + public int getTicketsSold() { + int total = 0; + for (Integer val : this.entries.values()) { + total += val; + } + return total; + } + + public long getPlayerWinnings() { + long taxes = (long)((double)this.totalWinnings * TAX); + return this.totalWinnings - taxes; + } + + public UUID getRandomWinner() { + if (this.entries.isEmpty()) { + return null; + } + List winnerPool = Lists.newArrayList(); + this.entries.forEach((info, values) -> { + for (int i = 0; i < values; ++i) { + winnerPool.add(info); + } + }); + Collections.shuffle(winnerPool); + return winnerPool.get(ThreadLocalRandom.current().nextInt(winnerPool.size())); + } + + +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/struct/JackpotManager.java b/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/struct/JackpotManager.java new file mode 100644 index 0000000..db42064 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/jackpot/struct/JackpotManager.java @@ -0,0 +1,102 @@ + +package net.crankedpvp.gambling.jackpot.struct; + + +import com.google.common.collect.Lists; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Map; +import java.util.UUID; + +@Getter +@Setter +public class JackpotManager { + private final DecimalFormat moneyFormat = new DecimalFormat("#,###.##"); + private Jackpot currentJackpot; + private Map jackpotHistory; + private int defaultDrawTime = 1800; + private LinkedList sortedHistory = new LinkedList<>(); + private long lastListUpdate; + + + public void onJackpotTick() { + int secondsLeft = this.currentJackpot.getSecondsLeft(); + if (secondsLeft > 0) { + if (secondsLeft == 300 || secondsLeft == 60 || secondsLeft == 30 || secondsLeft == 10 || secondsLeft <= 5 && secondsLeft > 0) { + for (Player pl : Bukkit.getOnlinePlayers()) { + //if (this.toggledNofications.contains(pl.getUniqueId())) continue; + + pl.sendMessage(""); + pl.sendMessage(StringUtils.getCenteredMessage(CC.translate("&6&lJackpot"))); + pl.sendMessage(StringUtils.getCenteredMessage(CC.translate("&fTime Remaining&7: &6" + (secondsLeft == 60 ? "60s" : TimeUtils.formatSeconds(secondsLeft).trim())))); + pl.sendMessage(StringUtils.getCenteredMessage(CC.translate("&fTotal Value&7: &a$" + this.getMoneyFormat().format(this.currentJackpot.getPlayerWinnings())))); + pl.sendMessage(StringUtils.getCenteredMessage(CC.translate("&7&o(( &f&o/jackpot buy (amount)&7&o to purchase tickets ))"))); + pl.sendMessage(""); + + } + } + this.currentJackpot.setSecondsLeft(secondsLeft - 1); + } else { + this.drawWinner(); + } + } + + public void drawWinner() { + UUID winner = this.currentJackpot.getRandomWinner(); + if (winner == null) { + Bukkit.broadcastMessage(ChatColor.RED.toString() + ChatColor.BOLD + "(!) " + ChatColor.RED + "No Jackpot winner available due to no ticket sales!"); + this.startNewJackpot(); + return; + } + Bukkit.broadcastMessage(""); + Bukkit.broadcastMessage(ChatColor.GREEN + ChatColor.BOLD.toString() + "(!) " + Bukkit.getOfflinePlayer(winner).getName() + ChatColor.GREEN + " has won the " + ChatColor.GREEN + ChatColor.UNDERLINE + "/jackpot" + ChatColor.GREEN + " and received "); + Bukkit.broadcastMessage(ChatColor.DARK_GREEN + ChatColor.BOLD.toString() + "$" + ChatColor.DARK_GREEN + this.moneyFormat.format(this.currentJackpot.getPlayerWinnings()) + ChatColor.GREEN + "! They purchased " + ChatColor.GREEN + this.moneyFormat.format(this.currentJackpot.getTicketsPurchased(winner)) + ChatColor.GREEN + " (" + this.moneyFormat.format(this.currentJackpot.getPercentHolder(winner)) + "%) ticket(s) out of the "); + Bukkit.broadcastMessage(ChatColor.GREEN.toString() + this.moneyFormat.format(this.currentJackpot.getTicketsSold()) + ChatColor.GREEN + " ticket(s) sold!"); + Bukkit.broadcastMessage(""); + + double winnings = this.currentJackpot.getPlayerWinnings(); + this.startNewJackpot(); + + OfflinePlayer pl = Bukkit.getOfflinePlayer(winner); + EconomyUtils.depositBalance(pl, winnings); + GamblingPlugin.getInstance().getGambleManager().getGambleUser(winner).addJackpotWin(winnings); + + } + + public Inventory getJackpotConfirmMenu(int ticketsToBuy, double totalCost) { + Inventory inv = Bukkit.createInventory(null, 9, "Confirm Ticket Purchase"); + for (int i = 5; i < 9; ++i) { + inv.setItem(i, new ItemBuilder(Material.STAINED_GLASS_PANE,1, DyeColor.RED.getWoolData()).setName(ChatColor.RED + ChatColor.BOLD.toString() + "Cancel Purchase").setLore(Lists.newArrayList(ChatColor.GRAY + "Click to " + ChatColor.RED + "cancel" + ChatColor.GRAY + " ticket purchase.")).build()); + } + ArrayList lore = Lists.newArrayList(ChatColor.GRAY + "Click to " + ChatColor.GREEN + "confirm" + ChatColor.GRAY + " purchase of", ChatColor.GREEN + this.moneyFormat.format(ticketsToBuy) + ChatColor.GRAY + " ticket(s) for " + ChatColor.GREEN + ChatColor.BOLD + "$" + ChatColor.GREEN + this.moneyFormat.format(totalCost)); + if (ticketsToBuy > 1) { + lore.add(ChatColor.GRAY + "at " + ChatColor.GREEN + ChatColor.BOLD.toString() + "$" + ChatColor.GREEN + this.moneyFormat.format(this.currentJackpot.getTicketPrice()) + "/ea"); + } + for (int i = 0; i < 4; ++i) { + inv.setItem(i, new ItemBuilder(Material.STAINED_GLASS_PANE,1, DyeColor.LIME.getWoolData()).setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Confirm Purchase").setLore(lore).build()); + } + return inv; + } + + public void startNewJackpot() { + Bukkit.getLogger().info("(CrankedJackpot) Starting new JackPot" + (this.currentJackpot == null ? "!" : ", previous Jackpot: $" + this.currentJackpot.getTotalWinnings())); + this.currentJackpot = new Jackpot(this.defaultDrawTime); + } + + +} + diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/mines/commands/MinesCommand.java b/Gambling/src/main/java/net/crankedpvp/gambling/mines/commands/MinesCommand.java new file mode 100644 index 0000000..01609b6 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/mines/commands/MinesCommand.java @@ -0,0 +1,60 @@ +package net.crankedpvp.gambling.mines.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.mines.inventory.MinesDifficultySelectionInventory; +import net.crankedpvp.gambling.mines.inventory.MinesInformationInventory; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.text.DecimalFormat; + +@Command("mines") +public class MinesCommand extends CommandBase { + + private final GamblingPlugin plugin; + public MinesCommand(GamblingPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender, @Optional Double bet) { + Player player = (Player) commandSender; + if(bet == null) { + MinesInformationInventory minesInformationInventory = new MinesInformationInventory(player); + minesInformationInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + return; + } + + if(bet < 1) { + player.sendMessage(CC.translate("&cBet cannot be less than $1")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(EconomyUtils.hasBalance(player, bet)) { + MinesDifficultySelectionInventory minesDifficultySelectionInventory = new MinesDifficultySelectionInventory(player, bet); + minesDifficultySelectionInventory.getUI().open(player); + return; + } + + player.sendMessage(CC.translate("&cYou cannot afford this bet")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + @SubCommand("adminstats") + @Alias({"as", "adminstats"}) + @Permission("cranked.admin") + public void adminStatsCommand(CommandSender commandSender) { + commandSender.sendMessage("Overall Winnings: " + moneyFormat.format(this.plugin.getOverallMinesWinnings())); + commandSender.sendMessage("Overall Losings: " + moneyFormat.format(this.plugin.getOverallMinesLosings())); + commandSender.sendMessage("Overall Server Profit: " + moneyFormat.format(this.plugin.getOverallMinesWinnings() - this.plugin.getOverallMinesLosings())); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/mines/enums/DifficultyType.java b/Gambling/src/main/java/net/crankedpvp/gambling/mines/enums/DifficultyType.java new file mode 100644 index 0000000..2c93fd1 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/mines/enums/DifficultyType.java @@ -0,0 +1,16 @@ +package net.crankedpvp.gambling.mines.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@AllArgsConstructor +@Getter +public enum DifficultyType { + EASY(8, new double[] { 1D, 1.08D, 1.16D, 1.26D, 1.43D, 1.68D, 1.831D, 2.38D, 3.1D, 3.96D, 4.56D, 5.24D, 6.3D, 7.1D, 7.93D, 9.16D, 10.5D, 12D, 15D, 21D, 30D, 50D, 75D, 125D}), + MEDIUM(17, new double[] { 1D, 1.85D, 2.43D, 3.73D, 5.22D, 7.74D, 10.69D, 14.14D, 21D, 30D, 50D, 90D, 145D, 200D, 270D, 360D, 450D, 600D}), + HARD(25, new double[] { 1D, 2.7D, 5.4D, 9.2D, 14.6D, 20.5D, 28.7D, 40D, 60.5D, 100D, 120D, 210D, 330D, 475D, 665D, 1000D}), + ; + + private final int mines; + private final double[] multiplier; +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesDifficultySelectionInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesDifficultySelectionInventory.java new file mode 100644 index 0000000..a11e8af --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesDifficultySelectionInventory.java @@ -0,0 +1,61 @@ +package net.crankedpvp.gambling.mines.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.mines.enums.DifficultyType; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class MinesDifficultySelectionInventory { + + + private final Gui mineInventory; + + public Gui getUI() { + return this.mineInventory; + } + + + public MinesDifficultySelectionInventory(Player player, double bet) { + this.mineInventory = new Gui(GuiType.HOPPER, "Cranked Mines Difficulty"); + this.mineInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemBuilder easyBuilder = new ItemBuilder(Material.WOOL, 1, (short) 5, + "&a&lEASY", + "&7An easy mine...", + "&7Less bombs"); + ItemBuilder mediumBuilder = new ItemBuilder(Material.WOOL, 1, (short) 4, + "&e&lMEDIUM", + "&7An intermediate mine...", + "&7some bombs"); + ItemBuilder hardBuilder = new ItemBuilder(Material.WOOL, 1, (short) 14, + "&c&lHARD", + "&7A difficult mine...", + "&7lots of bombs"); + this.mineInventory.setItem(1, new GuiItem(easyBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + MinesGameInventory minesGameInventory = new MinesGameInventory(player, DifficultyType.EASY, bet); + minesGameInventory.getUI().open(player); + })); + this.mineInventory.setItem(2, new GuiItem(mediumBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + MinesGameInventory minesGameInventory = new MinesGameInventory(player, DifficultyType.MEDIUM, bet); + minesGameInventory.getUI().open(player); + })); + this.mineInventory.setItem(3, new GuiItem(hardBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + MinesGameInventory minesGameInventory = new MinesGameInventory(player, DifficultyType.HARD, bet); + minesGameInventory.getUI().open(player); + })); + this.mineInventory.setItem(4, new GuiItem(createExitItem(), event -> player.closeInventory())); + this.mineInventory.setItem(0, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit mines menu").colorize().build(); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesGameInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesGameInventory.java new file mode 100644 index 0000000..5f7f698 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesGameInventory.java @@ -0,0 +1,119 @@ +package net.crankedpvp.gambling.mines.inventory; + +import com.google.common.util.concurrent.AtomicDouble; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import net.crankedpvp.gambling.mines.enums.DifficultyType; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class MinesGameInventory { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final GambleUser gambleUser; + + @Setter + private boolean hasLost = false; + + private int currentCashout = 0; + + private final Gui mineInventory; + public Gui getUI() { + return this.mineInventory; + } + + + public MinesGameInventory(Player player, DifficultyType difficultyType, double bet) { + EconomyUtils.withdrawBalance(player, bet); + this.gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + + this.mineInventory = new Gui(6, "Mine Game: " + difficultyType.name()); + this.mineInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.mineInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.mineInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(!hasLost) { + EconomyUtils.depositBalance(player, bet); + player.sendMessage(CC.translate("&aYour money has been returned to you as you closed the GUI")); + } + }); + + + ItemBuilder unknownBuilder = new ItemBuilder(Material.ENDER_CHEST, "&f&l???"); + ItemBuilder safeBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short)5, "&a&lSAFE", + "&7This tile was safe!").setGlowing(); + + + AtomicDouble chance = new AtomicDouble(getMinesAmount(difficultyType) / 28.0); + for(int i = 0; i < 45; i++) { + this.mineInventory.addItem(new GuiItem(unknownBuilder.colorize().build(), event -> { + if(Math.random() < chance.get()) { + setHasLost(true); + this.gambleUser.addMinesLoss(bet); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.EXPLODE, 5.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&c&lBOOM!"), CC.translate("&7You clicked a mine!"), 1, 3, 1); + setHasLost(true); + } else { + currentCashout++; + chance.set(getMinesAmount(difficultyType) / 28.0); + System.out.println(chance); + event.setCurrentItem(safeBuilder.colorize().build()); + setMiddleButton(player, bet, difficultyType); + } + })); + } + setMiddleButton(player, bet, difficultyType); + } + + private int getMinesAmount(DifficultyType difficultyType) { + int mines = difficultyType.getMines(); + mines = mines + currentCashout; + return mines; + } + + private void setMiddleButton(Player player, double bet, DifficultyType difficultyType) { + ItemBuilder middleButton = new ItemBuilder(Material.DIAMOND, "&a&lCASHOUT", + "&7Click this button to cashout"); + List lore = new ArrayList<>(); + lore.add("&fBet: &a$" + moneyFormat.format(bet)); + lore.add("&fMultiplier: &a" + difficultyType.getMultiplier()[currentCashout] + "x"); + lore.add("&fCashout: &a$" + moneyFormat.format(bet * difficultyType.getMultiplier()[currentCashout])); + middleButton.setLore(lore); + middleButton.setGlowing(); + this.mineInventory.updateItem(1, 5, new GuiItem(middleButton.colorize().build(), event -> { + setHasLost(true); + double moneyGain = bet * difficultyType.getMultiplier()[currentCashout]; + EconomyUtils.depositBalance(player, moneyGain); + this.gambleUser.addMinesWin(moneyGain); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 5.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&a&lCASHOUT"), CC.translate("&7You cashed out for $" + moneyFormat.format(moneyGain)), 1, 3, 1); + })); + player.updateInventory(); + } + + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(" "); + item.setItemMeta(meta); + return item; + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesInformationInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesInformationInventory.java new file mode 100644 index 0000000..39a0316 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/mines/inventory/MinesInformationInventory.java @@ -0,0 +1,63 @@ +package net.crankedpvp.gambling.mines.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class MinesInformationInventory { + + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + + private final Gui mineInventory; + + public Gui getUI() { + return this.mineInventory; + } + + + public MinesInformationInventory(Player player) { + this.mineInventory = new Gui(GuiType.HOPPER, "Cranked Mines"); + this.mineInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, + "&cMines Gambling", + "&fUse &c/mines &fto enter the game" + ).colorize().build(); + + GambleUser gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + List playerStatsLore = new ArrayList<>(); + playerStatsLore.add("&fWins: &a" + gambleUser.getMinesWins()); + playerStatsLore.add("&fWinnings: &a$" + moneyFormat.format(gambleUser.getMinesWinnings())); + playerStatsLore.add("&fLosses: &c" + gambleUser.getMinesLosses()); + playerStatsLore.add("&fLosings: &c$" + moneyFormat.format(gambleUser.getMinesLosings())); + playerStatsLore.add("&fRatio: &7[" + gambleUser.getMinesWinLossRatio(":") + "]"); + ItemBuilder playerStatsItemBuilder = new ItemBuilder(Material.PAPER, + "&cMines Stats", + playerStatsLore); + + this.mineInventory.setItem(3, new GuiItem(playerStatsItemBuilder.setGlowing().colorize().build())); + this.mineInventory.setItem(2, new GuiItem(info)); + + this.mineInventory.setItem(4, new GuiItem(createExitItem(), event -> player.closeInventory())); + this.mineInventory.setItem(0, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit mines menu").colorize().build(); + } + + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/roulette/commands/RouletteCommand.java b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/commands/RouletteCommand.java new file mode 100644 index 0000000..be45df9 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/commands/RouletteCommand.java @@ -0,0 +1,51 @@ +package net.crankedpvp.gambling.roulette.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.roulette.inventory.RouletteColourSelectionInventory; +import net.crankedpvp.gambling.roulette.inventory.RouletteInformationInventory; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.text.DecimalFormat; + +@Command("roulette") +public class RouletteCommand extends CommandBase { + private final GamblingPlugin plugin; + public RouletteCommand(GamblingPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender, @Optional Double bet) { + Player player = (Player) commandSender; + if(bet == null) { + RouletteInformationInventory rouletteInformationInventory = new RouletteInformationInventory(player); + rouletteInformationInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + return; + } + + if(bet < 1) { + player.sendMessage(CC.translate("&cBet cannot be less than $1")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(EconomyUtils.hasBalance(player, bet)) { + RouletteColourSelectionInventory rouletteColourSelectionInventory = new RouletteColourSelectionInventory(player, bet); + rouletteColourSelectionInventory.getUI().open(player); + return; + } + + player.sendMessage(CC.translate("&cYou cannot afford this bet")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteColourSelectionInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteColourSelectionInventory.java new file mode 100644 index 0000000..8d6e62f --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteColourSelectionInventory.java @@ -0,0 +1,55 @@ +package net.crankedpvp.gambling.roulette.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.roulette.struct.RouletteColour; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class RouletteColourSelectionInventory { + + + private final Gui mineInventory; + + public Gui getUI() { + return this.mineInventory; + } + + + public RouletteColourSelectionInventory(Player player, double bet) { + this.mineInventory = new Gui(GuiType.HOPPER, "Roulette Colour Selection"); + this.mineInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemBuilder blackBuilder = new ItemBuilder(Material.WOOL, 1, (short) 15, + "&f&lBLACK", + "&7CLick to select black", + ""); + ItemBuilder redBuilder = new ItemBuilder(Material.WOOL, 1, (short) 14, + "&f&lRED", + "&7CLick to select red", + ""); + ItemBuilder greenBuilder = new ItemBuilder(Material.WOOL, 1, (short) 5, + "&f&lGREEN", + "&7CLick to select green", + ""); + this.mineInventory.setItem(1, new GuiItem(blackBuilder.colorize().build(), event -> openGameInv(player, bet, RouletteColour.BLACK))); + this.mineInventory.setItem(2, new GuiItem(greenBuilder.colorize().build(), event -> openGameInv(player, bet, RouletteColour.GREEN))); + this.mineInventory.setItem(3, new GuiItem(redBuilder.colorize().build(), event -> openGameInv(player, bet, RouletteColour.RED))); + this.mineInventory.setItem(4, new GuiItem(createExitItem(), event -> player.closeInventory())); + this.mineInventory.setItem(0, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private void openGameInv(Player player, double bet, RouletteColour rouletteColour) { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + RouletteGameInventory rouletteGameInventory = new RouletteGameInventory(player, rouletteColour); + rouletteGameInventory.getUI().open(player); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit roulette menu").colorize().build(); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteGameInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteGameInventory.java new file mode 100644 index 0000000..dc8afd4 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteGameInventory.java @@ -0,0 +1,134 @@ +package net.crankedpvp.gambling.roulette.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.roulette.struct.RouletteColour; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +public class RouletteGameInventory { + + private int spins; + private int maxSpins; + private Player player; + + private RouletteColour yourRouletteColour; + + private final Map rouletteColours = new HashMap<>(); + + private final Gui rouletteGameInventory; + + public Gui getUI() { + return this.rouletteGameInventory; + } + + private void setupRouletteColours() { + this.rouletteColours.put(0, RouletteColour.BLACK); + this.rouletteColours.put(2, RouletteColour.BLACK); + this.rouletteColours.put(6, RouletteColour.BLACK); + this.rouletteColours.put(8, RouletteColour.BLACK); + this.rouletteColours.put(26, RouletteColour.BLACK); + this.rouletteColours.put(44, RouletteColour.BLACK); + this.rouletteColours.put(52, RouletteColour.BLACK); + this.rouletteColours.put(50, RouletteColour.BLACK); + this.rouletteColours.put(48, RouletteColour.BLACK); + this.rouletteColours.put(46, RouletteColour.BLACK); + this.rouletteColours.put(36, RouletteColour.BLACK); + + this.rouletteColours.put(4, RouletteColour.GREEN); + this.rouletteColours.put(49, RouletteColour.GREEN); + + this.rouletteColours.put(1, RouletteColour.RED); + this.rouletteColours.put(3, RouletteColour.RED); + this.rouletteColours.put(5, RouletteColour.RED); + this.rouletteColours.put(7, RouletteColour.RED); + this.rouletteColours.put(17, RouletteColour.RED); + this.rouletteColours.put(35, RouletteColour.RED); + this.rouletteColours.put(53, RouletteColour.RED); + this.rouletteColours.put(51, RouletteColour.RED); + this.rouletteColours.put(47, RouletteColour.RED); + this.rouletteColours.put(45, RouletteColour.RED); + } + + public RouletteGameInventory(Player player, RouletteColour rouletteColour) { + + this.spins = 0; + this.maxSpins = ThreadLocalRandom.current().nextInt(60, 80); + this.player = player; + this.yourRouletteColour = rouletteColour; + + this.rouletteGameInventory = new Gui(6, "Roulette Game"); + this.rouletteGameInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.rouletteColours.forEach((integer, colour) -> this.rouletteGameInventory.setItem(integer, new GuiItem(createColourSquare(rouletteColour)))); + this.rouletteGameInventory.setItem(22, new GuiItem(createInfoItem())); + this.recursiveSpin(0, 2); + } + + private void recursiveSpin(int index, long speed) { + + this.spins++; + if(this.spins >= this.maxSpins) { + RouletteColour rouletteColour = rouletteColours.get(index); + return; + } + + if(index >= this.rouletteColours.size()) { + recursiveSpin(0, speed); + return; + } + + setGlowing(index); + int lastSpun = index - 1; + if(lastSpun >= 0) { + removeGlowing(lastSpun); + } else { + removeGlowing(this.rouletteColours.size()-1); + } + this.player.updateInventory(); + + + if(spins > 70) { + GamblingPlugin.getInstance().getServer().getScheduler().runTaskLater(GamblingPlugin.getInstance(), () -> recursiveSpin((index + 1), 4L), speed); + } else if(spins > 50) { + GamblingPlugin.getInstance().getServer().getScheduler().runTaskLater(GamblingPlugin.getInstance(), () -> recursiveSpin((index + 1), 3L), speed); + } else { + GamblingPlugin.getInstance().getServer().getScheduler().runTaskLater(GamblingPlugin.getInstance(), () -> recursiveSpin((index + 1), 1L), speed); + } + } + + + private ItemStack createInfoItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND, "&e&lRoulette Information", + "&fSelected: &e" + this.yourRouletteColour.name().toUpperCase(), + "&fMultiplier: &a" + this.yourRouletteColour.getMultiplier() + "x"); + return itemBuilder.colorize().build(); + } + + + private ItemStack createColourSquare(RouletteColour rouletteColour) { + ItemBuilder itemBuilder = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, rouletteColour.getGlassColour()); + itemBuilder.setName(rouletteColour.getColour() + rouletteColour.name().toUpperCase(Locale.ROOT)); + itemBuilder.setLore("&fMultiplier: &a" + rouletteColour.getMultiplier() + "x"); + return itemBuilder.colorize().build(); + } + + private void setGlowing(int index) { + ItemBuilder currentItemBuilder = new ItemBuilder(this.rouletteGameInventory.getGuiItem(index).getItemStack()); + currentItemBuilder.setGlowing(); + this.rouletteGameInventory.updateItem(index, new GuiItem(currentItemBuilder.colorize().build())); + } + + private void removeGlowing(int index) { + ItemBuilder lastItemBuilder = new ItemBuilder(this.rouletteGameInventory.getGuiItem(index).getItemStack()); + lastItemBuilder.removeGlow(); + this.rouletteGameInventory.updateItem(index, new GuiItem(lastItemBuilder.colorize().build())); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteInformationInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteInformationInventory.java new file mode 100644 index 0000000..c28282b --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/inventory/RouletteInformationInventory.java @@ -0,0 +1,63 @@ +package net.crankedpvp.gambling.roulette.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class RouletteInformationInventory { + + + private static final DecimalFormat decimalFormat = new DecimalFormat("#.##"); + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + + private final Gui rouletteInformationInventory; + + public Gui getUI() { + return this.rouletteInformationInventory; + } + + + public RouletteInformationInventory(Player player) { + this.rouletteInformationInventory = new Gui(GuiType.HOPPER, "Cranked Roulette"); + this.rouletteInformationInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, + "&cRoulette Gambling", + "&fUse &c/roulette &fto enter the game" + ).colorize().build(); + + GambleUser gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + List playerStatsLore = new ArrayList<>(); + playerStatsLore.add("&fWins: &a" + gambleUser.getMinesWins()); + playerStatsLore.add("&fWinnings: &a$" + moneyFormat.format(gambleUser.getMinesWinnings())); + playerStatsLore.add("&fLosses: &c" + gambleUser.getMinesLosses()); + playerStatsLore.add("&fLosings: &c$" + moneyFormat.format(gambleUser.getMinesLosings())); + playerStatsLore.add("&fRatio: &7[" + gambleUser.getMinesWinLossRatio(":") + "]"); + ItemBuilder playerStatsItemBuilder = new ItemBuilder(Material.PAPER, + "&cMines Stats", + playerStatsLore); + + this.rouletteInformationInventory.setItem(3, new GuiItem(playerStatsItemBuilder.setGlowing().colorize().build())); + this.rouletteInformationInventory.setItem(2, new GuiItem(info)); + + this.rouletteInformationInventory.setItem(4, new GuiItem(createExitItem(), event -> player.closeInventory())); + this.rouletteInformationInventory.setItem(0, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit mines menu").colorize().build(); + } + + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteColour.java b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteColour.java new file mode 100644 index 0000000..8d02eaa --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteColour.java @@ -0,0 +1,19 @@ +package net.crankedpvp.gambling.roulette.struct; + + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter @AllArgsConstructor +public enum RouletteColour { + + RED(2, (short)14, "&c"), + BLACK(2, (short) 15, "&0"), + GREEN(8, (short) 5, "&a"), + ; + + + private final int multiplier; + private final short glassColour; + private final String colour; +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteGame.java b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteGame.java new file mode 100644 index 0000000..14cc029 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteGame.java @@ -0,0 +1,16 @@ +package net.crankedpvp.gambling.roulette.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.io.Serializable; +import java.util.List; +import java.util.UUID; + +@Getter +@AllArgsConstructor +public class RouletteGame implements Serializable { + private UUID rouletteGameID; + private List players; + private RouletteColour rouletteColour; +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RoulettePlayer.java b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RoulettePlayer.java new file mode 100644 index 0000000..df576dd --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RoulettePlayer.java @@ -0,0 +1,25 @@ +package net.crankedpvp.gambling.roulette.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.io.Serializable; +import java.util.UUID; + +@Getter @AllArgsConstructor +public class RoulettePlayer implements Serializable { + private UUID playerUUID; + private Double money; + private RouletteColour rouletteColour; + private RouletteColour gameEndedOn; + + public boolean isWinner() { + if(gameEndedOn == null) return false; + return rouletteColour == gameEndedOn; + } + + public Double getWinnings() { + if(!isWinner()) return null; + return money * rouletteColour.getMultiplier(); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteStats.java b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteStats.java new file mode 100644 index 0000000..b9f8216 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/roulette/struct/RouletteStats.java @@ -0,0 +1,20 @@ +package net.crankedpvp.gambling.roulette.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +import java.io.Serializable; +import java.util.List; +import java.util.UUID; + +@Getter +@AllArgsConstructor +public class RouletteStats implements Serializable { + + private UUID playerUUID; + + @Setter + private List rouletteGames; + +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/tower/commands/TowerCommand.java b/Gambling/src/main/java/net/crankedpvp/gambling/tower/commands/TowerCommand.java new file mode 100644 index 0000000..6d3ef0f --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/tower/commands/TowerCommand.java @@ -0,0 +1,61 @@ +package net.crankedpvp.gambling.tower.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.tower.inventory.TowerDifficultySelectionInventory; +import net.crankedpvp.gambling.tower.inventory.TowerInformationInventory; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.text.DecimalFormat; + +@Command("tower") +@Alias("towers") +public class TowerCommand extends CommandBase { + + private final GamblingPlugin plugin; + public TowerCommand(GamblingPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender, @Optional Double bet) { + Player player = (Player) commandSender; + if(bet == null) { + TowerInformationInventory towerInformationInventory = new TowerInformationInventory(player); + towerInformationInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + return; + } + + if(bet < 1) { + player.sendMessage(CC.translate("&cBet cannot be less than $1")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(EconomyUtils.hasBalance(player, bet)) { + TowerDifficultySelectionInventory towerDifficultySelectionInventory = new TowerDifficultySelectionInventory(player, bet); + towerDifficultySelectionInventory.getUI().open(player); + return; + } + + player.sendMessage(CC.translate("&cYou cannot afford this bet")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + @SubCommand("adminstats") + @Alias({"as", "adminstats"}) + @Permission("cranked.admin") + public void adminStatsCommand(CommandSender commandSender) { + commandSender.sendMessage("Overall Winnings: " + moneyFormat.format(this.plugin.getOverallTowerWinnings())); + commandSender.sendMessage("Overall Losings: " + moneyFormat.format(this.plugin.getOverallTowerLosings())); + commandSender.sendMessage("Overall Server Profit: " + moneyFormat.format(this.plugin.getOverallTowerWinnings() - this.plugin.getOverallTowerLosings())); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/tower/enums/DifficultyType.java b/Gambling/src/main/java/net/crankedpvp/gambling/tower/enums/DifficultyType.java new file mode 100644 index 0000000..e1f905a --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/tower/enums/DifficultyType.java @@ -0,0 +1,15 @@ +package net.crankedpvp.gambling.tower.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@AllArgsConstructor +@Getter +public enum DifficultyType { + EASY(new double[] { 1D, 1.5D, 2.1D, 2.75D, 3.5D, 4.2D, 5D}), + MEDIUM(new double[] { 1D, 1.85D, 3.53D, 7.14D, 14.82D, 29.23D, 59.39D}), + HARD(new double[] { 1D, 2.8D, 6.5D, 14.3D, 28.6D, 57.5D, 115.7D}), + ; + + private final double[] multiplier; +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerDifficultySelectionInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerDifficultySelectionInventory.java new file mode 100644 index 0000000..9412a42 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerDifficultySelectionInventory.java @@ -0,0 +1,60 @@ +package net.crankedpvp.gambling.tower.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.tower.enums.DifficultyType; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class TowerDifficultySelectionInventory { + + private final Gui towerDifficultySelectionInventory; + + public Gui getUI() { + return this.towerDifficultySelectionInventory; + } + + + public TowerDifficultySelectionInventory(Player player, double bet) { + this.towerDifficultySelectionInventory = new Gui(GuiType.HOPPER, "Cranked Towers Difficulty"); + this.towerDifficultySelectionInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemBuilder easyBuilder = new ItemBuilder(Material.WOOL, 1, (short) 5, + "&a&lEASY", + "&7There are three towers in easy mode", + "&7Only one row of the tower is bad"); + ItemBuilder mediumBuilder = new ItemBuilder(Material.WOOL, 1, (short) 4, + "&e&lMEDIUM", + "&7There are two towers in medium mode", + "&7One row is good, the other is bad"); + ItemBuilder hardBuilder = new ItemBuilder(Material.WOOL, 1, (short) 14, + "&c&lHARD", + "&7There are three towers in hard mode", + "&7Two of the rows of the tower are bad"); + this.towerDifficultySelectionInventory.setItem(1, new GuiItem(easyBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + TowerGameInventory towerGameInventory = new TowerGameInventory(player, DifficultyType.EASY, bet); + towerGameInventory.getUI().open(player); + })); + this.towerDifficultySelectionInventory.setItem(2, new GuiItem(mediumBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + TowerGameInventory towerGameInventory = new TowerGameInventory(player, DifficultyType.MEDIUM, bet); + towerGameInventory.getUI().open(player); + })); + this.towerDifficultySelectionInventory.setItem(3, new GuiItem(hardBuilder.colorize().build(), event -> { + if(! EconomyUtils.hasBalance(player, bet)) player.closeInventory(); + TowerGameInventory towerGameInventory = new TowerGameInventory(player, DifficultyType.HARD, bet); + towerGameInventory.getUI().open(player); + })); + this.towerDifficultySelectionInventory.setItem(4, new GuiItem(createExitItem(), event -> player.closeInventory())); + this.towerDifficultySelectionInventory.setItem(0, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit towers menu").colorize().build(); + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerGameInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerGameInventory.java new file mode 100644 index 0000000..93a55a0 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerGameInventory.java @@ -0,0 +1,197 @@ +package net.crankedpvp.gambling.tower.inventory; + +import de.tr7zw.nbtapi.NBTItem; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import net.crankedpvp.gambling.tower.enums.DifficultyType; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class TowerGameInventory { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final GambleUser gambleUser; + + private int currentCashout = 0; + + @Setter + private boolean hasLost = false; + + private int row = 6; + + private final Gui towerGameInventory; + public Gui getUI() { + return this.towerGameInventory; + } + + + public TowerGameInventory(Player player, DifficultyType difficultyType, double bet) { + EconomyUtils.withdrawBalance(player, bet); + this.gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + + this.towerGameInventory = new Gui(6, "Tower Game: " + difficultyType.name()); + this.towerGameInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.towerGameInventory.getFiller().fill(new GuiItem(createFillerItem())); + this.towerGameInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(!hasLost) { + EconomyUtils.depositBalance(player, bet); + player.sendMessage(CC.translate("&aYour money has been returned to you as you closed the GUI")); + } + }); + + switch(difficultyType) { + case EASY: + startEasyTowerGame(player, bet); + break; + case MEDIUM: + startMediumTowerGame(player, bet); + break; + case HARD: + startHardTowerGame(player, bet); + break; + } + + } + + private void startMediumTowerGame(Player player, double bet) { + setCashoutButton(player, bet, DifficultyType.MEDIUM); + for(int row = 1; row < 7; row++) { + ItemStack itemStack = new ItemBuilder(Material.ENDER_CHEST, "&f&l???").colorize().build(); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("row", row); + for(int column : new int[] {4, 6}) { + this.towerGameInventory.setItem(row, column, new GuiItem(nbtItem.getItem(), event -> { + NBTItem nbtItem1 = new NBTItem(event.getCurrentItem()); + if(this.row == nbtItem1.getInteger("row")) { + if(Math.random() > 0.5D) { + this.row--; + currentCashout++; + ItemStack correctItemStack = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short) 5, "&a&lCORRECT").colorize().build(); + this.towerGameInventory.updateItem(event.getSlot(), new GuiItem(correctItemStack)); + setCashoutButton(player, bet, DifficultyType.MEDIUM); + } else { + setHasLost(true); + this.gambleUser.addTowerLoss(bet); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.ITEM_BREAK, 3.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&c&lTOWER CRASHED"), CC.translate("&fYour tower crashed..."), 1, 3, 1); + } + } else { + player.sendMessage(CC.translate("&cError: &eYou are not on this row in the tower.")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + })); + } + } + } + + private void startEasyTowerGame(Player player, double bet) { + setCashoutButton(player, bet, DifficultyType.EASY); + for(int row = 1; row < 7; row++) { + ItemStack itemStack = new ItemBuilder(Material.ENDER_CHEST, "&f&l???").colorize().build(); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("row", row); + for(int column : new int[] {3, 5, 7}) { + this.towerGameInventory.setItem(row, column, new GuiItem(nbtItem.getItem(), event -> { + NBTItem nbtItem1 = new NBTItem(event.getCurrentItem()); + if(this.row == nbtItem1.getInteger("row")) { + if(Math.random() > 0.33D) { + this.row--; + currentCashout++; + ItemStack correctItemStack = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short) 5, "&a&lCORRECT").colorize().build(); + this.towerGameInventory.updateItem(event.getSlot(), new GuiItem(correctItemStack)); + setCashoutButton(player, bet, DifficultyType.EASY); + } else { + setHasLost(true); + this.gambleUser.addTowerLoss(bet); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.ITEM_BREAK, 3.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&c&lTOWER CRASHED"), CC.translate("&fYour tower crashed..."), 1, 3, 1); + } + } else { + player.sendMessage(CC.translate("&cError: &eYou are not on this row in the tower.")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + })); + } + } + } + + private void startHardTowerGame(Player player, double bet) { + setCashoutButton(player, bet, DifficultyType.HARD); + for(int row = 1; row < 7; row++) { + ItemStack itemStack = new ItemBuilder(Material.ENDER_CHEST, "&f&l???").colorize().build(); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("row", row); + for(int column : new int[] {3, 5, 7}) { + this.towerGameInventory.setItem(row, column, new GuiItem(nbtItem.getItem(), event -> { + NBTItem nbtItem1 = new NBTItem(event.getCurrentItem()); + if(this.row == nbtItem1.getInteger("row")) { + if(Math.random() > 0.66D) { + this.row--; + currentCashout++; + ItemStack correctItemStack = new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (short) 5, "&a&lCORRECT").colorize().build(); + this.towerGameInventory.updateItem(event.getSlot(), new GuiItem(correctItemStack)); + setCashoutButton(player, bet, DifficultyType.HARD); + } else { + setHasLost(true); + this.gambleUser.addTowerLoss(bet); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.ITEM_BREAK, 3.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&c&lTOWER CRASHED"), CC.translate("&fYour tower crashed..."), 1, 3, 1); + } + } else { + player.sendMessage(CC.translate("&cError: &eYou are not on this row in the tower.")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + })); + } + } + } + + private void setCashoutButton(Player player, double bet, DifficultyType difficultyType) { + ItemBuilder cashoutButton = new ItemBuilder(Material.DIAMOND, "&a&lCASHOUT", + "&7Click this button to cashout"); + List lore = new ArrayList<>(); + lore.add("&fBet: &a$" + moneyFormat.format(bet)); + lore.add("&fMultiplier: &a" + difficultyType.getMultiplier()[currentCashout] + "x"); + lore.add("&fCashout: &a$" + moneyFormat.format(bet * difficultyType.getMultiplier()[currentCashout])); + cashoutButton.setLore(lore); + cashoutButton.setGlowing(); + this.towerGameInventory.updateItem(3, 9, new GuiItem(cashoutButton.colorize().build(), event -> { + setHasLost(true); + double moneyGain = bet * difficultyType.getMultiplier()[currentCashout]; + EconomyUtils.depositBalance(player, moneyGain); + this.gambleUser.addTowerWin(moneyGain); + player.closeInventory(); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 5.0F, 2.0F); + TitleUtils.sendTitle(player, CC.translate("&a&lCASHOUT"), CC.translate("&7You cashed out for " + moneyFormat.format(moneyGain)), 1, 3, 1); + })); + player.updateInventory(); + } + + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(" "); + item.setItemMeta(meta); + return item; + } +} diff --git a/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerInformationInventory.java b/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerInformationInventory.java new file mode 100644 index 0000000..1219090 --- /dev/null +++ b/Gambling/src/main/java/net/crankedpvp/gambling/tower/inventory/TowerInformationInventory.java @@ -0,0 +1,60 @@ +package net.crankedpvp.gambling.tower.inventory; + +import dev.triumphteam.gui.components.GuiType; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.gambling.GamblingPlugin; +import net.crankedpvp.gambling.data.GambleUser; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class TowerInformationInventory { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + + private final Gui towerInformationInventory; + + public Gui getUI() { + return this.towerInformationInventory; + } + + + public TowerInformationInventory(Player player) { + this.towerInformationInventory = new Gui(GuiType.HOPPER, "Cranked Towers"); + this.towerInformationInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, + "&cTowers Gambling", + "&fUse &c/tower &fto enter the game" + ).colorize().build(); + + GambleUser gambleUser = GamblingPlugin.getInstance().getGambleManager().getGambleUser(player.getUniqueId()); + List playerStatsLore = new ArrayList<>(); + playerStatsLore.add("&fWins: &a" + gambleUser.getTowerWins()); + playerStatsLore.add("&fWinnings: &a$" + moneyFormat.format(gambleUser.getTowerWinnings())); + playerStatsLore.add("&fLosses: &c" + gambleUser.getTowerLosses()); + playerStatsLore.add("&fLosings: &c$" + moneyFormat.format(gambleUser.getTowerLosings())); + playerStatsLore.add("&fRatio: &7[" + gambleUser.getTowerWinLossRatio(":") + "]"); + ItemBuilder playerStatsItemBuilder = new ItemBuilder(Material.PAPER, + "&cTower Stats", + playerStatsLore); + + this.towerInformationInventory.setItem(3, new GuiItem(playerStatsItemBuilder.setGlowing().colorize().build())); + this.towerInformationInventory.setItem(2, new GuiItem(info)); + + this.towerInformationInventory.setItem(4, new GuiItem(createExitItem(), event -> player.closeInventory())); + this.towerInformationInventory.setItem(0, new GuiItem(createExitItem(), event -> player.closeInventory())); + } + + private ItemStack createExitItem() { + return new ItemBuilder(Material.FENCE_GATE, "&cExit tower menu").colorize().build(); + } + +} diff --git a/Gambling/src/main/resources/plugin.yml b/Gambling/src/main/resources/plugin.yml new file mode 100644 index 0000000..27bb61a --- /dev/null +++ b/Gambling/src/main/resources/plugin.yml @@ -0,0 +1,15 @@ +name: CrankedGambling +main: net.crankedpvp.gambling.GamblingPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - StorageUtil +commands: + coinflip: + description: Coin flip command. + aliases: [ cf, coinflips] + jackpot: + description: Jackpot command. + aliases: [ jp, jackpots ] \ No newline at end of file diff --git a/GrindingSword/pom.xml b/GrindingSword/pom.xml new file mode 100644 index 0000000..8cdfa6d --- /dev/null +++ b/GrindingSword/pom.xml @@ -0,0 +1,49 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + GrindingSword + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + Shards + + + net.crankedpvp + Leaderboards + + + net.crankedpvp + Keys + + + net.crankedpvp + Spawners + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/GrindingSwordAPI.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/GrindingSwordAPI.java new file mode 100644 index 0000000..bcb2248 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/GrindingSwordAPI.java @@ -0,0 +1,44 @@ +package net.crankedpvp.grindingsword; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.grindingsword.struct.Enchant; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class GrindingSwordAPI { + + public static boolean isGrindingSword(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + if(!nbtItem.hasKey("crankedCustomItem")) return false; + return nbtItem.getString("crankedCustomItem").equals("grindingSword"); + } + + public static UUID getGrindingSwordUUID(ItemStack itemStack) { + if(!isGrindingSword(itemStack)) return null; + NBTItem nbtItem = new NBTItem(itemStack); + return UUID.fromString(nbtItem.getString("grindingSwordUUID")); + } + + public static Map getEnchantsOnGrindingSword(ItemStack itemStack) { + if(!isGrindingSword(itemStack)) return null; + Map enchantIntegerMap = new HashMap<>(); + + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound nbtCompound = nbtItem.getCompound("grindingSwordEnchants"); + for(String enchantName : nbtCompound.getKeys()) { + if(nbtCompound.getInteger(enchantName) < 1) continue; + enchantIntegerMap.put(GrindingSwordPlugin.getInstance().getEnchantRegister().getEnchant(enchantName), nbtCompound.getInteger(enchantName)); + } + + return enchantIntegerMap; + + } + +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/GrindingSwordPlugin.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/GrindingSwordPlugin.java new file mode 100644 index 0000000..d2cfd24 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/GrindingSwordPlugin.java @@ -0,0 +1,49 @@ +package net.crankedpvp.grindingsword; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.grindingsword.cache.CacheStorage; +import net.crankedpvp.grindingsword.commands.GrindingSwordCommand; +import net.crankedpvp.grindingsword.listeners.GrindingSwordDeathListener; +import net.crankedpvp.grindingsword.listeners.OpenSwordInventoryListener; +import net.crankedpvp.grindingsword.struct.EnchantRegister; +import net.crankedpvp.grindingsword.tasks.GrindingRewardsTask; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class GrindingSwordPlugin extends JavaPlugin { + + @Getter + private static GrindingSwordPlugin instance; + + @Getter + private CacheStorage cacheStorage; + + private CommandManager commandManager; + @Getter + private EnchantRegister enchantRegister; + + @Override + public void onEnable() { + instance = this; + + this.cacheStorage = new CacheStorage(); + this.commandManager = new CommandManager(this); + this.commandManager.register(new GrindingSwordCommand()); + + this.enchantRegister = new EnchantRegister(this); + this.enchantRegister.initialize(); + + this.registerListeners(); + + GrindingRewardsTask grindingRewardsTask = new GrindingRewardsTask(); + grindingRewardsTask.runTaskTimer(this, 40L, 15 * 20L); + } + + private void registerListeners() { + + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new OpenSwordInventoryListener(this), this); + pluginManager.registerEvents(new GrindingSwordDeathListener(), this); + } +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/cache/CacheStorage.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/cache/CacheStorage.java new file mode 100644 index 0000000..194e0de --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/cache/CacheStorage.java @@ -0,0 +1,49 @@ +package net.crankedpvp.grindingsword.cache; + +import lombok.Getter; +import net.crankedpvp.grindingsword.struct.GrindingSword; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +public class CacheStorage { + + @Getter + private static CacheStorage cacheStorage; + + private final Map playerCacheMap; + + public CacheStorage() { + cacheStorage = this; + this.playerCacheMap = new HashMap<>(); + } + + public Map getPlayersInCache() { + return this.playerCacheMap; + } + + public void removePlayerFromCache(Player player) { + this.playerCacheMap.remove(player); + } + + public void putPlayerInCache(Player player) { + PlayerCache playerCache = new PlayerCache(player); + playerCacheMap.put(player, playerCache); + } + + public void putPlayerInCache(Player player, GrindingSword grindingSword) { + PlayerCache playerCache = new PlayerCache(player); + playerCache.setGrindingSword(grindingSword); + playerCacheMap.put(player, playerCache); + } + + public PlayerCache getPlayerCache(Player player) { + return this.playerCacheMap.get(player); + } + + public boolean isCached(Player player) { + return this.playerCacheMap.containsKey(player); + } + +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/cache/PlayerCache.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/cache/PlayerCache.java new file mode 100644 index 0000000..4134942 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/cache/PlayerCache.java @@ -0,0 +1,114 @@ +package net.crankedpvp.grindingsword.cache; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.XPUtils; +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.grindingsword.struct.GrindingSword; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.shards.ShardsAPI; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +@Getter +public class PlayerCache { + + private final Player player; + private GrindingSword grindingSword; + + @Setter + private long lastKilledInMs; + + + private final Map keys; + private double shards; + private double exp; + private int mobsKilled; + + public PlayerCache(Player player) { + this.player = player; + this.grindingSword = null; + this.keys = new HashMap<>(); + this.shards = 0; + this.exp = 0; + this.mobsKilled = 0; + this.lastKilledInMs = System.currentTimeMillis(); + } + + public boolean hasBeenAmountOfTimeInSeconds(int seconds) { + return System.currentTimeMillis() - this.lastKilledInMs > (seconds * 1000L); + } + + public void setGrindingSword(GrindingSword grindingSword) { + this.grindingSword = grindingSword; + } + + public void addKey(CrateKeyType key) { + if(keys.containsKey(key)) { + int value = keys.get(key); + keys.put(key, value + 1); + return; + } + keys.put(key, 1); + } + + public void addShards(double amount) { + this.shards = this.shards + amount; + } + + public void addMobsKilled(int amount) { + this.mobsKilled = this.mobsKilled + amount; + } + + public void addExp(double amount) { + this.exp = this.exp + amount; + } + + public int getAmountOfKeys() { + int finalVal = 0; + for(Integer value : this.keys.values()) { + finalVal+=value; + } + return finalVal; + } + + public void reset() { + this.mobsKilled = 0; + this.exp = 0; + this.shards = 0; + this.keys.clear(); + } + + public boolean areDefaultValues() { + return this.exp == 0 && this.shards == 0 && this.keys.isEmpty(); + } + + public void giveRewardsToPlayer() { + if(this.areDefaultValues()) return; + this.keys.forEach((keyName, amount) -> CrankedCrateKeysAPI.givePlayerKeys(player, keyName, amount)); + XPUtils.addExperience(this.player, (int)this.exp); + ShardsAPI.getShardsUser(this.player).addShards(this.shards); + + + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).addEXPGained((int) exp); + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).addMobsKilled(this.mobsKilled); + + player.sendMessage(CC.translate("")); + player.sendMessage(CC.translate("&c&lGrinding Rewards")); + player.sendMessage(CC.translate("&8 ➥ &7EXP: &e" + NumberUtils.formatMoney(exp))); + player.sendMessage(CC.translate("&8 ➥ &7Shards: &b" + NumberUtils.formatMoney(shards) + "♦")); + player.sendMessage(CC.translate("&8 ➥ &7Keys Gathered: &d" + NumberUtils.formatMoney(getAmountOfKeys()))); + player.sendMessage(CC.translate("&8 ➥ &7Mobs Killed: &c" + NumberUtils.formatMoney(mobsKilled))); + player.sendMessage(CC.translate("&7&o(( Every &f15s &7&oyou will receive your grinding rewards from the last 15s. ))")); + player.sendMessage(CC.translate("")); + + + //player.sendMessage(CC.translate("&8 ➥ &7Money: &2$&a" + NumberUtils.formatMoney(moneyEarned))); + this.reset(); + } +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/commands/GrindingSwordCommand.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/commands/GrindingSwordCommand.java new file mode 100644 index 0000000..f935f25 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/commands/GrindingSwordCommand.java @@ -0,0 +1,60 @@ +package net.crankedpvp.grindingsword.commands; + +import de.tr7zw.nbtapi.NBTItem; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.grindingsword.GrindingSwordAPI; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +@Command("cgs") +@Alias({"grindingsword", "crankedgrindingsword"}) +public class GrindingSwordCommand extends CommandBase { + + @Default + @Permission("cranked.admin") + public void defaultCommand(final CommandSender commandSender, @Optional Player receiver) { + + if(receiver == null) { + if(!(commandSender instanceof Player)) { + commandSender.sendMessage(CC.translate("&cYou must be a player to receive this item")); + return; + } + receiver = (Player) commandSender; + } + + ItemBuilder itemBuilder = new ItemBuilder(Material.GOLD_SWORD, "&4&lGrinding&8 &8➥ &f&lSword", + "", "&7&oAn upgradeable sword used to", + "&7&omake the most out of grinding...", + "", + "&4Enchantments:", + "", + "&7&nShift Right-Click&r &7to &fupgrade &7this weapon"); + + itemBuilder.addEnchantment(Enchantment.DAMAGE_ALL, 5); + itemBuilder.setUnbreakable(true); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "grindingSword"); + nbtItem.setString("grindingSwordUUID", UUID.randomUUID().toString()); + nbtItem.addCompound("grindingSwordEnchants"); + + + receiver.getInventory().addItem(nbtItem.getItem()); + + } + + @SubCommand("uuid") + @Permission("cranked.admin") + public void checkUuidCommand(final Player player) { + ItemStack itemStack = player.getItemInHand(); + if(!GrindingSwordAPI.isGrindingSword(itemStack)) return; + player.sendMessage(CC.translate("&cGrinding Sword UUID: &f" + GrindingSwordAPI.getGrindingSwordUUID(itemStack))); + } +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/Inquisitive.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/Inquisitive.java new file mode 100644 index 0000000..5778ea9 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/Inquisitive.java @@ -0,0 +1,23 @@ +package net.crankedpvp.grindingsword.enchants; + +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.grindingsword.cache.CacheStorage; +import net.crankedpvp.grindingsword.struct.Enchant; +import net.crankedpvp.spawners.events.StackedMobDeathEvent; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +public class Inquisitive extends Enchant { + public Inquisitive() { + super("inquisitive", 25, Material.EXP_BOTTLE, "&6&lInquisitive", new String[]{"&7Gain more EXP from killing hostile", "&7mobs with this grinding sword"}, 11, + new int[]{50, 100, 150, 200, 250, 300, 400, 500, 750, 1000, 1500, 2500, 3500, 5000, 7500, 10000, 12500, 15000, 17500, 20000, 22500, 25000, 28500, 31000, 34500}); + } + + @Override + public void runStackedMobDeathEvent(StackedMobDeathEvent event, int level) { + double expDropped = event.getExp(event.getEntity().getType()); + Player player = (Player) event.getDamager(); + double multiplier = LuckpermUtils.playerHasRank(player, "satan") ? 1.5 : 1.0; + CacheStorage.getCacheStorage().getPlayerCache(player).addExp(multiplier * (int) (((expDropped * (1+(0.1 * level))) * (1 + Math.random()))) ); + } +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/KeyGrind.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/KeyGrind.java new file mode 100644 index 0000000..77943e4 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/KeyGrind.java @@ -0,0 +1,37 @@ +package net.crankedpvp.grindingsword.enchants; + +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.grindingsword.cache.CacheStorage; +import net.crankedpvp.grindingsword.struct.Enchant; +import net.crankedpvp.spawners.events.StackedMobDeathEvent; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +public class KeyGrind extends Enchant { + public KeyGrind() { + super("key_grind", 15, Material.TRIPWIRE_HOOK, "&d&lKey Grind", new String[]{"&7Gain keys from killing hostile", "&7mobs with this grinding sword"}, 13, + new int[]{50, 100, 150, 200, 250, 300, 400, 500, 750, 1000, 1250, 1500, 1750, 2000, 2500}); + } + + @Override + public void runStackedMobDeathEvent(StackedMobDeathEvent event, int level) { + Player player = (Player) event.getDamager(); + + if((Math.random() * 1000) > (level * 16) * 3) return; + if(level < 8) { + CacheStorage.getCacheStorage().getPlayerCache(player).addKey(CrateKeyType.ABYSS_KEY); + } + + if(level < 3) return; + if((Math.random() * 1000) > (level * 11) * 3) return; + CacheStorage.getCacheStorage().getPlayerCache(player).addKey(CrateKeyType.MYTHIC_KEY); + + + if(level < 8) return; + if((Math.random() * 1000) > (level * 6) * 3) return; + CacheStorage.getCacheStorage().getPlayerCache(player).addKey(CrateKeyType.SEASON_KEY); + } + + // * 3 FOR BETA + +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/ShardGrind.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/ShardGrind.java new file mode 100644 index 0000000..c8ce114 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/enchants/ShardGrind.java @@ -0,0 +1,25 @@ +package net.crankedpvp.grindingsword.enchants; + +import net.crankedpvp.grindingsword.cache.CacheStorage; +import net.crankedpvp.grindingsword.struct.Enchant; +import net.crankedpvp.spawners.events.StackedMobDeathEvent; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +public class ShardGrind extends Enchant { + public ShardGrind() { + super("shard_grind", 10, Material.PRISMARINE_SHARD, "&b&lShard Grind", new String[]{"&7Gain shards from killing hostile", "&7mobs with this grinding sword"}, 15, + new int[]{0, 75, 125, 165, 200, 250, 325, 425, 550, 750}); + } + + @Override + public void runStackedMobDeathEvent(StackedMobDeathEvent event, int level) { + Player player = (Player) event.getDamager(); + + if((Math.random() * 1000) > (2 * ((level+1) * 30))) return; + CacheStorage.getCacheStorage().getPlayerCache(player).addShards(1); + } + + // * 2 FOR BETA + +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/inventory/GrindingSwordInventory.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/inventory/GrindingSwordInventory.java new file mode 100644 index 0000000..ab0e84e --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/inventory/GrindingSwordInventory.java @@ -0,0 +1,83 @@ +package net.crankedpvp.grindingsword.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.grindingsword.GrindingSwordPlugin; +import net.crankedpvp.grindingsword.cache.CacheStorage; +import net.crankedpvp.grindingsword.struct.Enchant; +import net.crankedpvp.grindingsword.struct.EnchantRegister; +import net.crankedpvp.grindingsword.struct.GrindingSword; +import net.crankedpvp.shards.ShardsAPI; +import net.crankedpvp.shards.data.ShardsUser; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class GrindingSwordInventory { + + private final Gui grindingSwordInventory; + private final GrindingSword grindingSword; + private final EnchantRegister enchantRegister; + + public Gui getUI() { + return this.grindingSwordInventory; + } + + public GrindingSwordInventory(ItemStack itemStack) { + this.enchantRegister = GrindingSwordPlugin.getInstance().getEnchantRegister(); + this.grindingSword = new GrindingSword(itemStack); + this.grindingSwordInventory = new Gui(3, "Grinding Sword"); + this.grindingSwordInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + + this.addEnchantsToInventory(); + } + + private void addEnchantsToInventory() { + for(Enchant enchant : this.enchantRegister.getEnchants()) { + this.addEnchantToInventory(enchant); + } + } + + private void addEnchantToInventory(Enchant enchant) { + List lore = new ArrayList<>(Arrays.asList(enchant.getGuiLore())); + lore.add(""); + lore.add("&7Current Level: " + this.grindingSword.getEnchantLevel(enchant) + "&f/&7" + enchant.getMaxLevel()); + lore.add(""); + int cost = this.grindingSword.getEnchantLevel(enchant) >= enchant.getMaxLevel() ? 0 : enchant.getPrices()[this.grindingSword.getEnchantLevel(enchant)]; + lore.add("&b&lCOST &f" + cost + " Shards"); + ItemStack itemStack = new ItemBuilder(enchant.getGuiMaterial(), enchant.getGuiName(), lore).colorize().build(); + this.grindingSwordInventory.updateItem(enchant.getGuiPosition(), new GuiItem(itemStack, event -> { + if(this.grindingSword.getEnchantLevel(enchant) >= enchant.getMaxLevel()) return; + Player player = (Player) event.getWhoClicked(); + ShardsUser shardsUser = ShardsAPI.getShardsUser(player); + if(!shardsUser.canAfford(cost)) { + //if(!XPUtils.hasEnoughExperience(player, cost)) { + player.sendMessage(CC.translate("&6&lGrinding &8" + Arrow.arrow() + " &cYou are missing " + (cost - shardsUser.getBalance()) + " shards")); + SoundUtils.tryPlayErrorSound(player); + return; + } + + shardsUser.removeShards(cost); + //XPUtils.removeExperience(player, cost); + player.sendMessage(CC.translate("&6&lGrinding &8" + Arrow.arrow() + " &aYour " + StringUtils.fixName(enchant.getId()) + " enchant has been upgraded")); + SoundUtils.tryPlaySuccessSound(player); + this.grindingSword.upgradeEnchant(enchant); + this.addEnchantToInventory(enchant); + player.setItemInHand(this.grindingSword.buildNewSword()); + //this.grindingSwordInventory.update(); + + CacheStorage cacheStorage = CacheStorage.getCacheStorage(); + cacheStorage.putPlayerInCache(player, this.grindingSword); + })); + } + +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/listeners/GrindingSwordDeathListener.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/listeners/GrindingSwordDeathListener.java new file mode 100644 index 0000000..604e131 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/listeners/GrindingSwordDeathListener.java @@ -0,0 +1,47 @@ +package net.crankedpvp.grindingsword.listeners; + +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.grindingsword.GrindingSwordAPI; +import net.crankedpvp.grindingsword.cache.CacheStorage; +import net.crankedpvp.grindingsword.cache.PlayerCache; +import net.crankedpvp.grindingsword.struct.GrindingSword; +import net.crankedpvp.spawners.events.StackedMobDeathEvent; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +public class GrindingSwordDeathListener implements Listener { + + @EventHandler + public void onDeath(StackedMobDeathEvent event) { + if (event.getDamager() != null) { + if(!(event.getDamager() instanceof Player)) return; + Player player = ((Player) event.getDamager()); + if(ItemUtils.isAirOrNull(player.getItemInHand())) return; + if(player.getInventory().getItemInHand().getType() != Material.GOLD_SWORD) return; + + CacheStorage cacheStorage = CacheStorage.getCacheStorage(); + if(cacheStorage.isCached(player)) { + PlayerCache playerCache = cacheStorage.getPlayerCache(player); + if(playerCache.hasBeenAmountOfTimeInSeconds(15)) { + cacheStorage.removePlayerFromCache(player); + return; + } + playerCache.setLastKilledInMs(System.currentTimeMillis()); + playerCache.addMobsKilled(1); + GrindingSword grindingSword = playerCache.getGrindingSword(); + grindingSword.getEnchantLevelsMap().forEach(((enchant, integer) -> { + if(grindingSword.getEnchantLevel(enchant) > 0) enchant.runStackedMobDeathEvent(event, integer); + })); + return; + } + + ItemStack itemStack = player.getItemInHand(); + if(!GrindingSwordAPI.isGrindingSword(itemStack)) return; + GrindingSword grindingSword = new GrindingSword(itemStack); + cacheStorage.putPlayerInCache(player, grindingSword); + } + } +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/listeners/OpenSwordInventoryListener.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/listeners/OpenSwordInventoryListener.java new file mode 100644 index 0000000..9ff681f --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/listeners/OpenSwordInventoryListener.java @@ -0,0 +1,33 @@ +package net.crankedpvp.grindingsword.listeners; + +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.grindingsword.GrindingSwordAPI; +import net.crankedpvp.grindingsword.GrindingSwordPlugin; +import net.crankedpvp.grindingsword.inventory.GrindingSwordInventory; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class OpenSwordInventoryListener implements Listener { + + private final GrindingSwordPlugin plugin; + public OpenSwordInventoryListener(GrindingSwordPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void openSwordInventoryAction(PlayerInteractEvent event) { + if(ItemUtils.isAirOrNull(event.getItem())) return; + if(event.getPlayer() == null) return; + if(!(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) return; + if(!event.getPlayer().isSneaking()) return; + + ItemStack itemStack = event.getItem(); + if(!GrindingSwordAPI.isGrindingSword(itemStack)) return; + + GrindingSwordInventory grindingSwordInventory = new GrindingSwordInventory(itemStack); + grindingSwordInventory.getUI().open(event.getPlayer()); + } +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/Enchant.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/Enchant.java new file mode 100644 index 0000000..a02f8a7 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/Enchant.java @@ -0,0 +1,23 @@ +package net.crankedpvp.grindingsword.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.spawners.events.StackedMobDeathEvent; +import org.bukkit.Material; +import org.bukkit.event.Listener; + +@Getter +@AllArgsConstructor +public abstract class Enchant implements Listener { + + private final String id; + private final int maxLevel; + private final Material guiMaterial; + private final String guiName; + private final String[] guiLore; + private final int guiPosition; + private final int[] prices; + + public abstract void runStackedMobDeathEvent(StackedMobDeathEvent event, int level); + +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/EnchantRegister.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/EnchantRegister.java new file mode 100644 index 0000000..c25b487 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/EnchantRegister.java @@ -0,0 +1,66 @@ +package net.crankedpvp.grindingsword.struct; + + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Maps; +import net.crankedpvp.grindingsword.GrindingSwordPlugin; +import net.crankedpvp.grindingsword.enchants.Inquisitive; +import net.crankedpvp.grindingsword.enchants.KeyGrind; +import net.crankedpvp.grindingsword.enchants.ShardGrind; +import org.apache.commons.lang.Validate; +import org.bukkit.event.Listener; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +public class EnchantRegister { + + private final GrindingSwordPlugin plugin; + + public EnchantRegister(GrindingSwordPlugin plugin) { + this.plugin = plugin; + } + + private final Map enchants = Maps.newConcurrentMap(); + + public void initialize() { + registerAll(new Enchant[] { + new ShardGrind(), new KeyGrind(), new Inquisitive() + }); + } + + public void registerAll(Enchant[] enchants) { + for (Enchant enchant : enchants) { + register(enchant); + } + } + + public void register(Enchant enchant) { + try { + this.enchants.put(enchant.getId().toLowerCase(), enchant); + Listener.class.isAssignableFrom(enchant.getClass()); + plugin.getServer().getPluginManager().registerEvents(enchant, plugin); + } catch (Exception var3) { + System.err.println("&8(&c!&8) Failed to register enchant, " + enchant.getId()); + } + } + + public boolean isEnchant(String name) { + return (getEnchant(name) != null); + } + + public Enchant getEnchant(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + return this.enchants.get(name.toLowerCase()); + } + + public Collection getEnchants() { + return Collections.unmodifiableCollection(this.enchants.values()); + } + public Enchant select(Collection enchantCollection) { + return (enchantCollection.size() > 0) ? ImmutableList.copyOf(enchantCollection).get(ThreadLocalRandom.current().nextInt(enchantCollection.size())) : null; + } +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/GrindingSword.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/GrindingSword.java new file mode 100644 index 0000000..8e72877 --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/struct/GrindingSword.java @@ -0,0 +1,69 @@ +package net.crankedpvp.grindingsword.struct; + +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.RomanNumeral; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.grindingsword.GrindingSwordAPI; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + +import java.util.Map; +import java.util.UUID; + +@Getter @Setter +public class GrindingSword { + + private final UUID swordUUID; + private final Map enchantLevelsMap; + + private final ItemStack itemStack; + + public GrindingSword(ItemStack itemStack) { + this.itemStack = itemStack; + this.swordUUID = GrindingSwordAPI.getGrindingSwordUUID(itemStack); + this.enchantLevelsMap = GrindingSwordAPI.getEnchantsOnGrindingSword(itemStack); + } + + public int getEnchantLevel(Enchant enchant) { + if(!hasEnchant(enchant)) return 0; + return enchantLevelsMap.get(enchant); + } + + public boolean hasEnchant(Enchant enchant) { + return enchantLevelsMap.containsKey(enchant); + } + + public void upgradeEnchant(Enchant enchant) { + if(!hasEnchant(enchant)) { + enchantLevelsMap.put(enchant, 1); + return; + } + int level = enchantLevelsMap.get(enchant); + enchantLevelsMap.put(enchant, level+1); + } + + public ItemStack buildNewSword() { + ItemBuilder itemBuilder = new ItemBuilder(Material.GOLD_SWORD, "&4&lGrinding&8 &8➥ &f&lSword", + "", "&7&oAn upgradeable sword used to", + "&7&omake the most out of grinding...", + "", + "&4Enchantments:"); + itemBuilder.addEnchantment(Enchantment.DAMAGE_ALL, 5); + itemBuilder.setUnbreakable(true); + + this.enchantLevelsMap.forEach((enchant, level) -> itemBuilder.addLoreLine(" &f• &c" + StringUtils.fixName(enchant.getId()) + " " + RomanNumeral.convertToRoman(level))); + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&7&nShift Right-Click&r &7to &fupgrade &7this weapon"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "grindingSword"); + nbtItem.setString("grindingSwordUUID", UUID.randomUUID().toString()); + nbtItem.addCompound("grindingSwordEnchants"); + this.enchantLevelsMap.forEach((enchant, level) -> nbtItem.getCompound("grindingSwordEnchants").setInteger(enchant.getId(), level)); + + return nbtItem.getItem(); + } +} diff --git a/GrindingSword/src/main/java/net/crankedpvp/grindingsword/tasks/GrindingRewardsTask.java b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/tasks/GrindingRewardsTask.java new file mode 100644 index 0000000..8c934de --- /dev/null +++ b/GrindingSword/src/main/java/net/crankedpvp/grindingsword/tasks/GrindingRewardsTask.java @@ -0,0 +1,14 @@ +package net.crankedpvp.grindingsword.tasks; + +import net.crankedpvp.grindingsword.cache.CacheStorage; +import net.crankedpvp.grindingsword.cache.PlayerCache; +import org.bukkit.scheduler.BukkitRunnable; + +public class GrindingRewardsTask extends BukkitRunnable { + + + @Override + public void run() { + CacheStorage.getCacheStorage().getPlayersInCache().values().forEach(PlayerCache::giveRewardsToPlayer); + } +} diff --git a/GrindingSword/src/main/resources/plugin.yml b/GrindingSword/src/main/resources/plugin.yml new file mode 100644 index 0000000..5310bd9 --- /dev/null +++ b/GrindingSword/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedGrindingSword +main: net.crankedpvp.grindingsword.GrindingSwordPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/Help/pom.xml b/Help/pom.xml new file mode 100644 index 0000000..e500ae0 --- /dev/null +++ b/Help/pom.xml @@ -0,0 +1,63 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Help + + + 8 + 8 + + + + + + Utils + net.crankedpvp + + + + Armor + net.crankedpvp + + + + Pets + net.crankedpvp + + + net.crankedpvp + AdminArmor + + + Enchants + net.crankedpvp + + + + Bosses + net.crankedpvp + + + + Masks + net.crankedpvp + + + net.crankedpvp + AdminWeapons + + + net.crankedpvp + StarItems + + + + \ No newline at end of file diff --git a/Help/src/main/java/net/crankedpvp/help/HelpPlugin.java b/Help/src/main/java/net/crankedpvp/help/HelpPlugin.java new file mode 100644 index 0000000..1d451b7 --- /dev/null +++ b/Help/src/main/java/net/crankedpvp/help/HelpPlugin.java @@ -0,0 +1,27 @@ +package net.crankedpvp.help; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.help.commands.HelpCommand; +import net.crankedpvp.help.struct.InventoryManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class HelpPlugin extends JavaPlugin { + + @Getter + private static HelpPlugin instance; + + @Getter + private InventoryManager inventoryManager; + + @Override + public void onEnable() { + instance = this; + + CommandManager commandManager = new CommandManager(this); + commandManager.register(new HelpCommand(this)); + + this.inventoryManager = new InventoryManager(this); + this.inventoryManager.initializeInventories(); + } +} diff --git a/Help/src/main/java/net/crankedpvp/help/commands/HelpCommand.java b/Help/src/main/java/net/crankedpvp/help/commands/HelpCommand.java new file mode 100644 index 0000000..afed703 --- /dev/null +++ b/Help/src/main/java/net/crankedpvp/help/commands/HelpCommand.java @@ -0,0 +1,70 @@ +package net.crankedpvp.help.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedmasks.inventory.MasksInventory; +import net.crankedpvp.crankedpets.inventory.PetsInventory; +import net.crankedpvp.crankedpets.inventory.PetsMainInventory; +import net.crankedpvp.help.HelpPlugin; +import net.crankedpvp.help.inventory.FactionsHelpInventory; +import net.crankedpvp.help.inventory.HelpInventory; +import net.crankedpvp.help.inventory.PvPHelpInventory; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +@Command("help") +@Alias("helpp") +public class HelpCommand extends CommandBase { + + private final HelpPlugin plugin; + public HelpCommand(HelpPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + HelpInventory helpInventory = this.plugin.getInventoryManager().getHelpInventory(); + helpInventory.getHelpMenuInventory().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("factions") + @Alias("faction") + public void factionsHelpCommand(final Player player) { + FactionsHelpInventory factionsHelpInventory = this.plugin.getInventoryManager().getFactionsHelpInventory(); + factionsHelpInventory.getFactionsHelpInventory().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("pvp") + public void pvpHelpCommand(final Player player) { + PvPHelpInventory pvPHelpInventory = this.plugin.getInventoryManager().getPvPHelpInventory(); + pvPHelpInventory.getPvpHelpMenu().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("pet") + @Alias("pets") + public void petHelpCommand(final Player player) { + PetsMainInventory petsInventory = this.plugin.getInventoryManager().getPetsInventory(); + petsInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("mask") + @Alias("masks") + public void maskHelpCommand(final Player player) { + MasksInventory masksInventory = this.plugin.getInventoryManager().getMasksInventory(); + masksInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("underworld") + @Alias({"uw", "uworld", "underw"}) + public void underworldHelpCommand(final Player player) { + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } +} diff --git a/Help/src/main/java/net/crankedpvp/help/inventory/FactionsHelpInventory.java b/Help/src/main/java/net/crankedpvp/help/inventory/FactionsHelpInventory.java new file mode 100644 index 0000000..0f56132 --- /dev/null +++ b/Help/src/main/java/net/crankedpvp/help/inventory/FactionsHelpInventory.java @@ -0,0 +1,55 @@ +package net.crankedpvp.help.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.help.HelpPlugin; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class FactionsHelpInventory { + + @Getter + private final Gui factionsHelpInventory; + + public FactionsHelpInventory() { + this.factionsHelpInventory = new Gui(6, "Factions Help Menu"); + this.factionsHelpInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.factionsHelpInventory.getFiller().fillBorder(new GuiItem(setupFillerItem())); + + this.setupInformationItem(); + this.setupGoBackButton(); + } + + private void setupGoBackButton() { + ItemBuilder itemBuilder = new ItemBuilder(Material.REDSTONE, "&cGo Back", "&7Click here to return to", + "&7the previous inventory"); + this.factionsHelpInventory.setItem(6, 1, new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + HelpInventory helpInventory = HelpPlugin.getInstance().getInventoryManager().getHelpInventory(); + helpInventory.getHelpMenuInventory().open(event.getWhoClicked()); + })); + } + + private ItemStack setupFillerItem() { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.BLACK.getWoolData(), "&cCranked&fPvP") + .colorize() + .build(); + } + + private void setupInformationItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.BOOK, "&6&lFactions Help Menu", + "&7This inventory will guide you through", + "&7the use of &f'Factions' &7on the server", + "", + "&7If you get stuck, or this menu does", + "&7not give a sufficient amount of", + "&7information, feel free to open a", + "&7support ticket in the cranked discord", + "", + "&fDiscord: &7discord.gg/crankedpvp"); + this.factionsHelpInventory.setItem(1, 5, new GuiItem(itemBuilder.colorize().build())); + } +} diff --git a/Help/src/main/java/net/crankedpvp/help/inventory/HelpInventory.java b/Help/src/main/java/net/crankedpvp/help/inventory/HelpInventory.java new file mode 100644 index 0000000..047574c --- /dev/null +++ b/Help/src/main/java/net/crankedpvp/help/inventory/HelpInventory.java @@ -0,0 +1,115 @@ +package net.crankedpvp.help.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.help.HelpPlugin; +import org.bukkit.Material; +import org.bukkit.Sound; + +public class HelpInventory { + + @Getter + private final Gui helpMenuInventory; + + public HelpInventory() { + this.helpMenuInventory = new Gui(1, "CrankedPvP Help Menu"); + this.helpMenuInventory.setDefaultClickAction(event -> event.setCancelled(true)); + setupInformationItem(); + setupPvPHelpItem(); + setupFactionsHelpItem(); + setupUnderworldHelpItem(); + setupStartingHelpItem(); + + } + + private void setupStartingHelpItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.PAPER, "&a&lGetting Started", + "&7This menu will show you the basics", + "&7of the features on the server", + "", + "&a&l(!) &f&nClick&r &fto get started" + ); + this.helpMenuInventory.setItem(1, new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + StartHelpInventory startHelpInventory = HelpPlugin.getInstance().getInventoryManager().getStartHelpInventory(); + startHelpInventory.getStartingHelpInventory().open(event.getWhoClicked()); + SoundUtils.playSoundIfPlayer(event.getWhoClicked(), Sound.CHEST_OPEN); + })); + } + + private void setupPvPHelpItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_SWORD, "&c&lPvP Help", + "&7This menu will show you the pvp", + "&7related features on this server", + "", + "&7PvP related features include, but", + "&7are not limited to: enchants, armor", + "&7sets, pets, bosses, masks", + "", + "&a&l(!) &f&nClick&r &fto view pvp help" + ); + this.helpMenuInventory.setItem(3, new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + PvPHelpInventory pvPHelpInventory = HelpPlugin.getInstance().getInventoryManager().getPvPHelpInventory(); + pvPHelpInventory.getPvpHelpMenu().open(event.getWhoClicked()); + SoundUtils.playSoundIfPlayer(event.getWhoClicked(), Sound.CHEST_OPEN); + })); + } + + private void setupFactionsHelpItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_SWORD, "&a&lFactions Help", + "&7This menu will show you the factions", + "&7related features on this server", + "", + "&7Faction related features include, but", + "&7are not limited to: shields, spawners", + "&7bases, grace period, logs and upgrades", + "", + "&a&l(!) &f&nClick&r &fto view factions help" + ); + this.helpMenuInventory.setItem(2, new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + FactionsHelpInventory factionsHelpInventory = HelpPlugin.getInstance().getInventoryManager().getFactionsHelpInventory(); + factionsHelpInventory.getFactionsHelpInventory().open(event.getWhoClicked()); + SoundUtils.playSoundIfPlayer(event.getWhoClicked(), Sound.CHEST_OPEN); + })); + } + + private void setupUnderworldHelpItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.EYE_OF_ENDER, "&c&lUnderworld Help", + "&7This menu will show you the underworld", + "&7related features on this server", + "", + "&7The underworld is a PvE zone where", + "&7players fight mobs & collect rewards", + "&7scaling up based on their underworld tier", + "", + "&7The higher underworld tier you are, the", + "&7better the rewards you will receive from", + "&7both underworld mobs and underworld chests", + "", + "&a&l(!) &f&nClick&r &fto view underworld help" + ); + this.helpMenuInventory.setItem(4, new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + SoundUtils.playSoundIfPlayer(event.getWhoClicked(), Sound.CHEST_OPEN); + })); + } + + private void setupInformationItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.BOOK, "&b&lHelp Menu", + "&7This inventory will guide you through", + "&7all of the features on the server", + "", + "&7If you get stuck, or this menu does", + "&7not give a sufficient amount of", + "&7information, feel free to open a", + "&7support ticket in the cranked discord", + "", + "&fDiscord: &7discord.gg/crankedpvp"); + this.helpMenuInventory.setItem(0, new GuiItem(itemBuilder.colorize().build())); + } +} diff --git a/Help/src/main/java/net/crankedpvp/help/inventory/PvPHelpInventory.java b/Help/src/main/java/net/crankedpvp/help/inventory/PvPHelpInventory.java new file mode 100644 index 0000000..7a2e825 --- /dev/null +++ b/Help/src/main/java/net/crankedpvp/help/inventory/PvPHelpInventory.java @@ -0,0 +1,236 @@ +package net.crankedpvp.help.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.adminarmor.inventory.AdminArmorInventory; +import net.crankedpvp.adminweapons.inventory.AdminWeaponsInventory; +import net.crankedpvp.bosses.inventory.BossesInventory; +import net.crankedpvp.crankedarmor.inventory.ArmorSetsInventory; +import net.crankedpvp.crankedenchants.inventories.MainEnchantsUI; +import net.crankedpvp.crankedmasks.inventory.MasksInventory; +import net.crankedpvp.crankedpets.inventory.PetsInventory; +import net.crankedpvp.crankedpets.inventory.PetsMainInventory; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.help.HelpPlugin; +import net.crankedpvp.staritems.inventory.StarItemsInventory; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class PvPHelpInventory { + + @Getter + private final Gui pvpHelpMenu; + + public PvPHelpInventory() { + this.pvpHelpMenu = new Gui(6, "PvP Help Menu"); + this.pvpHelpMenu.setDefaultClickAction(event -> event.setCancelled(true)); + this.pvpHelpMenu.getFiller().fillBorder(new GuiItem(setupFillerItem())); + + this.setupInformationItem(); + this.setupEnchantsItem(); + this.setupArmorSetsItem(); + this.setupMasksItem(); + this.setupBossesItem(); + this.setupPetsItem(); + this.setupStarItemsItem(); + this.setupAdminWeaponsItem(); + this.setupAdminArmorItem(); + this.setupGoBackButton(); + } + + private void setupGoBackButton() { + ItemBuilder itemBuilder = new ItemBuilder(Material.REDSTONE, "&cGo Back", "&7Click here to return to", + "&7the previous inventory"); + this.pvpHelpMenu.setItem(6, 1, new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + HelpInventory helpInventory = HelpPlugin.getInstance().getInventoryManager().getHelpInventory(); + helpInventory.getHelpMenuInventory().open(event.getWhoClicked()); + })); + } + + private void setupPetsItem() { + ItemBuilder itemBuilder = new ItemBuilder(SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvY2U4OTI4NjY5MjZiNGQzYjk4NmRhNzk3YTUxYWUxOGU3NjJlNmQ4YTZjNzg5N2Q4YmQ5MDc3MzY1Y2I4ZTBmYSJ9fX0=")); + itemBuilder.setName("&b&lPets"); + itemBuilder.setLore( + "&7Pets are &fphysical &7items which", + "&7players can use to gain a buff", + "", + "&7Each pet has an individual &ccooldown&7,", + "&7and also a &elevel&7. Pets cannot be used", + "&7while on cooldown. Once used, they gain", + "&7pet &fexperience&7. Once a pet has enough", + "&7experience, it levels up. Enhancing it's", + "&7pet &eabilities&7.", + "", + "&a&l(!) &f&nClick&r &fto view ALL pets"); + this.pvpHelpMenu.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + PetsMainInventory petsInventory = HelpPlugin.getInstance().getInventoryManager().getPetsInventory(); + petsInventory.getUI().open(event.getWhoClicked()); + })); + } + + private void setupEnchantsItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.BOOK, "&d&lEnchantments", + "&7Enchantments are items which can be", + "&7applied to &farmor/weapons/tools&7, each", + "&7enchantment useful for something &aunique", + "", + "&7Enchantments are usually used to create", + "&7a &f'God Set' &7which is an armor set that", + "&7has the best enchants on and can be used", + "&7to fight other players.", + "", + "&7There is a &climit &7on how many enchantments", + "&7you can put on an item, so make sure you", + "&7choose the &abest &7ones. The default limit", + "&7is &n9&r&7 enchants, however &f'Enchantment Orbs'", + "&7can allow you to apply &fmore enchantments.", + "", + "&a&l(!) &f&nClick&r &fto view ALL enchantments"); + this.pvpHelpMenu.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + MainEnchantsUI enchantsUI = HelpPlugin.getInstance().getInventoryManager().getEnchantsInventory(); + enchantsUI.getEnchantsGUI().open(event.getWhoClicked()); + })); + } + + private void setupArmorSetsItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_CHESTPLATE, "&e&lArmor Sets", + "&7Armor Sets are special sets that", + "&7players can &fequip &7to give them", + "&7special &fbuffs.", + "", + "&7In order for the &fspecial set &7to", + "&7work, you must wear &f&nALL&r &ffour pieces", + "&7of the armor set at the &fsame time", + "", + "&a&l(!) &f&nClick&r &fto view ALL sets"); + this.pvpHelpMenu.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + ArmorSetsInventory armorSetsInventory = new ArmorSetsInventory(((Player) event.getWhoClicked())); + armorSetsInventory.getUI().open(event.getWhoClicked()); + })); + } + + private void setupMasksItem() { + ItemBuilder itemBuilder = new ItemBuilder(SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNjM4YzUzZTY2ZjI4Y2YyYzdmYjE1MjNjOWU1ZGUxYWUwY2Y0ZDdhMWZhZjU1M2U3NTI0OTRhOGQ2ZDJlMzIifX19")); + itemBuilder.setName("&a&lMasks"); + itemBuilder.setLore( + "&7Masks are items that can be", + "&7applied onto any &fhelmet &7to give", + "&7it a &fvisual override", + "", + "&7There are different types of", + "&7masks, each with it's own", + "&eabilities &7and &fvisual overrides", + "", + "&a&l(!) &f&nClick&r &fto view ALL masks"); + this.pvpHelpMenu.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + MasksInventory masksInventory = HelpPlugin.getInstance().getInventoryManager().getMasksInventory(); + masksInventory.getUI().open(event.getWhoClicked()); + })); + } + + private void setupStarItemsItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.SPONGE, 1, (short) 1); + itemBuilder.setName("&d&lStar Items"); + itemBuilder.setLore( + "&7Star items are items that can be", + "&7applied onto any &fhelmet &7to give", + "&7it a &fvisual override", + "", + "&7There are different types of", + "&7star items, each with it's own", + "&eabilities &7and &fvisual overrides", + "", + "&a&l(!) &f&nClick&r &fto view ALL star items"); + this.pvpHelpMenu.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + StarItemsInventory starItemsInventory = HelpPlugin.getInstance().getInventoryManager().getStarItemsInventory(); + starItemsInventory.getUI().open(event.getWhoClicked()); + })); + } + + private void setupAdminWeaponsItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_SWORD); + itemBuilder.setName("&c&lAdmin Weapons"); + itemBuilder.setLore( + "&7Admin weapons are special weapons", + "&7that have individual abilities", + "", + "&7These admin weapons can be used with", + "&7any set type.", + "", + "&a&l(!) &f&nClick&r &fto view ALL admin weapons"); + this.pvpHelpMenu.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + AdminWeaponsInventory adminWeaponsInventory = HelpPlugin.getInstance().getInventoryManager().getAdminWeaponsInventory(); + adminWeaponsInventory.getUI().open(event.getWhoClicked()); + })); + } + + private void setupAdminArmorItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_CHESTPLATE); + itemBuilder.setName("&c&lAdmin Armor"); + itemBuilder.setLore( + "&7Admin armor are special armor", + "&7with intensified protection and", + "&7a range of impressive enchantments", + "", + "&7These pieces of admin armor can only", + "&7be used with the specified armor set type.", + "", + "&a&l(!) &f&nClick&r &fto view ALL admin armor"); + this.pvpHelpMenu.addItem(new GuiItem(itemBuilder.setGlowing().colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + AdminArmorInventory adminArmorInventory = HelpPlugin.getInstance().getInventoryManager().getAdminArmorInventory(); + adminArmorInventory.getUI().open(event.getWhoClicked()); + })); + } + + private void setupBossesItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.MONSTER_EGG, 1, (short) 51); + itemBuilder.setName("&6&lBosses"); + itemBuilder.setLore( + "&7Bosses are &cpowerful &7ai &7that", + "&cattack &7players and drop &fhigh tier", + "&7loot when they die.", + "", + "&7There are different &ftiers &7of bosses,", + "&7each having different &chealth&7, abilities", + "&7and loot drops.", + "", + "&a&l(!) &f&nClick&r &fto view ALL bosses"); + this.pvpHelpMenu.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + BossesInventory bossesInventory = HelpPlugin.getInstance().getInventoryManager().getBossesInventory(); + bossesInventory.getUI().open(event.getWhoClicked()); + })); + } + + private ItemStack setupFillerItem() { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.BLACK.getWoolData(), "&cCranked&fPvP") + .colorize() + .build(); + } + + private void setupInformationItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.BOOK, "&c&lPvP Help Menu", + "&7This inventory will guide you through", + "&7the pvp related features on the server", + "", + "&7If you get stuck, or this menu does", + "&7not give a sufficient amount of", + "&7information, feel free to open a", + "&7support ticket in the cranked discord", + "", + "&fDiscord: &7discord.gg/crankedpvp"); + this.pvpHelpMenu.setItem(1, 5, new GuiItem(itemBuilder.colorize().build())); + } +} diff --git a/Help/src/main/java/net/crankedpvp/help/inventory/StartHelpInventory.java b/Help/src/main/java/net/crankedpvp/help/inventory/StartHelpInventory.java new file mode 100644 index 0000000..6d60d8f --- /dev/null +++ b/Help/src/main/java/net/crankedpvp/help/inventory/StartHelpInventory.java @@ -0,0 +1,114 @@ +package net.crankedpvp.help.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.help.HelpPlugin; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class StartHelpInventory { + + @Getter + private final Gui startingHelpInventory; + + public StartHelpInventory() { + this.startingHelpInventory = new Gui(6, "PvP Help Menu"); + this.startingHelpInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.startingHelpInventory.getFiller().fillBorder(new GuiItem(setupFillerItem())); + + this.setupInformationItem(); + this.setupGoBackButton(); + + this.setupKitsButton(); + this.setupGKitsButton(); + + this.setupGrindingButton(); + } + + private void setupGrindingButton() { + ItemBuilder itemBuilder = new ItemBuilder(Material.BLAZE_ROD, "&6&lBlaze Grinding", + "&7Blaze grinding is where you kill", + "&7blazes and receive keys, money, and", + "&7exp in return.", + "", + "&7To get started, do the following;", + "&7- Open your starter bundle", + "&7- Execute /wild (or fly to an open space)", + "&7- Place a chunk buster down", + "&7- Place your blaze spawners down", + "&7- Kill blazes repetitively", + "&7- More kills -> more loot"); + this.startingHelpInventory.addItem(new GuiItem(itemBuilder.colorize().build())); + } + + private void setupKitsButton() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_CHESTPLATE, "&b&lKits", + "&7Kits are small &fsets of items &7that you", + "&7can claim through a &erank &7or permission", + "", + "&7When you first join the server, you will be", + "&7able to access and claim the default kit. This", + "&7is not a powerful kit however it will give you", + "&7basic items which allow you to progress quickly", + "", + "&7The most common kits are &e'Rank Kits'.", + "&7These kits give you very simple starting", + "&7items based on the rank you currently have", + "&7on the server", + "", + "&a&l(!) &f&nClick&r &fto view ALL kits"); + this.startingHelpInventory.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + ((Player) event.getWhoClicked()).performCommand("kit"); + })); + } + + private void setupGKitsButton() { + ItemBuilder itemBuilder = new ItemBuilder(Material.GOLD_HELMET, "&c&lGodly Kits", + "&7Godly Kits, or more commonly known as 'gkits',", + "&7are better sets of items which increase efficiency", + "", + "&7An example of a godly kit is an enchanted set of armor,", + "&7exceptionally fast tools and alchemist styled items", + "", + "&a&l(!) &f&nClick&r &fto view ALL gkits"); + this.startingHelpInventory.addItem(new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + ((Player) event.getWhoClicked()).performCommand("gkit"); + })); + } + + private void setupGoBackButton() { + ItemBuilder itemBuilder = new ItemBuilder(Material.REDSTONE, "&cGo Back", "&7Click here to return to", + "&7the previous inventory"); + this.startingHelpInventory.setItem(6, 1, new GuiItem(itemBuilder.colorize().build(), event -> { + event.getWhoClicked().closeInventory(); + HelpInventory helpInventory = HelpPlugin.getInstance().getInventoryManager().getHelpInventory(); + helpInventory.getHelpMenuInventory().open(event.getWhoClicked()); + })); + } + + private ItemStack setupFillerItem() { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.BLACK.getWoolData(), "&cCranked&fPvP") + .colorize() + .build(); + } + + private void setupInformationItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.BOOK, "&a&lStarting Help Menu", + "&7This inventory will guide you through", + "&7the starting features on the server", + "", + "&7If you get stuck, or this menu does", + "&7not give a sufficient amount of", + "&7information, feel free to open a", + "&7support ticket in the cranked discord", + "", + "&fDiscord: &7discord.gg/crankedpvp"); + this.startingHelpInventory.setItem(1, 5, new GuiItem(itemBuilder.colorize().build())); + } +} diff --git a/Help/src/main/java/net/crankedpvp/help/inventory/UnderworldHelpInventory.java b/Help/src/main/java/net/crankedpvp/help/inventory/UnderworldHelpInventory.java new file mode 100644 index 0000000..42de037 --- /dev/null +++ b/Help/src/main/java/net/crankedpvp/help/inventory/UnderworldHelpInventory.java @@ -0,0 +1,4 @@ +package net.crankedpvp.help.inventory; + +public class UnderworldHelpInventory { +} diff --git a/Help/src/main/java/net/crankedpvp/help/struct/InventoryManager.java b/Help/src/main/java/net/crankedpvp/help/struct/InventoryManager.java new file mode 100644 index 0000000..a4771cf --- /dev/null +++ b/Help/src/main/java/net/crankedpvp/help/struct/InventoryManager.java @@ -0,0 +1,52 @@ +package net.crankedpvp.help.struct; + +import lombok.Getter; +import net.crankedpvp.adminarmor.inventory.AdminArmorInventory; +import net.crankedpvp.adminweapons.inventory.AdminWeaponsInventory; +import net.crankedpvp.bosses.inventory.BossesInventory; +import net.crankedpvp.crankedenchants.inventories.MainEnchantsUI; +import net.crankedpvp.crankedmasks.inventory.MasksInventory; +import net.crankedpvp.crankedpets.inventory.PetsInventory; +import net.crankedpvp.crankedpets.inventory.PetsMainInventory; +import net.crankedpvp.help.HelpPlugin; +import net.crankedpvp.help.inventory.*; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.inventory.StarItemsInventory; + +@Getter +public class InventoryManager { + + + private final HelpPlugin plugin; + public InventoryManager(HelpPlugin plugin) { + this.plugin = plugin; + } + + private FactionsHelpInventory factionsHelpInventory; + private HelpInventory helpInventory; + private PvPHelpInventory pvPHelpInventory; + private StartHelpInventory startHelpInventory; + private BossesInventory bossesInventory; + private AdminArmorInventory adminArmorInventory; + private AdminWeaponsInventory adminWeaponsInventory; + private PetsMainInventory petsInventory; + private MasksInventory masksInventory; + private StarItemsInventory starItemsInventory; + private MainEnchantsUI enchantsInventory; + private UnderworldHelpInventory underworldHelpInventory; + + public void initializeInventories() { + this.factionsHelpInventory = new FactionsHelpInventory(); + this.helpInventory = new HelpInventory(); + this.pvPHelpInventory = new PvPHelpInventory(); + this.startHelpInventory = new StartHelpInventory(); + this.bossesInventory = new BossesInventory(); + this.adminArmorInventory = new AdminArmorInventory(); + this.adminWeaponsInventory = new AdminWeaponsInventory(); + this.petsInventory = new PetsMainInventory(); + this.masksInventory = new MasksInventory(); + this.starItemsInventory = StarItemsAPI.getStarItemsUI(); + this.enchantsInventory = new MainEnchantsUI(); + } + +} diff --git a/Help/src/main/resources/plugin.yml b/Help/src/main/resources/plugin.yml new file mode 100644 index 0000000..17e5924 --- /dev/null +++ b/Help/src/main/resources/plugin.yml @@ -0,0 +1,14 @@ +name: CrankedHelp +main: net.crankedpvp.help.HelpPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedArmor + - CrankedEnchants + - CrankedBosses + - CrankedPets + - CrankedMasks + - CrankedAdminWeapons + - CrankedAdminArmor \ No newline at end of file diff --git a/HolyWhitescrolls/pom.xml b/HolyWhitescrolls/pom.xml new file mode 100644 index 0000000..022d5d9 --- /dev/null +++ b/HolyWhitescrolls/pom.xml @@ -0,0 +1,45 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + HolyWhitescrolls + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + StarItems + + + net.crankedpvp + Masks + + + net.crankedpvp + Armor + + + net.crankedpvp + Arcade + + + net.crankedpvp + AdminWeapons + + + \ No newline at end of file diff --git a/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/HolyWhitescrollAPI.java b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/HolyWhitescrollAPI.java new file mode 100644 index 0000000..a6c913e --- /dev/null +++ b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/HolyWhitescrollAPI.java @@ -0,0 +1,58 @@ +package net.crankedpvp.holywhitescrolls; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class HolyWhitescrollAPI { + + public static boolean isHolyWhitescroll(ItemStack itemStack) { + if(itemStack == null) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + if(!nbtItem.hasKey("crankedCustomItem")) return false; + return nbtItem.getString("crankedCustomItem").equals("holyWhiteScroll"); + } + + public static boolean hasHolyWhitescroll(ItemStack itemStack) { + if(itemStack == null) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + if(!nbtItem.hasKey("holyWhiteScrollEquipped")) return false; + return nbtItem.getBoolean("holyWhiteScrollEquipped"); + } + + public static ItemStack removeHolyWhitescrollFromItem(ItemStack itemStack) { + if(itemStack == null) return null; + ItemBuilder itemBuilder = new ItemBuilder(itemStack); + List lore = itemBuilder.getLore(); + lore.removeIf(line -> line.equals(CC.translate("&f&lPROTECTED (&6&l*HOLY*&f&l)"))); + itemBuilder.setLore(lore); + itemBuilder.addLore("&c&lCORRUPT &7(Holy White Scrolls Blocked)"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setBoolean("holyWhiteScrollEquipped", false); + nbtItem.setBoolean("holyWhiteScrollCorrupt", true); + return nbtItem.getItem(); + } + + public static ItemStack addHolyWhitescrollToItem(ItemStack itemStack) { + if(itemStack == null) return null; + ItemBuilder itemBuilder = new ItemBuilder(itemStack); + itemBuilder.addLore("&f&lPROTECTED (&6&l*HOLY*&f&l)"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setBoolean("holyWhiteScrollEquipped", true); + return nbtItem.getItem(); + } + + public static boolean isCorrupt(ItemStack itemStack) { + if(itemStack == null) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + return nbtItem.getBoolean("holyWhiteScrollCorrupt"); + } + + +} diff --git a/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/HolyWhitescrollsPlugin.java b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/HolyWhitescrollsPlugin.java new file mode 100644 index 0000000..180b27d --- /dev/null +++ b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/HolyWhitescrollsPlugin.java @@ -0,0 +1,28 @@ +package net.crankedpvp.holywhitescrolls; + +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.holywhitescrolls.commands.HolyWhitescrollCommand; +import net.crankedpvp.holywhitescrolls.listeners.ApplyHolyWhitescroll; +import net.crankedpvp.holywhitescrolls.listeners.PlayerDeathListener; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class HolyWhitescrollsPlugin extends JavaPlugin { + + @Override + public void onEnable() { + + CommandManager commandManager = new CommandManager(this); + commandManager.register(new HolyWhitescrollCommand()); + + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new ApplyHolyWhitescroll(), this); + pluginManager.registerEvents(new PlayerDeathListener(this), this); + + } + + @Override + public void onDisable() { + } + +} diff --git a/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/commands/HolyWhitescrollCommand.java b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/commands/HolyWhitescrollCommand.java new file mode 100644 index 0000000..8db32ea --- /dev/null +++ b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/commands/HolyWhitescrollCommand.java @@ -0,0 +1,38 @@ +package net.crankedpvp.holywhitescrolls.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.holywhitescrolls.struct.CustomItemBuilder; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Command("holyws") +@Alias({"chws", "crankedholywhitescroll", "holywhitescroll"}) +public class HolyWhitescrollCommand extends CommandBase { + + @Default + @Permission("cranked.admin") + public void defaultCommand(final CommandSender sender) { + + } + + @SubCommand("give") + @WrongUsage("&c/holyws give ") + @Permission("cranked.admin") + public void giveCommand(final CommandSender sender, @Completion("#players") final Player receiver, @Optional Integer amount) { + if(amount == null) amount = 1; + ItemStack itemStack = CustomItemBuilder.buildHolyWhiteScroll(amount); + receiver.getInventory().addItem(itemStack); + } + + @SubCommand("water") + @Alias("holywater") + @WrongUsage("&c/holyws water ") + @Permission("cranked.admin") + public void holyWaterCommand(final CommandSender sender, @Completion("#players") final Player receiver, Integer amount, Integer max) { + if(amount == null) amount = 1; + ItemStack itemStack = CustomItemBuilder.buildHolyWater(amount, max); + receiver.getInventory().addItem(itemStack); + } +} diff --git a/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/listeners/ApplyHolyWhitescroll.java b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/listeners/ApplyHolyWhitescroll.java new file mode 100644 index 0000000..20ce437 --- /dev/null +++ b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/listeners/ApplyHolyWhitescroll.java @@ -0,0 +1,58 @@ +package net.crankedpvp.holywhitescrolls.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryClickUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.holywhitescrolls.HolyWhitescrollAPI; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class ApplyHolyWhitescroll implements Listener { + + @EventHandler + public void applyHolyWhitescroll(InventoryClickEvent event) { + if(event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR || event.getCursor() == null || event.getCursor().getType() == Material.AIR) return; + Player player = (Player) event.getWhoClicked(); + + if(!HolyWhitescrollAPI.isHolyWhitescroll(event.getCursor())) return; + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + event.setCancelled(true); + if(!ItemUtils.isWeapon(event.getCurrentItem()) && !ItemUtils.isArmor(event.getCurrentItem())) { + player.sendMessage(CC.translate("&c&l(!) &cYou cannot apply a holy white scroll to this item")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(HolyWhitescrollAPI.hasHolyWhitescroll(event.getCurrentItem())) { + player.sendMessage(CC.translate("&c&l(!) &cThere is already a holy white scroll equipped on this item")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(HolyWhitescrollAPI.isCorrupt(event.getCurrentItem())) { + player.sendMessage(CC.translate("&c&l(!) &cThis item is corrupt and no more holy white scrolls can be applied")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + + ItemStack cursor = event.getCursor(); + int amount = cursor.getAmount(); + if (amount <= 1) { + event.setCursor(null); + } else { + cursor.setAmount(amount - 1); + event.setCursor(cursor); + } + + event.setCurrentItem(HolyWhitescrollAPI.addHolyWhitescrollToItem(event.getCurrentItem())); + player.sendMessage(CC.translate("&a&l(!) &aYou have successfully applied a holy white scroll to this item")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } +} diff --git a/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/listeners/PlayerDeathListener.java b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/listeners/PlayerDeathListener.java new file mode 100644 index 0000000..b2f03ca --- /dev/null +++ b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/listeners/PlayerDeathListener.java @@ -0,0 +1,163 @@ +package net.crankedpvp.holywhitescrolls.listeners; + +import net.crankedpvp.adminweapons.AdminWeaponsAPI; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.holywhitescrolls.HolyWhitescrollAPI; +import net.crankedpvp.holywhitescrolls.HolyWhitescrollsPlugin; +import net.crankedpvp.staritems.StarItemsAPI; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class PlayerDeathListener implements Listener { + + private final HolyWhitescrollsPlugin plugin; + private final List disabledWorlds = new ArrayList<>(); + + public PlayerDeathListener(HolyWhitescrollsPlugin plugin) { + this.plugin = plugin; + this.disabledWorlds.add("world_nether"); + this.disabledWorlds.add("world_duels"); + //this.disabledWorlds.add(ArcadeAPI.WORLD_NAME); + } + + private final List negatedItems = new ArrayList<>(); + + @EventHandler(priority = EventPriority.LOWEST) + public void playerDeathListener(PlayerDeathEvent event) { + if(event.getEntity() == null) return; + if (this.disabledWorlds.contains(event.getEntity().getWorld().getName())) return; + final Player victim = event.getEntity(); + final Player attacker = event.getEntity().getKiller(); + + this.negatedItems.clear(); + + List holiedItems = new ArrayList<>(event.getDrops()) + .stream() + .filter(HolyWhitescrollAPI::hasHolyWhitescroll) + .collect(Collectors.toList()); + if(holiedItems.isEmpty()) return; + event.getDrops().removeAll(holiedItems); + List finalHoliedItems = holiedItems.stream().map(HolyWhitescrollAPI::removeHolyWhitescrollFromItem).collect(Collectors.toList()); + + + if(CrankedMasksAPI.hasMaskEquipped(attacker, CrankedMasks.getInstance().getMasksRegister().getMaskFromID("monopoly"))) { + for(ItemStack itemStack : finalHoliedItems) { + if(Math.random() > 0.33) continue; //33% chance to negate + tryAddNegatedItem(attacker, itemStack, "&3&l[&b&lMonopoly Mask&3&l]"); + } + } + + + /* + if(CrankedMasksAPI.hasMaskEquipped(attacker, CrankedMasks.getInstance().getMasksRegister().getMaskFromID("davyjones"))) { + for(ItemStack itemStack : finalHoliedItems) { + if(Math.random() > 0.33) continue; //33% chance to negate + tryAddNegatedItem(attacker, itemStack, "&d&l[&5&lDavy Jones&d&l]"); + } + } + + ArmorSet armorSet = CrankedArmorAPI.getCurrentArmorSet(attacker); + if (armorSet != null && armorSet.getID().equals("pirate")) { + if (CrankedArmorAPI.isPlayersWeaponSameAsSet(attacker)) { + for (ItemStack itemStack : finalHoliedItems) { + if (Math.random() > 0.15) continue; + tryAddNegatedItem(attacker, itemStack, "&4&l[&c&lPirate Set&4&l]"); + } + } + } + + */ + + + + if (StarItemsAPI.playerHasStarItemInCache(attacker)) { + /* + if(StarItemsAPI.playerHasStarItem(attacker, "chroma")) { + for(ItemStack itemStack : finalHoliedItems) { + tryAddNegatedItem(attacker, itemStack, "&f&l[&c&lC&6&lH&e&lR&a&lO&b&lM&d&lA&f&l]"); + } + } + + */ + + if(StarItemsAPI.playerHasStarItem(attacker, "galacticvisor")) { + for(ItemStack itemStack : finalHoliedItems) { + if(Math.random() > 0.75) continue; //75% chance to negate + tryAddNegatedItem(attacker, itemStack, "&d&l[&5&lGalactic Visor&d&l]"); + } + } + + if(StarItemsAPI.playerHasStarItem(attacker, "goldeneyebandage")) { + for(ItemStack itemStack : finalHoliedItems) { + if(Math.random() > 0.15) continue; //15% chance to negate + tryAddNegatedItem(attacker, itemStack, "&e&l[&6&lGolden Eye Bandage&e&l]"); + } + } + + if(StarItemsAPI.playerHasStarItem(attacker, "gloopgetaway")) { + for(ItemStack itemStack : finalHoliedItems) { + if(Math.random() > 0.1) continue; //10% chance to negate + tryAddNegatedItem(attacker, itemStack, "&2&l[&a&lGloop Getaway&2&l]"); + } + } + + if(StarItemsAPI.playerHasStarItem(attacker, "olympus")) { + for(ItemStack itemStack : finalHoliedItems) { + if(Math.random() > 0.66) continue; //66% chance to negate + tryAddNegatedItem(attacker, itemStack, "&f&l[&3&lO&b&ll&3&ly&b&lm&3&lp&b&lu&3&ls&f&l]"); + } + } + } + + + /* + if(AdminWeaponsAPI.hasAdminWeaponEquipped(attacker, "hellforge")) { + for(ItemStack itemStack : finalHoliedItems) { + if(Math.random() > 0.15) continue; //15% chance to negate + tryAddNegatedItem(attacker, itemStack, "&c&l[&4&lHELLFORGE&c&l]"); + } + } + */ + + if(AdminWeaponsAPI.hasAdminWeaponEquipped(attacker, "shigenjo")) { + for(ItemStack itemStack : finalHoliedItems) { + if(Math.random() > 0.15) continue; //15% chance to negate + tryAddNegatedItem(attacker, itemStack, CC.translateAlternating("[Shigenjo]", "&b&l", "&f&l")); + } + } + + finalHoliedItems.removeAll(this.negatedItems); + event.getDrops().addAll(this.negatedItems); + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + finalHoliedItems.forEach(itemStack -> { + victim.getInventory().addItem(itemStack); + victim.sendMessage(CC.translate("&a&l+ &6&l*HOLY* PROTECTION &8➥ " + itemStack.getItemMeta().getDisplayName())); + }); + this.negatedItems.forEach(itemStack -> { + victim.sendMessage(CC.translate("&c&l- *HOLY* NEGATED &8➥ " + itemStack.getItemMeta().getDisplayName())); + }); + }, 1L); + } + + private void tryAddNegatedItem(Player player, ItemStack itemStack, String reason) { + if(this.negatedItems.contains(itemStack)) return; + this.negatedItems.add(itemStack); + player.sendMessage(CC.translate("&c&l+ *HOLY* NEGATION " + reason + " &8➥ " + itemStack.getItemMeta().getDisplayName())); + } + + +} diff --git a/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/struct/CustomItemBuilder.java b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/struct/CustomItemBuilder.java new file mode 100644 index 0000000..41ac3c0 --- /dev/null +++ b/HolyWhitescrolls/src/main/java/net/crankedpvp/holywhitescrolls/struct/CustomItemBuilder.java @@ -0,0 +1,64 @@ +package net.crankedpvp.holywhitescrolls.struct; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class CustomItemBuilder { + + public static ItemStack buildHolyWhiteScroll(int amount) { + ItemStack itemStack = new ItemBuilder(Material.PAPER, "&6&lHoly White Scroll", + "&7A legendary reward that can be", + "&7applied to armor & weapons to", + "&7give a 100% chance of not losing", + "&7the blessed item upon death.", + "", + "&7However, there are some items which", + "&7can block your holy white scroll", + "&7from saving your item upon death.", + "", + "&7&oPlace this on an item to protect it." + ) + .setAmount(amount) + .colorize() + .build(); + /* + ItemStack itemStack = new ItemBuilder(Material.PAPER, "&8» &6&lHoly White Scroll&8 «", + "", + "&fThis scroll can be applied to any piece", + "&fof equipement and gives a 100% chance", + "&fof not losing the item on death.", + "", + "&fThe item must have a &2&lWhite Scroll", + "&fapplied on it already.", + "", + "&7&oPlace this on an item to protect it." + ) + .setAmount(amount) + .colorize() + .build(); + + */ + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("crankedCustomItem", "holyWhiteScroll"); + return nbtItem.getItem(); + } + + public static ItemStack buildHolyWater(int amount, int max) { + ItemStack itemStack = new ItemBuilder(Material.PAPER, "&6&lHoly Water [&eMax: " + max + "&6&l]", + "&eA rare consumable that increases", + "ðe amount of holy white scrolls", + "&ewhich can be applied to an item." + ) + .setAmount(amount) + .colorize() + .build(); + + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("crankedCustomItem", "holyWater"); + nbtItem.setInteger("holyWaterMax", max); + return nbtItem.getItem(); + } +} diff --git a/HolyWhitescrolls/src/main/resources/plugin.yml b/HolyWhitescrolls/src/main/resources/plugin.yml new file mode 100644 index 0000000..e3df6a3 --- /dev/null +++ b/HolyWhitescrolls/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedHolyWhitescrolls +main: net.crankedpvp.holywhitescrolls.HolyWhitescrollsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/HubCore/pom.xml b/HubCore/pom.xml new file mode 100644 index 0000000..97cf04e --- /dev/null +++ b/HubCore/pom.xml @@ -0,0 +1,26 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + HubCore + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + + \ No newline at end of file diff --git a/HubCore/src/main/java/net/crankedpvp/hubcore/HubCore.java b/HubCore/src/main/java/net/crankedpvp/hubcore/HubCore.java new file mode 100644 index 0000000..cd4b076 --- /dev/null +++ b/HubCore/src/main/java/net/crankedpvp/hubcore/HubCore.java @@ -0,0 +1,21 @@ +package net.crankedpvp.hubcore; + +import lombok.Getter; +import net.crankedpvp.hubcore.listeners.NoDamageListener; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class HubCore extends JavaPlugin { + @Getter + private static HubCore instance; + private PluginManager pluginManager; + public void onEnable() { + instance = this; + this.pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new NoDamageListener(), this); + } + + public void onDisable() { + instance = null; + } +} diff --git a/HubCore/src/main/java/net/crankedpvp/hubcore/listeners/NoDamageListener.java b/HubCore/src/main/java/net/crankedpvp/hubcore/listeners/NoDamageListener.java new file mode 100644 index 0000000..0216f46 --- /dev/null +++ b/HubCore/src/main/java/net/crankedpvp/hubcore/listeners/NoDamageListener.java @@ -0,0 +1,15 @@ +package net.crankedpvp.hubcore.listeners; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class NoDamageListener implements Listener { + @EventHandler + public void onDamage(EntityDamageEvent event) { + if (event.getEntity() instanceof Player) { + event.setCancelled(true); + } + } +} diff --git a/HubCore/src/main/resources/plugin.yml b/HubCore/src/main/resources/plugin.yml new file mode 100644 index 0000000..dbe7023 --- /dev/null +++ b/HubCore/src/main/resources/plugin.yml @@ -0,0 +1,4 @@ +name: CrankedHubCore +main: net.crankedpvp.hubcore.HubCore +version: 1.0 +commands: diff --git a/HypeBoxes/pom.xml b/HypeBoxes/pom.xml new file mode 100644 index 0000000..9a41b47 --- /dev/null +++ b/HypeBoxes/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + + net.crankedpvp + ProjectCranked + 1.0 + + + net.crankedpvp.hypeboxes + HypeBoxes + + + 8 + 8 + UTF-8 + + + + + net.crankedpvp + Utils + + + + \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/HypeboxesPlugin.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/HypeboxesPlugin.java new file mode 100644 index 0000000..b95e633 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/HypeboxesPlugin.java @@ -0,0 +1,81 @@ +package net.crankedpvp.hypeboxes; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.hypeboxes.commands.HypeBoxCommand; +import net.crankedpvp.hypeboxes.commands.ViewBattleOpenCommand; +import net.crankedpvp.hypeboxes.commands.ViewHypeboxOpenCommand; +import net.crankedpvp.hypeboxes.inventory.HypeBoxAnimationInventory; +import net.crankedpvp.hypeboxes.inventory.HypeboxBattleInventory; +import net.crankedpvp.hypeboxes.language.FileHandler; +import net.crankedpvp.hypeboxes.listeners.HypeboxOpenListener; +import net.crankedpvp.hypeboxes.listeners.HypeboxPreviewListener; +import net.crankedpvp.hypeboxes.struct.HypeBoxManager; +import net.crankedpvp.hypeboxes.struct.HypeBoxRegister; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +public class HypeboxesPlugin extends JavaPlugin { + + @Getter + private static HypeboxesPlugin instance; + + @Getter + private FileHandler fileHandler; + + @Getter + private HypeBoxRegister hypeBoxRegister; + + @Getter + private HypeBoxManager hypeBoxManager; + + @Getter + private CommandManager commandManager; + + @Getter + private Map hypeboxesBeingOpened; + + @Getter + private Map hypeboxBattles; + + + @Override + public void onEnable() { + + instance = this; + + this.fileHandler = new FileHandler(this); + this.fileHandler.load(); + + this.hypeBoxRegister = new HypeBoxRegister(this); + this.hypeBoxManager = new HypeBoxManager(this); + + this.hypeBoxRegister.clearHypeboxMap(); + this.hypeBoxManager.createDefaultConfig("-example"); + this.hypeBoxManager.initializeAll(); + + this.commandManager = new CommandManager(this); + this.registerCommandCompletion(); + this.commandManager.register(new HypeBoxCommand(this)); + this.commandManager.register(new ViewHypeboxOpenCommand(this)); + this.commandManager.register(new ViewBattleOpenCommand(this)); + + this.hypeboxesBeingOpened = new HashMap<>(); + this.hypeboxBattles = new HashMap<>(); + + this.registerListeners(); + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new HypeboxOpenListener(this), this); + pluginManager.registerEvents(new HypeboxPreviewListener(this), this); + } + + public void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#hypeboxes", input -> this.hypeBoxRegister.getHypeboxesAsIDs()); + } +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/HypeBoxCommand.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/HypeBoxCommand.java new file mode 100644 index 0000000..1f1847e --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/HypeBoxCommand.java @@ -0,0 +1,313 @@ +package net.crankedpvp.hypeboxes.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.inventory.AdminHypeboxInventory; +import net.crankedpvp.hypeboxes.inventory.HypeboxPreBattleInventory; +import net.crankedpvp.hypeboxes.language.Language; +import net.crankedpvp.hypeboxes.struct.HypeBox; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +@Command("hypebox") +@Alias({"hb"}) +public class HypeBoxCommand extends CommandBase { + + private final HypeboxesPlugin plugin; + public HypeBoxCommand(HypeboxesPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + + if(player.hasPermission("cranked.admin")) { + sendAdminHelpMessage(player); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + return; + } + } + + @SubCommand("help") + @WrongUsage("&eUsage: /hb help") + @Permission("cranked.admin") + public void helpCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + sendAdminHelpMessage(player); + } + + @SubCommand("create") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb create [amount of rewards]") + public void createCommand(CommandSender commandSender, String lootbox) { + Player player = (Player) commandSender; + if(plugin.getHypeBoxRegister().isHypebox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.ALREADY_HYPEBOX.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(player.getItemInHand() == null) { + plugin.getHypeBoxManager().createHypebox(lootbox); + } else { + plugin.getHypeBoxManager().createHypeboxFromItemStack(player.getItemInHand(), lootbox); + } + player.sendMessage(Language.PREFIX.getMessage() + Language.CREATED_HYPEBOX.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + plugin.registerCommandCompletion(); + } + + @SubCommand("delete") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb delete ") + public void deleteCommand(CommandSender commandSender, @Completion("#hypeboxes") String lootbox) { + Player player = (Player) commandSender; + if(!plugin.getHypeBoxRegister().isHypebox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + player.sendMessage(Language.PREFIX.getMessage() + Language.DELETED_HYPEBOX.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.LAVA_POP, 2.0F, 2.0F); + plugin.getHypeBoxManager().deleteConfig(lootbox); + plugin.getHypeBoxRegister().removeHypebox(lootbox); + } + + @SubCommand("disable") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb disable ") + public void disableCommand(CommandSender commandSender, @Completion("#hypeboxes") String lootbox) { + Player player = (Player) commandSender; + + if (!this.plugin.getHypeBoxRegister().isHypebox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + File file = new File(this.plugin.getDataFolder() + "/Hypeboxes/" + lootbox + ".yml"); + if (file.renameTo(new File(this.plugin.getDataFolder() + "/Hypeboxes/-" + lootbox + ".yml"))) { + this.plugin.getHypeBoxRegister().removeHypebox(lootbox); + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_DISABLED.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 2.0F); + } + } + + @SubCommand("enable") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb enable ") + public void enableCommand(CommandSender commandSender, @Completion("#hypeboxes") String lootbox) { + Player player = (Player) commandSender; + + if (this.plugin.getHypeBoxRegister().isHypebox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.ALREADY_HYPEBOX.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + File file = new File(this.plugin.getDataFolder() + "/Hypeboxes/-" + lootbox + ".yml"); + if (file.renameTo(new File(this.plugin.getDataFolder() + "/Hypeboxes/" + lootbox + ".yml"))) { + this.plugin.getHypeBoxManager().initialize(lootbox); + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_ENABLED.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + } + + @SubCommand("reload") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb reload [lootbox]") + public void reloadCommand(CommandSender commandSender, @Optional @Completion("#hypeboxes") String lootbox) { + Player player = (Player) commandSender; + + if(lootbox == null) { + player.sendMessage(Language.PREFIX.getMessage() + Language.RELOADED_ALL.getMessage()); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + this.plugin.getHypeBoxRegister().clearHypeboxMap(); + this.plugin.getHypeBoxManager().initializeAll(); + this.plugin.getFileHandler().load(); + return; + } + if (this.plugin.getHypeBoxRegister().getLootboxes().containsKey(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.RELOADED_SINGULAR.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + this.plugin.getHypeBoxRegister().removeHypebox(lootbox); + this.plugin.getHypeBoxManager().initialize(lootbox); + return; + } + player.sendMessage(Language.HYPEBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + + @SubCommand("list") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb list") + public void listCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + + AdminHypeboxInventory adminLootboxInventory = new AdminHypeboxInventory(player, this.plugin); + adminLootboxInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("give") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb give [amount]") + public void giveCommand(CommandSender commandSender, @Completion("#players")Player player, @Completion("#hypeboxes") String lootbox, @Optional Integer amount) { + if(amount == null) amount = 1; + + if(!player.isOnline()) { + player.sendMessage(Language.PREFIX.getMessage() + CC.translate("&cThat player is not online")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(!this.plugin.getHypeBoxRegister().isHypebox(lootbox)) { + commandSender.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + //sender.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + this.plugin.getHypeBoxManager().giveHypebox(player, this.plugin.getHypeBoxRegister().getHypebox(lootbox), amount); + commandSender.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_GIVEN.getMessage().replace("%lootbox%", lootbox)); + //sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + //player.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_RECEIVED.getMessage().replace("%lootbox%", CC.translate(this.plugin.getHypeBoxRegister().getHypebox(lootbox).getDisplayName()))); + } + + @SubCommand("giveall") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb giveall [amount]") + public void giveCommand(CommandSender commandSender, @Completion("#hypeboxes") String lootbox, @Optional Integer amount) { + if(amount == null) amount = 1; + + if(!this.plugin.getHypeBoxRegister().isHypebox(lootbox)) { + commandSender.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + SoundUtils.tryPlayErrorSound(commandSender); + return; + } + + commandSender.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_GIVEN.getMessage().replace("%lootbox%", lootbox)); + SoundUtils.tryPlaySuccessSound(commandSender); + + final Map ipMap = new HashMap<>(); + for (final Player p : Bukkit.getOnlinePlayers()) { + if(commandSender instanceof Player) { + if(p.getUniqueId().toString().equals(((Player) commandSender).getUniqueId().toString())) { + continue; + } + } + final String ip = p.getAddress().getAddress().toString(); + if (ipMap.containsKey(ip) && ipMap.get(ip) > 0) { + continue; + } + + this.plugin.getHypeBoxManager().giveHypebox(p, this.plugin.getHypeBoxRegister().getHypebox(lootbox), amount); + p.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_RECEIVED.getMessage().replace("%lootbox%", CC.translate(this.plugin.getHypeBoxRegister().getHypebox(lootbox).getDisplayName()))); + + p.playSound(p.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + ipMap.put(ip, ipMap.getOrDefault(ip, 0) + 1); + } + } + + + @SubCommand("addreward") + @Alias({"additem", "addloot"}) + @Permission("cranked.admin") + @WrongUsage("&eUsage: /hb addreward ") + public void addItemCommand(CommandSender commandSender, @Completion("#hypeboxes") String lootbox, Double chance, Double value) { + this.plugin.getHypeBoxManager().addItem((Player)commandSender, lootbox, chance, value); + } + + @SubCommand("removereward") + @Alias({"removeitem", "removeloot"}) + @Permission("cranked.admin") + public void removeItemCommand(CommandSender commandSender, @Completion("#hypeboxes") String lootbox) { + Player player = (Player)commandSender; + this.plugin.getHypeBoxManager().removeItemFromHypebox(player, player.getItemInHand(), lootbox); + } + + @SubCommand("clearrewardsinallhypeboxes") + @Permission("*") + public void clear(CommandSender commandSender) { + if(commandSender instanceof Player) return; + this.plugin.getHypeBoxRegister().getLootboxes().forEach((lootboxName, lootbox) -> { + lootbox.getRewards().clear(); + + File file = new File(this.plugin.getDataFolder() + "/Hypeboxes/" + lootboxName + ".yml"); + if (file.exists()) { + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file); + yamlConfiguration.set("rewards", null); + try { + yamlConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + commandSender.sendMessage(CC.translate("&aSuccessfully cleared all lootbox rewards")); + + } + + @SubCommand("half") + @Alias({"leftorright", "halfgen", "randomhalf"}) + @WrongUsage("/hb half [left/right]") + @Permission("cranked.admin") + public void giveHalf(final Player player, String lootbox, @Optional String half) { + + if(!this.plugin.getHypeBoxRegister().isHypebox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + SoundUtils.tryPlayErrorSound(player); + return; + } + + HypeBox lootboxObject = this.plugin.getHypeBoxRegister().getHypebox(lootbox); + + if(half == null) { + player.getInventory().addItem(lootboxObject.buildLeftOrRightHalf()); + return; + } + half = half.toLowerCase(Locale.ROOT).equals("left") ? "left" : "right"; + player.getInventory().addItem(lootboxObject.buildHalf(half)); + player.sendMessage(CC.translate("&aGiven " + half + " half for " + lootbox)); + } + + @SubCommand("battle") + public void battle(final Player player) { + HypeboxPreBattleInventory hypeboxPreBattleInventory = new HypeboxPreBattleInventory(player); + hypeboxPreBattleInventory.getUI().open(player); + } + + private void sendAdminHelpMessage(Player player) { + player.sendMessage(""); + player.sendMessage(CC.translate("&cCranked&fPvP &8| &cHypeboxes")); + player.sendMessage(CC.translate("&c[] &8- &fOptional Argument")); + player.sendMessage(CC.translate("&4<> &8- &fRequired Argument")); + player.sendMessage(""); + player.sendMessage(CC.translate(" &c* &f/hb create ")); + player.sendMessage(CC.translate(" &c* &f/hb delete ")); + player.sendMessage(CC.translate(" &c* &f/hb enable ")); + player.sendMessage(CC.translate(" &c* &f/hb disable ")); + player.sendMessage(CC.translate(" &c* &f/hb additem ")); + player.sendMessage(CC.translate(" &c* &f/hb removeitem ")); + player.sendMessage(CC.translate(" &c* &f/hb reload [lootbox]")); + player.sendMessage(CC.translate(" &c* &f/hb list")); + player.sendMessage(CC.translate(" &c* &f/hb give [amount]")); + player.sendMessage(CC.translate(" &c* &f/hb giveall [amount]")); + player.sendMessage(""); + } +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/ViewBattleOpenCommand.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/ViewBattleOpenCommand.java new file mode 100644 index 0000000..b82730d --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/ViewBattleOpenCommand.java @@ -0,0 +1,35 @@ +package net.crankedpvp.hypeboxes.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.inventory.HypeboxBattleInventory; +import org.bukkit.entity.Player; + +import java.util.UUID; + +@Command("viewbattleopen") +public class ViewBattleOpenCommand extends CommandBase { + + private final HypeboxesPlugin plugin; + public ViewBattleOpenCommand(HypeboxesPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player, String crateID) { + if(!this.plugin.getHypeboxBattles().containsKey(UUID.fromString(crateID))) return; + + HypeboxBattleInventory hypeboxBattleInventory = this.plugin.getHypeboxBattles().get(UUID.fromString(crateID)); + if(!hypeboxBattleInventory.isActive()) { + player.sendMessage(CC.translate("&4&lHypebox Battles &8" + Arrow.arrow() + " &eThis hype box battle has finished being opened")); + SoundUtils.tryPlayErrorSound(player); + return; + } + this.plugin.getHypeboxBattles().get(UUID.fromString(crateID)).getUI().open(player); + } +} \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/ViewHypeboxOpenCommand.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/ViewHypeboxOpenCommand.java new file mode 100644 index 0000000..1ccaf91 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/commands/ViewHypeboxOpenCommand.java @@ -0,0 +1,35 @@ +package net.crankedpvp.hypeboxes.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.inventory.HypeBoxAnimationInventory; +import org.bukkit.entity.Player; + +import java.util.UUID; + +@Command("viewhypeboxopen") +public class ViewHypeboxOpenCommand extends CommandBase { + + private final HypeboxesPlugin plugin; + public ViewHypeboxOpenCommand(HypeboxesPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player, String crateID) { + if(!this.plugin.getHypeboxesBeingOpened().containsKey(UUID.fromString(crateID))) return; + + HypeBoxAnimationInventory hypeBoxAnimationInventory = this.plugin.getHypeboxesBeingOpened().get(UUID.fromString(crateID)); + if(!hypeBoxAnimationInventory.isActive()) { + player.sendMessage(CC.translate("&d&lHype Boxes &8" + Arrow.arrow() + " &eThis hype box has finished being opened")); + SoundUtils.tryPlayErrorSound(player); + return; + } + this.plugin.getHypeboxesBeingOpened().get(UUID.fromString(crateID)).getUI().open(player); + } +} \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/interfaces/ActiveInventory.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/interfaces/ActiveInventory.java new file mode 100644 index 0000000..0b5c998 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/interfaces/ActiveInventory.java @@ -0,0 +1,5 @@ +package net.crankedpvp.hypeboxes.interfaces; + +public interface ActiveInventory { + boolean isActive(); +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/AdminHypeboxInventory.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/AdminHypeboxInventory.java new file mode 100644 index 0000000..8c55905 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/AdminHypeboxInventory.java @@ -0,0 +1,61 @@ +package net.crankedpvp.hypeboxes.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.language.Language; +import net.crankedpvp.hypeboxes.struct.HypeBox; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Map; +import java.util.Objects; + +public class AdminHypeboxInventory { + + private final PaginatedGui lootboxMenu; + + public PaginatedGui getUI() { + return this.lootboxMenu; + } + + + public AdminHypeboxInventory(Player player, HypeboxesPlugin plugin) { + + Map lootboxObjectMap = plugin.getHypeBoxRegister().getSortedHypeboxes(); + + this.lootboxMenu = new PaginatedGui(6, 28, "Cranked Hypeboxes"); + this.lootboxMenu.setDefaultClickAction(event -> event.setCancelled(true)); + this.lootboxMenu.getFiller().fillBorder(new GuiItem(GuiUtil.createFillerItem())); + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, CC.translate("&cCranked&fPvP &cHypeboxes")).build(); + this.lootboxMenu.setItem(1, 5, new GuiItem(info)); + + this.lootboxMenu.setItem(6, 1, new GuiItem(GuiUtil.createPreviousItem(), event -> { + this.lootboxMenu.previous(); + event.setCancelled(true); + })); + this.lootboxMenu.setItem(6, 9, new GuiItem(GuiUtil.createNextItem(), event -> { + this.lootboxMenu.next(); + event.setCancelled(true); + })); + + lootboxObjectMap.entrySet().stream() + .filter(Objects::nonNull) + .forEach(lootbox -> { + ItemStack itemStack = lootbox.getValue().createHypeBox(1); + this.lootboxMenu.addItem(new GuiItem(itemStack, event -> { + if(player.hasPermission("cranked.admin")) { + player.getInventory().addItem(itemStack); + player.sendMessage(CC.translate(Language.PREFIX.getMessage() + "&aYou have been given a " + lootbox.getKey() + " hypebox")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + })); + }); + } + +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeBoxAnimationInventory.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeBoxAnimationInventory.java new file mode 100644 index 0000000..54cf1c4 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeBoxAnimationInventory.java @@ -0,0 +1,122 @@ +package net.crankedpvp.hypeboxes.inventory; + + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.interfaces.ActiveInventory; +import net.crankedpvp.hypeboxes.struct.HypeBox; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitTask; + +public class HypeBoxAnimationInventory implements ActiveInventory { + + private BukkitTask spinningTask; + + private int amountOfSpins = 0; + + private ItemStack receivingItem; + + private final ItemStack[] itemStacks = new ItemStack[9]; + + private final Player player; + + private boolean active = true; + + + private final Gui hypeBoxAnimationInventory; + + public Gui getUI() { + return this.hypeBoxAnimationInventory; + } + + public HypeBoxAnimationInventory(Player player, HypeBox hypebox) { + this.player = player; + this.amountOfSpins = 0; + this.receivingItem = hypebox.pickRandomReward(); + this.hypeBoxAnimationInventory = new Gui(3, CC.translate(hypebox.getDisplayName())); + this.hypeBoxAnimationInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.hypeBoxAnimationInventory.getFiller().fill(new GuiItem(createFillerItem())); + this.hypeBoxAnimationInventory.setItem(1, 5, new GuiItem(this.createWinningFillerItem())); + this.hypeBoxAnimationInventory.setItem(3, 5, new GuiItem(this.createWinningFillerItem())); + this.hypeBoxAnimationInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(!inventoryCloseEvent.getPlayer().equals(player)) return; + active = false; + if(this.spinningTask != null) this.spinningTask.cancel(); + player.getInventory().addItem(receivingItem); + if(hypebox.doesBroadcast())Bukkit.broadcastMessage(CC.translate("&d&lHype Boxes &8" + Arrow.arrow() + " &f" + LuckpermUtils.getDisplayName(player) + " &fhas just opened a " + hypebox.getDisplayName() + "&r &fand received:")); + if(hypebox.doesBroadcast())Bukkit.broadcastMessage(CC.translate(" &f• &l" + receivingItem.getAmount() + "x &r" + (receivingItem.hasItemMeta() ? receivingItem.getItemMeta().getDisplayName() : receivingItem.getType().name()))); + + }); + + for(int i = 0; i < 9; i++) { + ItemStack itemStack = hypebox.pickRandomReward(); + this.itemStacks[i] = itemStack; + this.hypeBoxAnimationInventory.setItem(2, i+1, new GuiItem(itemStack)); + } + + runTask(hypebox); + } + + public void shiftAllItems(HypeBox hypeBox) { + this.amountOfSpins++; + ItemStack[] itemStacks = this.itemStacks.clone(); + System.arraycopy(itemStacks, 1, this.itemStacks, 0, 8); + this.itemStacks[8] = hypeBox.pickRandomReward(); + + for(int i = 0; i < 9; i++) { + this.hypeBoxAnimationInventory.updateItem(2, i+1, new GuiItem(this.itemStacks[i])); + } + this.player.updateInventory(); + this.player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 1.0f, 2.0f); + } + + public void check(HypeBox hypeBox) { + shiftAllItems(hypeBox); + if(this.amountOfSpins >= 50) { + this.spinningTask.cancel(); + this.receivingItem = this.itemStacks[4]; + this.player.playSound(player.getLocation(), Sound.NOTE_PLING, 2.0f, 2.0f); + } else if(this.amountOfSpins == 47) { + this.spinningTask.cancel(); + this.spinningTask = Bukkit.getScheduler().runTaskTimer(HypeboxesPlugin.getInstance(), () -> check(hypeBox), 0L, 7L); + } else if(this.amountOfSpins == 43) { + this.spinningTask.cancel(); + this.spinningTask = Bukkit.getScheduler().runTaskTimer(HypeboxesPlugin.getInstance(), () -> check(hypeBox), 0L, 5L); + } else if(this.amountOfSpins == 35) { + this.spinningTask.cancel(); + this.spinningTask = Bukkit.getScheduler().runTaskTimer(HypeboxesPlugin.getInstance(), () -> check(hypeBox), 0L, 3L); + } + } + + public void runTask(HypeBox hypeBox) { + this.spinningTask = Bukkit.getScheduler().runTaskTimer(HypeboxesPlugin.getInstance(), () -> check(hypeBox), 3L, 3L); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate(" ")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createWinningFillerItem() { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.BLACK.getData()).setName(" ").setGlowing().build(); + } + + @Override + public boolean isActive() { + return this.active; + } +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeboxBattleInventory.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeboxBattleInventory.java new file mode 100644 index 0000000..caa6a95 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeboxBattleInventory.java @@ -0,0 +1,303 @@ +package net.crankedpvp.hypeboxes.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.interfaces.ActiveInventory; +import net.crankedpvp.hypeboxes.struct.HypeBox; +import net.crankedpvp.hypeboxes.struct.HypeBoxReward; +import net.crankedpvp.hypeboxes.struct.battle.BattleInfo; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitTask; + +import java.text.NumberFormat; +import java.util.*; + +public class HypeboxBattleInventory implements ActiveInventory { + + private final Gui hypeboxBattleInventory; + public Gui getUI() { + return this.hypeboxBattleInventory; + } + + private int amountOfHypeboxes = 0; + + private final Map hypeboxAmounts; + private final Map toGive; + private final Player player; + + private final BattleInfo playerWins = new BattleInfo(); + private final BattleInfo botWins = new BattleInfo(); + + private boolean complete = false; + + private BukkitTask roller; + + private int count = 0; + + private boolean active = true; + + private LinkedList rightQueue; + private LinkedList leftQueue; + + public HypeboxBattleInventory(Player player, Map hypeboxAmounts) { + this.player = player; + this.amountOfHypeboxes = getAmountFromMap(hypeboxAmounts); + this.hypeboxAmounts = hypeboxAmounts; + this.toGive = new HashMap<>(hypeboxAmounts); + this.hypeboxBattleInventory = new Gui(6, "Hypebox Battle Inventory"); + this.hypeboxBattleInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.hypeboxBattleInventory.setItem(Arrays.asList(0, 1, 3, 5, 7, 8, 9, 10, 16, 17, 27, 28, 29, 30, 31, 32, 33, 34, 35, 40, 49), new GuiItem(createFillerItem(DyeColor.GRAY))); + this.hypeboxBattleInventory.setItem(Arrays.asList(4, 12, 14, 22), new GuiItem(createFillerItem(DyeColor.LIME))); + + this.hypeboxBattleInventory.setItem(Arrays.asList(11, 15), new GuiItem(new ItemBuilder(Material.HOPPER, "&dRolling...").colorize().build())); + this.updatePlayerHead(); + this.updateBotHead(); + + this.rollNextBox(); + } + + private int getAmountFromMap(Map hypeboxAmounts) { + int amt = 0; + for (String s : hypeboxAmounts.keySet()) { + if(hypeboxAmounts.get(s) > 0) amt += hypeboxAmounts.get(s); + } + return amt; + } + + + private void handleBattleCompletion(Player player) { + if (playerWins.getValue() == botWins.getValue()) { + handleDraw(player); + } else if (playerWins.getValue() > botWins.getValue()) { + handlePlayerWin(player); + } else { + handlePlayerLoss(player); + } + } + + private void handleDraw(Player player) { + Bukkit.broadcastMessage(CC.translate("&4&lHype Box Battles &8" + Arrow.arrow() + "&f" + LuckpermUtils.getDisplayName(player) + " &8(&e$" + this.playerWins.getValue() + "&8) &fhas &b&lDREW &fwith the &cCranked Bot " + "&8(&e$" + this.botWins.getValue() + "&8) &fin a hype box battle &8(&4" + this.amountOfHypeboxes * 2 + " Hypeboxes&8)")); + Bukkit.broadcastMessage(CC.translate("&fVisit &cbuy.crankedpvp.net &fto purchase hype boxes! &7(/hypebox battle)")); + toGive.forEach((lb, amt) -> player.getInventory().addItem(HypeboxesPlugin.getInstance().getHypeBoxRegister().getHypebox(lb).createHypeBox(amt))); + } + + private void handlePlayerWin(Player player) { + Bukkit.broadcastMessage(CC.translate("&4&lHype Box Battles &8" + Arrow.arrow() + "&f" + LuckpermUtils.getDisplayName(player) + " &8(&e$" + this.playerWins.getValue() + "&8) &fhas &a&lWON &fagainst the &cCranked Bot " + "&8(&e$" + this.botWins.getValue() + "&8) &fin a hype box battle &8(&4" + this.amountOfHypeboxes * 2 + " Hypeboxes&8)")); + playerWins.getHypeBoxRewardList().forEach(item -> { + Bukkit.broadcastMessage(CC.translate(" &f• &l" + item.getItemStack().getAmount() + "x " + item.getItemStack().getItemMeta().getDisplayName() + " &8(&e" + formatAsCurrency(item.getValue()) + "&8)")); + player.getInventory().addItem(item.getItemStack()); + }); + botWins.getHypeBoxRewardList().forEach(item -> { + Bukkit.broadcastMessage(CC.translate(" &f• &l" + item.getItemStack().getAmount() + "x " + item.getItemStack().getItemMeta().getDisplayName() + " &8(&e" + formatAsCurrency(item.getValue()) + "&8)")); + player.getInventory().addItem(item.getItemStack()); + }); + Bukkit.broadcastMessage(CC.translate("&fVisit &cbuy.crankedpvp.net &fto purchase hype boxes! &7(/hypebox battle)")); + } + + private void handlePlayerLoss(Player player) { + Bukkit.broadcastMessage(CC.translate("&4&lHype Box Battles &8" + Arrow.arrow() + "&f" + LuckpermUtils.getDisplayName(player) + " &8(&e$" + this.playerWins.getValue() + "&8) &fhas &c&lLOST &fagainst the &cCranked Bot " + "&8(&e$" + this.botWins.getValue() + "&8) &fin a hype box battle &8(&4" + this.amountOfHypeboxes * 2 + " Hypeboxes&8)")); + playerWins.getHypeBoxRewardList().forEach(item -> Bukkit.broadcastMessage(CC.translate(" &f• &l" + item.getItemStack().getAmount() + "x " + item.getItemStack().getItemMeta().getDisplayName() + " &8(&e" + formatAsCurrency(item.getValue()) + "&8)"))); + botWins.getHypeBoxRewardList().forEach(item -> Bukkit.broadcastMessage(CC.translate(" &f• &l" + item.getItemStack().getAmount() + "x " + item.getItemStack().getItemMeta().getDisplayName() + " &8(&e" + formatAsCurrency(item.getValue()) + "&8)"))); + Bukkit.broadcastMessage(CC.translate("&fVisit &cbuy.crankedpvp.net &fto purchase hype boxes! &7(/hypebox battle)")); + } + + private void addPlayerItem(HypeBoxReward reward) { + if(count <= 4) { + this.hypeboxBattleInventory.updateItem(count + 35, new GuiItem(reward.buildWithInfo())); + } else { + this.hypeboxBattleInventory.updateItem(count + 40, new GuiItem(reward.buildWithInfo())); + } + } + + private void addBotItem(HypeBoxReward reward) { + if(count <= 4) { + this.hypeboxBattleInventory.updateItem(count + 40, new GuiItem(reward.buildWithInfo())); + } else { + this.hypeboxBattleInventory.updateItem(count + 45, new GuiItem(reward.buildWithInfo())); + } + } + + private int spins = 0; + + private void rollNextBox() { + HypeBox currentBox = getNextBox(); + if (currentBox == null) { + this.complete = true; + Bukkit.getScheduler().runTaskLater(HypeboxesPlugin.getInstance(), () -> { + if(this.active) { + this.active = false; + handleBattleCompletion(player); + } + }, 20L); + return; + } + + updateCurrentBox(currentBox); + + rightQueue = new LinkedList<>(); + for (int i = 0; i < 4; i++) { + rightQueue.addFirst(currentBox.pickRandomRewardAsReward()); + } + + leftQueue = new LinkedList<>(); + for (int i = 0; i < 4; i++) { + leftQueue.addFirst(currentBox.pickRandomRewardAsReward()); + } + + + roller = Bukkit.getScheduler().runTaskTimer(HypeboxesPlugin.getInstance(), () -> { + performRoll(currentBox); + }, 0L, 3L); + } + + private void updateCurrentBox(HypeBox currentBox) { + this.hypeboxBattleInventory.updateItem(13, new GuiItem(currentBox.createHypeBox(amountOfHypeboxes))); + } + + private void performRoll(HypeBox currentBox) { + rollRight(currentBox); + rollLeft(currentBox); + this.hypeboxBattleInventory.update(); + spins++; + playRollSound(); + + if (spins >= 40) { + endRoll(); + } + } + + private void playRollSound() { + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 1f, 1f); + } + + private void endRoll() { + Bukkit.getScheduler().cancelTask(roller.getTaskId()); + + HypeBoxReward playerReward = leftQueue.get(1); + HypeBoxReward botReward = rightQueue.get(1); + + if(count == 8) { + resetCount(); + } + count++; + + + playerWins.addItem(playerReward); + addPlayerItem(playerReward); + updatePlayerHead(); + + botWins.addItem(botReward); + addBotItem(botReward); + updateBotHead(); + + spins = 0; + + player.playSound(player.getLocation(), Sound.NOTE_PLING, 1.0f, 1.0f); + + scheduleNextRoll(); + } + + private void resetCount() { + count = 0; + for (Integer i : Arrays.asList(36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53)) { + this.hypeboxBattleInventory.updateItem(i, new GuiItem(new ItemStack(Material.AIR))); + } + } + + private void scheduleNextRoll() { + Bukkit.getScheduler().runTaskLater(HypeboxesPlugin.getInstance(), this::rollNextBox, 35L); + } + + + private void rollRight(HypeBox currentBox) { + rightQueue.removeLast(); + HypeBoxReward hypeBoxReward = currentBox.pickRandomRewardAsReward(); + rightQueue.addFirst(hypeBoxReward); + this.hypeboxBattleInventory.updateItem(23, buildWithLore(rightQueue.get(0))); + this.hypeboxBattleInventory.updateItem(24, buildWithLore(rightQueue.get(1))); + this.hypeboxBattleInventory.updateItem(25, buildWithLore(rightQueue.get(2))); + this.hypeboxBattleInventory.updateItem(26, buildWithLore(rightQueue.get(3))); + + } + + private void rollLeft(HypeBox currentBox) { + HypeBoxReward hypeBoxReward = currentBox.pickRandomRewardAsReward(); + leftQueue.removeFirst(); + leftQueue.addLast(hypeBoxReward); + this.hypeboxBattleInventory.updateItem(18, buildWithLore(leftQueue.get(3))); + this.hypeboxBattleInventory.updateItem(19, buildWithLore(leftQueue.get(2))); + this.hypeboxBattleInventory.updateItem(20, buildWithLore(leftQueue.get(1))); + this.hypeboxBattleInventory.updateItem(21, buildWithLore(leftQueue.get(0))); + } + + private ItemStack buildWithLore(HypeBoxReward reward) { + ItemBuilder itemBuilder = new ItemBuilder(reward.getItemStack().clone()); + itemBuilder.addLore("", "&fChance: &e" + reward.getChance() + "%", "&fValue: &e" + formatAsCurrency(reward.getValue())); + return itemBuilder.colorize().build(); + } + + private HypeBox getNextBox() { + HashMap test = new HashMap<>(this.hypeboxAmounts); + for (Map.Entry stringIntegerEntry : test.entrySet()) { + if(stringIntegerEntry.getValue() > 0) { + HypeBox hypeBox = HypeboxesPlugin.getInstance().getHypeBoxRegister().getHypebox(stringIntegerEntry.getKey()); + this.hypeboxAmounts.put(stringIntegerEntry.getKey(), stringIntegerEntry.getValue() - 1); + return hypeBox; + } else { + this.hypeboxAmounts.remove(stringIntegerEntry.getKey()); + } + } + return null; + } + + private void updateBotHead() { + ItemBuilder itemBuilder = new ItemBuilder(SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNjJjYWYxMGQzZjc4ZDQ0MTBlYmJhZjYyZDNhZjU3NGI2ZTdlYTNkZDg0MjQ4NzEyYzJhNzdmMTM1MWYyYmFjNCJ9fX0=")); + itemBuilder.setName("&f&l<&4&lBot&f&l> &4Cranked's Statistics"); + itemBuilder.setLore("", "&eRewards Value", " &f* &e" + formatAsCurrency(botWins.getValue()), "", "&eRewards Won"); + for (HypeBoxReward hypeBoxReward : botWins.getHypeBoxRewardList()) { + itemBuilder.addLore(" &f* " + hypeBoxReward.getItemStack().getItemMeta().getDisplayName()); + } + this.hypeboxBattleInventory.updateItem(1, 7, new GuiItem(itemBuilder.colorize().build())); + } + + private void updatePlayerHead() { + ItemBuilder itemBuilder = new ItemBuilder(SkullUtils.getSkullFromPlayer(player)); + itemBuilder.setName("&7" + LuckpermUtils.getDisplayName(player) + "'s Statistics"); + itemBuilder.setLore("", "&eRewards Value", " &f* &e$" + playerWins.getValue(), "", "&eRewards Won"); + for (HypeBoxReward hypeBoxReward : playerWins.getHypeBoxRewardList()) { + itemBuilder.addLore(" &f* " + hypeBoxReward.getItemStack().getItemMeta().getDisplayName()); + } + this.hypeboxBattleInventory.updateItem(1, 3, new GuiItem(itemBuilder.colorize().build())); + } + + + private ItemStack createFillerItem(DyeColor dyeColor) { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, dyeColor.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate(" ")); + item.setItemMeta(meta); + return item; + } + + public static String formatAsCurrency(double amount) { + NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US); + return currencyFormatter.format(amount); + } + + @Override + public boolean isActive() { + return active; + } +} \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeboxPreBattleInventory.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeboxPreBattleInventory.java new file mode 100644 index 0000000..89eab88 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/HypeboxPreBattleInventory.java @@ -0,0 +1,165 @@ +package net.crankedpvp.hypeboxes.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.Clickable; +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.struct.HypeBox; +import net.crankedpvp.hypeboxes.struct.HypeBoxManager; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class HypeboxPreBattleInventory { + + private final Gui preBattleInv; + + public Gui getUI() { + return this.preBattleInv; + } + + private final Map hypeboxAmounts = new HashMap<>(); + + private boolean isSpinning = false; + + private final Player player; + + public HypeboxPreBattleInventory(Player player) { + + this.player = player; + + this.preBattleInv = new Gui(3, "Hypebox Battles"); + this.preBattleInv.setDefaultTopClickAction(event -> event.setCancelled(true)); + + this.preBattleInv.setDefaultClickAction(event -> { + ItemStack clickedItem = event.getCurrentItem(); + if (clickedItem != null) { + if(HypeBoxManager.isHypebox(clickedItem)) { + HypeBox hypeBox = HypeBoxManager.getHypeBoxFromItemStack(clickedItem); + int amount = clickedItem.getAmount(); + event.setCurrentItem(null); + addToAmount(hypeBox, amount); + updateSlot(); + } else { + event.setCancelled(true); + } + } + }); + + this.preBattleInv.setItem(Arrays.asList(1, 11, 19, 7, 15, 25), new GuiItem(createFillerItem(DyeColor.RED))); + this.preBattleInv.setItem(2, 5, new GuiItem(createEmptySlot(), event -> { + tryOpenHypeboxBattle(player); + })); + + this.preBattleInv.setCloseGuiAction(event -> { + if(!isSpinning) { + hypeboxAmounts.forEach((hb, amt) -> { + ItemStack itemStack = HypeboxesPlugin.getInstance().getHypeBoxRegister().getHypebox(hb).createHypeBox(amt); + player.getInventory().addItem(itemStack); + player.sendMessage(CC.translate("&aYour hype boxes have been refunded")); + }); + } + }); + + } + + private void tryOpenHypeboxBattle(Player player) { + int amt = 0; + for (String s : this.hypeboxAmounts.keySet()) { + if(this.hypeboxAmounts.get(s) > 0) amt += this.hypeboxAmounts.get(s); + } + if(amt < 3) { + player.sendMessage(CC.translate("&cYou must open a minimum of 3 hypeboxes at once")); + player.closeInventory(); + return; + } + /* + if(amt > 8) { + player.sendMessage(CC.translate("&cYou can only open 8 hypeboxes at a time")); + player.closeInventory(); + return; + } + + */ + for (String s : this.hypeboxAmounts.keySet()) { + if(this.hypeboxAmounts.get(s) > 0) { + this.isSpinning = true; + player.closeInventory(); + HypeboxBattleInventory hypeboxBattleInventory = new HypeboxBattleInventory(player, hypeboxAmounts); + hypeboxBattleInventory.getUI().open(player); + + UUID uuid = UUID.randomUUID(); + HypeboxesPlugin.getInstance().getHypeboxBattles().put(uuid, hypeboxBattleInventory); + Clickable clickable = new Clickable("&f✧ &eClick to watch &c" + LuckpermUtils.getDisplayName(player) + " &eplay against the &cCranked Bot &ein a &4&lHype Box Battle", "&eClick to view &6" + player.getName() + "'s &ehypebox battle &f✧", "/viewbattleopen " + uuid); + clickable.add(CC.translate("\n&eYou can purchase hypeboxes at &cbuy.crankedpvp.net&e!")); + for(Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.sendMessage(""); + clickable.sendToPlayer(onlinePlayer); + onlinePlayer.sendMessage(""); + } + return; + } + } + player.sendMessage(CC.translate("&cYou can't do this battle, contact an admin to find out why")); + } + + private void updateSlot() { + if(hypeboxAmounts.isEmpty()) { + this.preBattleInv.setItem(2, 5, new GuiItem(createEmptySlot(), event -> { + tryOpenHypeboxBattle(player); + })); + } else { + this.preBattleInv.setItem(2, 5, new GuiItem(createReadySlot(), event -> { + tryOpenHypeboxBattle(player); + })); + } + + this.preBattleInv.update(); + } + + private ItemStack createEmptySlot() { + return new ItemBuilder(Material.BARRIER, "&c&lInsert Hypebox", "&7Click a hypebox in your inventory", + "&7to insert it into the battle.").colorize().build(); + } + + private ItemStack createReadySlot() { + ItemBuilder itemBuilder = new ItemBuilder(Material.SLIME_BALL, "&a&lInsert Hypebox", "&7Click a hypebox in your inventory", + "&7to insert it into the battle.", "", "&fCurrent Hypeboxes:"); + for (String s : hypeboxAmounts.keySet()) { + itemBuilder.addLore(" &f* " + hypeboxAmounts.get(s) + "x " + s + " Hypeboxes"); + } + itemBuilder.addLore("", "&a&lClick &fto enter the hypebox battle"); + return itemBuilder.colorize().build(); + } + + + private ItemStack createFillerItem(DyeColor dyeColor) { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, dyeColor.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate(" ")); + item.setItemMeta(meta); + return item; + } + + private void addToAmount(HypeBox hypeBox, int amount) { + String id = hypeBox.getId(); + if(this.hypeboxAmounts.containsKey(id)) { + this.hypeboxAmounts.put(id, this.hypeboxAmounts.get(id) + amount); + } else { + this.hypeboxAmounts.put(id, amount); + } + } + +} + diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/PreviewLootboxInventory.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/PreviewLootboxInventory.java new file mode 100644 index 0000000..f558133 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/inventory/PreviewLootboxInventory.java @@ -0,0 +1,50 @@ +package net.crankedpvp.hypeboxes.inventory; + + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.language.Language; +import net.crankedpvp.hypeboxes.struct.HypeBox; +import net.crankedpvp.hypeboxes.struct.HypeBoxReward; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class PreviewLootboxInventory { + private final Gui previewInventory; + + public Gui getUI() { + return this.previewInventory; + } + + public PreviewLootboxInventory(Player player, String name, HypeboxesPlugin plugin) { + this.previewInventory = new Gui(3, "Preview Hypebox"); + this.previewInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.previewInventory.getFiller().fillBorder(new GuiItem(GuiUtil.createFillerItem())); + HypeBox hypeBox = plugin.getHypeBoxRegister().getHypebox(name); + for (HypeBoxReward reward : hypeBox.getRewards()) { + ItemStack item = reward.getItemStack(); + this.previewInventory.addItem(new GuiItem(reward.buildWithInfo(), event -> { + if (player.hasPermission("cranked.admin")) { + if (event.isShiftClick() && event.isRightClick()) { + plugin.getHypeBoxManager().removeItemFromHypebox(player, item, name); + ItemStack itemStack = item.clone(); + itemStack.setType(Material.BARRIER); + this.previewInventory.updateItem(event.getSlot(), new GuiItem(itemStack)); + player.playSound(player.getLocation(), Sound.ANVIL_BREAK, 2.0F, 2.0F); + } + if (event.isLeftClick()) { + player.getInventory().addItem(item); + player.sendMessage(CC.translate(Language.PREFIX.getMessage() + "&a+ " + item.getItemMeta().getDisplayName())); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + } + })); + } + } + +} \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/Config.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/Config.java new file mode 100644 index 0000000..16a7b86 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/Config.java @@ -0,0 +1,97 @@ +package net.crankedpvp.hypeboxes.language; + + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Config { + HYPEBOX_LORE(), + HYPEBOX_MATERIAL() + ; + + + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/FileHandler.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/FileHandler.java new file mode 100644 index 0000000..c843a2f --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/FileHandler.java @@ -0,0 +1,137 @@ +package net.crankedpvp.hypeboxes.language; + +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class FileHandler { + + private final File languageFile; + private final File configFile; + private final FileConfiguration languageFileConfiguration; + private final FileConfiguration configFileConfiguration; + private final String languagePath; + private final String configPath; + private final HypeboxesPlugin plugin; + + public FileHandler(HypeboxesPlugin plugin) { + this.plugin = plugin; + this.languagePath = "language.yml"; + languageFile = new File(plugin.getDataFolder(), languagePath); + languageFileConfiguration = new YamlConfiguration(); + + this.configPath = "config.yml"; + configFile = new File(plugin.getDataFolder(), configPath); + configFileConfiguration = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultLanguage(); + this.loadLanguageFromDisk(); + this.copyLanguageDefaults(); + this.saveLanguage(); + this.loadLanguageFromDisk(); + this.loadLanguageMessages(); + + this.saveDefaultConfig(); + this.loadConfigFromDisk(); + this.copyConfigDefaults(); + this.saveConfig(); + this.loadConfigFromDisk(); + this.loadConfigMessages(); + } + + private void loadLanguageMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (languageFileConfiguration.isList(path)) { + entry.setValue(languageFileConfiguration.getStringList(path)); + continue; + } + entry.setValue(languageFileConfiguration.getString(path)); + } + } + + private void loadConfigMessages() { + for (Config entry : Config.values()) { + String path = entry.getPath(); + if (configFileConfiguration.isList(path)) { + entry.setValue(configFileConfiguration.getStringList(path)); + continue; + } + entry.setValue(configFileConfiguration.getString(path)); + } + } + + + private void loadLanguageFromDisk() { + try { + languageFileConfiguration.load(languageFile); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + private void loadConfigFromDisk() { + try { + configFileConfiguration.load(configFile); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void saveLanguage() { + try { + languageFileConfiguration.save(languageFile); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + languageFile.getPath() + "!"); + e.printStackTrace(); + } + } + + public void saveConfig() { + try { + configFileConfiguration.save(configFile); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + configFile.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyLanguageDefaults() { + InputStream defConfig = plugin.getResource(this.languagePath); + if (defConfig != null) { + languageFileConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + languageFileConfiguration.options().copyDefaults(true); + } + + private void copyConfigDefaults() { + InputStream defConfig = plugin.getResource(this.configPath); + if (defConfig != null) { + configFileConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + configFileConfiguration.options().copyDefaults(true); + } + + private void saveDefaultLanguage() { + if (!languageFile.exists()) { + languageFile.getParentFile().mkdirs(); + plugin.saveResource(languageFile.getName(),false); + } + } + + private void saveDefaultConfig() { + if (!configFile.exists()) { + configFile.getParentFile().mkdirs(); + plugin.saveResource(configFile.getName(),false); + } + } + +} \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/Language.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/Language.java new file mode 100644 index 0000000..a23b874 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/language/Language.java @@ -0,0 +1,120 @@ +package net.crankedpvp.hypeboxes.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + PREFIX, + FULL_INVENTORY, + + + ALREADY_HYPEBOX, + CREATED_HYPEBOX, + DELETED_HYPEBOX, + HYPEBOX_DISABLED, + HYPEBOX_ENABLED, + HYPEBOX_INVALID, + RELOADED_ALL, + RELOADED_SINGULAR, + + HYPEBOX_RECEIVED, + HYPEBOX_GIVEN, + + HYPEBOX_ADDITEM, + HYPEBOX_ITEM_ALREADY_IN, + + HYPEBOX_ITEM_NOT_FOUND, + HYPEBOX_REMOVE_ITEM, + + PREVIEW_LOOT, + HYPEBOX_OPENED, + + + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/listeners/HypeboxOpenListener.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/listeners/HypeboxOpenListener.java new file mode 100644 index 0000000..0262b2d --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/listeners/HypeboxOpenListener.java @@ -0,0 +1,73 @@ +package net.crankedpvp.hypeboxes.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.Clickable; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.inventory.HypeBoxAnimationInventory; +import net.crankedpvp.hypeboxes.language.Language; +import net.crankedpvp.hypeboxes.struct.HypeBox; +import net.crankedpvp.hypeboxes.struct.HypeBoxManager; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +public class HypeboxOpenListener implements Listener { + + private final HypeboxesPlugin plugin; + public HypeboxOpenListener(HypeboxesPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if(event.getAction() == null) return; + if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { + ItemStack itemStack = event.getItem(); + if(!HypeBoxManager.isHypebox(itemStack)) return; + event.setCancelled(true); + final NBTItem nbtItem = new NBTItem(itemStack); + final HypeBox hypeBox = plugin.getHypeBoxRegister().getHypebox(nbtItem.getOrCreateCompound("cosmicData").getString("hypeboxID")); + if(hypeBox == null) return; + if(hypeBox.getRewards().isEmpty()) return; + + if(!InventoryUtils.hasAvaliableSlot(event.getPlayer(), 1)) { + event.getPlayer().sendMessage(Language.PREFIX.getMessage() + Language.FULL_INVENTORY.getMessage()); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.LAVA_POP, 1.0F, 1.0F); + return; + } + + final int amount = itemStack.getAmount(); + if (amount <= 1) { + event.getPlayer().setItemInHand(null); + } else { + itemStack.setAmount(amount - 1); + event.getPlayer().setItemInHand(itemStack); + } + + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.SUCCESSFUL_HIT, 0.5F, 0.5F); + HypeBoxAnimationInventory hypeboxAnimationInventory = new HypeBoxAnimationInventory(event.getPlayer(), hypeBox); + hypeboxAnimationInventory.getUI().open(event.getPlayer()); + + UUID uuid = UUID.randomUUID(); + this.plugin.getHypeboxesBeingOpened().put(uuid, hypeboxAnimationInventory); + Clickable clickable = new Clickable("&f✧ &eClick to watch &6" + LuckpermUtils.getDisplayName(event.getPlayer()) + " &eopen a " + hypeBox.getDisplayName(), "&eClick to view &6" + event.getPlayer().getName() + "'s &ehypebox &f✧", "/viewhypeboxopen " + uuid); + clickable.add(CC.translate("\n&eYou can purchase this hypebox at &fbuy.crankedpvp.org&e!")); + for(Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.sendMessage(""); + clickable.sendToPlayer(onlinePlayer); + onlinePlayer.sendMessage(""); + } + + } + } +} \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/listeners/HypeboxPreviewListener.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/listeners/HypeboxPreviewListener.java new file mode 100644 index 0000000..52998c1 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/listeners/HypeboxPreviewListener.java @@ -0,0 +1,39 @@ +package net.crankedpvp.hypeboxes.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.inventory.PreviewLootboxInventory; +import net.crankedpvp.hypeboxes.language.Language; +import net.crankedpvp.hypeboxes.struct.HypeBoxManager; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class HypeboxPreviewListener implements Listener { + + private final HypeboxesPlugin plugin; + public HypeboxPreviewListener(HypeboxesPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if(event.getPlayer() == null) return; + if(event.getItem() == null) return; + if(event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_AIR) { + if (HypeBoxManager.isHypebox(event.getItem())) { + event.setCancelled(true); + final NBTItem nbtItem = new NBTItem(event.getItem()); + final String name = nbtItem.getCompound("cosmicData").getString("hypeboxID"); + PreviewLootboxInventory previewLootInventory = new PreviewLootboxInventory(event.getPlayer(), name, this.plugin); + previewLootInventory.getUI().open(event.getPlayer()); + event.getPlayer().sendMessage(Language.PREFIX.getMessage() + Language.PREVIEW_LOOT.getMessage().replace("%lootbox%", StringUtils.toNiceString(name))); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.CHEST_OPEN, 1.0F, 2.0F); + } + } + } + +} \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBox.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBox.java new file mode 100644 index 0000000..10d949c --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBox.java @@ -0,0 +1,106 @@ +package net.crankedpvp.hypeboxes.struct; + +import de.tr7zw.nbtapi.NBTItem; +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.RandomUtils; +import net.crankedpvp.crankedutils.utils.SortUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +@Getter @AllArgsConstructor +public class HypeBox { + + private final String id; + private final String displayName; + private final List lore; + private final Material material; + private final boolean glowing; + private final boolean broadcastRewards; + private final String skullValue; + private final List rewards; + + public ItemStack createHypeBox(int amount) { + ItemBuilder itemBuilder = this.skullValue.equals("???") ? new ItemBuilder(material) : new ItemBuilder(SkullUtils.getSkullFromSkin(this.skullValue)); + itemBuilder.setAmount(amount); + itemBuilder.setName(this.displayName); + itemBuilder.setLore(this.getLore()).colorize(); + if (glowing) itemBuilder.setGlowing(); + NBTItem nbtItem = new NBTItem(itemBuilder.build()); + nbtItem.setBoolean("broadcast", this.broadcastRewards); + nbtItem.getOrCreateCompound("cosmicData").setString("customItem", "hypebox"); + nbtItem.getCompound("cosmicData").setString("hypeboxID", id); + ItemStack itemStack = nbtItem.getItem(); + if(!this.skullValue.equals("???")) { + return SkullUtils.getSkull(itemStack, this.skullValue); + } + return nbtItem.getItem(); + } + + public ItemStack buildHalf(String side) { + String string = side.equals("left") ? "&b&lLeft Half (" + this.getDisplayName() + "&b&l)" : "&d&lRight Half (" + this.getDisplayName() + "&d&l)"; + String opposite = side.equals("left") ? "right" : "left"; + ItemBuilder itemBuilder = new ItemBuilder(Material.PRISMARINE_CRYSTALS, string, "&7Combine with the " + opposite + " half to", + "&7create a full " + this.getDisplayName()); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().setGlowing().build()); + nbtItem.setString("halfLootbox", this.getId()); + nbtItem.setString("side", side); + return nbtItem.getItem(); + + } + + public ItemStack buildLeftOrRightHalf() { + ItemBuilder itemBuilder = new ItemBuilder(Material.PAPER, "&b&lLEFT &f&l&nOR&r &d&lRIGHT &f&lHalf " + Arrow.arrow() + " " + this.getDisplayName(), + "&7Right-Click this lootbox to receive", + "&7either the &bleft &7or &dright&7 half", + "&7of the " + this.getDisplayName() + "&r &7lootbox", + "", + "&4&l(!) &7Obtained from &cbuy.crankedpvp.org &7(/buy)", + "", + "&f&lRandom Loot &7(1 Item)", + "&f&l* 1x &b&lLeft Half (" + this.getDisplayName() + "&b&l)", + "&f&l* 1x &d&lRight Half (" + this.getDisplayName() + "&d&l)" + ); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().setGlowing().build()); + nbtItem.setString("leftOrRightHalf", this.getId()); + return nbtItem.getItem(); + } + + public HypeBoxReward pickRandomRewardAsReward() { + double totalChance = 0.0; + for (HypeBoxReward reward : rewards) { + totalChance += reward.getChance(); + } + + Random random = new Random(); + double randomValue = random.nextDouble() * totalChance; + + double cumulativeChance = 0.0; + for (HypeBoxReward reward : rewards) { + cumulativeChance += reward.getChance(); + if (randomValue <= cumulativeChance) { + return reward; + } + } + + throw new IllegalStateException("No reward was selected. Check if the list of rewards and their chances are set up correctly."); + } + + public ItemStack pickRandomReward() { + final Map rewards = new HashMap<>(); + this.getRewards().stream() + .filter(Objects::nonNull) + .forEach(reward -> rewards.put(reward.getItemStack(), reward.getChance())); + return RandomUtils.getRandomItem(rewards); + } + + public boolean doesBroadcast() { + return this.broadcastRewards; + } +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxManager.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxManager.java new file mode 100644 index 0000000..63f0c56 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxManager.java @@ -0,0 +1,263 @@ +package net.crankedpvp.hypeboxes.struct; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import net.crankedpvp.hypeboxes.language.Config; +import net.crankedpvp.hypeboxes.language.Language; +import net.crankedpvp.hypeboxes.utils.ItemStackSerializer; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; + +public class HypeBoxManager { + + private final HypeboxesPlugin plugin; + public HypeBoxManager(HypeboxesPlugin plugin) { + this.plugin = plugin; + } + + public static boolean isHypebox(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getOrCreateCompound("cosmicData").hasKey("customItem")) return false; + return nbtItem.getCompound("cosmicData").hasKey("hypeboxID"); + } + + public static HypeBox getHypeBoxFromItemStack(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return null; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getOrCreateCompound("cosmicData").hasKey("customItem")) return null; + return HypeboxesPlugin.getInstance().getHypeBoxRegister().getHypebox(Objects.requireNonNull(nbtItem.getCompound("cosmicData")).getString("hypeboxID")); + } + + public static boolean isHypeboxHalfGenerator(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return (nbtItem.hasKey("leftOrRightHalf")); + } + + public static boolean isHypeboxHalf(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasKey("halfLootbox")) return false; + return nbtItem.hasKey("side"); + } + + public static boolean doesHypeboxBroadcast(ItemStack itemStack) { + if(!isHypebox(itemStack)) return false; + if (itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getBoolean("broadcast"); + } + + public void createDefaultConfig(String name) { + File file = new File(this.plugin.getDataFolder(), "Hypeboxes/" + name + ".yml"); + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + String[] colors = new String[]{"&a", "&b", "&c", "&d", "&e", "&2", "&3", "&4", "&5", "&6", "&9"}; + String color = colors[ThreadLocalRandom.current().nextInt(1, 10)]; + yamlConfiguration.set("Item.Display.Name", "&f&ki&r " + color + "&l" + StringUtils.toNiceString(name) + " &f&ki&r &f&lHypebox"); + yamlConfiguration.set("Item.Display.Lore", Config.HYPEBOX_LORE.getValuesAsList()); + yamlConfiguration.set("Item.Material", "" + Config.HYPEBOX_MATERIAL.getValue()); + yamlConfiguration.set("Item.Glowing", true); + yamlConfiguration.set("Misc.Broadcast.Rewards", true); + try { + yamlConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void createDefaultConfigFromItemStack(ItemStack itemStack, String name) { + File file = new File(this.plugin.getDataFolder(), "Hypeboxes/" + name + ".yml"); + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + ItemMeta itemMeta = itemStack.getItemMeta(); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + yamlConfiguration.set("Item.Display.Name", itemMeta.getDisplayName()); + yamlConfiguration.set("Item.Display.Lore", itemMeta.getLore()); + yamlConfiguration.set("Item.Material", "" + itemStack.getType().name()); + yamlConfiguration.set("Item.Glowing", itemMeta.hasEnchants()); + yamlConfiguration.set("Misc.Broadcast.Rewards", true); + try { + yamlConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void createHypebox(String lootbox) { + createDefaultConfig(lootbox); + this.initialize(lootbox); + } + + public void createHypeboxFromItemStack(ItemStack itemStack, String lootbox) { + createDefaultConfigFromItemStack(itemStack, lootbox); + this.initialize(lootbox); + } + + + + public void deleteConfig(String name) { + File file = new File(this.plugin.getDataFolder(), "Hypeboxes/" + name + ".yml"); + if (file.exists()) + file.delete(); + } + + public void reloadHypebox(String hypebox) { + if (this.plugin.getHypeBoxRegister().isHypebox(hypebox)) { + this.plugin.getHypeBoxRegister().removeHypebox(hypebox); + initialize(hypebox); + } else { + System.out.println("[-] Failure reloading hypebox, " + hypebox); + } + } + + public void initializeAll() { + File dataFolder = new File(this.plugin.getDataFolder(), "Hypeboxes"); + Arrays.stream(Objects.requireNonNull(dataFolder.listFiles())) + .filter(file -> !file.isDirectory()) + .filter(file -> !file.getName().startsWith("-")) + .forEach(file -> { + try { + initialize(file.getName().replace(".yml", "")); + } catch (NullPointerException exception) { + System.out.println("[CrankedLootboxes] Failed to register hypebox: " + file.getName().replace(".yml", "")); + } + }); + } + + public void initialize(String fileName) { + File file = new File(this.plugin.getDataFolder(), "Hypeboxes/" + fileName + ".yml"); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + String name = yamlConfiguration.getString("Item.Display.Name"); + List lore = yamlConfiguration.getStringList("Item.Display.Lore"); + String mater = yamlConfiguration.getString("Item.Material"); + Material material = mater.contains("SKULL") ? Material.SKULL_ITEM : Material.valueOf(mater.toUpperCase()); + String skullValue = mater.contains(":") ? mater.split(":")[1] : "???"; + boolean glowing = yamlConfiguration.getBoolean("Item.Glowing"); + boolean broadcastRewards = yamlConfiguration.contains("Misc.Broadcast.Rewards") && yamlConfiguration.getBoolean("Misc.Broadcast.Rewards"); + List rewards = getRewards(yamlConfiguration); + HypeBox lootbox = new HypeBox(file.getName().replace(".yml", ""), name, lore, material, glowing, broadcastRewards, skullValue, rewards); + this.plugin.getHypeBoxRegister().register(lootbox); + } + + private List getRewards(FileConfiguration fileConfiguration) { + List rewards = new ArrayList<>(); + if (fileConfiguration.getConfigurationSection("rewards") != null) + fileConfiguration.getConfigurationSection("rewards").getKeys(false).forEach(key -> { + ItemStack itemStack = null; + try { + itemStack = ItemStackSerializer.deserialize(fileConfiguration.getConfigurationSection("rewards." + key).getString("item").replace("\r\n", "")); + } catch (IOException|ClassNotFoundException e) { + e.printStackTrace(); + } + HypeBoxReward reward = new HypeBoxReward(itemStack, fileConfiguration.getConfigurationSection("rewards." + key).getDouble("chance"), fileConfiguration.getConfigurationSection("rewards." + key).getDouble("value")); + rewards.add(reward); + }); + return rewards; + } + + public void addItem(Player player, String lootbox, double chance, double value) { + try { + File file = new File(this.plugin.getDataFolder() + "/Hypeboxes/" + lootbox + ".yml"); + if(file.exists()) { + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file); + String itemName = ChatColor.stripColor(player.getItemInHand().getItemMeta().getDisplayName()); + String toBase64 = ItemStackSerializer.serialize(player.getItemInHand()); + if(!yamlConfiguration.contains("rewards") || !yamlConfiguration.getConfigurationSection("rewards").getKeys(true).contains(itemName + player.getItemInHand().getAmount())) { + String name = itemName + player.getItemInHand().getAmount(); + yamlConfiguration.set("rewards." + name + ".item", toBase64); + yamlConfiguration.set("rewards." + name + ".chance", chance); + yamlConfiguration.set("rewards." + name + ".value", value); + yamlConfiguration.save(file); + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_ADDITEM.getMessage().replace("%lootbox%", lootbox).replace("%item%", player.getItemInHand().getItemMeta().getDisplayName())); + player.playSound(player.getLocation(), Sound.LEVEL_UP, 2.0F, 2.0F); + reloadHypebox(lootbox); + } else { + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_ITEM_ALREADY_IN.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void removeItemFromHypebox(Player player, ItemStack itemStack, String lootbox) { + try { + File file = new File(this.plugin.getDataFolder() + "/Hypeboxes/" + lootbox + ".yml"); + if (file.exists()) { + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file); + String itemName = ChatColor.stripColor(itemStack.getItemMeta().getDisplayName()); + if (!yamlConfiguration.contains("rewards")) { + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_ITEM_NOT_FOUND.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + if (yamlConfiguration.getConfigurationSection("rewards").getKeys(true).contains(itemName + itemStack.getAmount())) { + yamlConfiguration.set("rewards." + itemName + itemStack.getAmount(), null); + yamlConfiguration.save(file); + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_REMOVE_ITEM.getMessage().replace("%lootbox%", lootbox).replace("%item%", itemStack.getItemMeta().getDisplayName())); + player.playSound(player.getLocation(), Sound.CHICKEN_EGG_POP, 2.0F, 2.0F); + reloadHypebox(lootbox); + } else { + player.sendMessage(Language.PREFIX.getMessage() + Language.HYPEBOX_ITEM_NOT_FOUND.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void giveHypebox(Player player, HypeBox lootbox, int amount) { + InventoryUtils.giveItemToPlayer(player, lootbox.createHypeBox(amount)); + } + + public void giveHypebox(Player player, HypeBox lootbox) { + giveHypebox(player, lootbox, 1); + } + + public ItemStack getHypebox(HypeBox lootbox) { + return getHypebox(lootbox, 1); + } + + public ItemStack getHypebox(HypeBox lootbox, int amount) { + return lootbox.createHypeBox(amount); + } + +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxRegister.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxRegister.java new file mode 100644 index 0000000..0cca8b0 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxRegister.java @@ -0,0 +1,88 @@ +package net.crankedpvp.hypeboxes.struct; + + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Maps; +import lombok.Getter; +import net.crankedpvp.hypeboxes.HypeboxesPlugin; +import org.apache.commons.lang.Validate; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +public class HypeBoxRegister { + private final HypeboxesPlugin plugin; + + @Getter + private final Map lootboxes; + + public HypeBoxRegister(HypeboxesPlugin plugin) { + this.lootboxes = Maps.newConcurrentMap(); + this.plugin = plugin; + } + + public Map getSortedHypeboxes() { + return sort(this.lootboxes); + } + + + public Map sort(Map map) { + List> list = new ArrayList<>(map.entrySet()); + list.sort(Map.Entry.comparingByKey()); + Collections.reverse(list); + Map result = new LinkedHashMap<>(); + for (int i = list.size() - 1; i >= 0; i--) { + Map.Entry entry = list.get(i); + result.put(entry.getKey(), entry.getValue()); + } + return result; + } + + public void register(HypeBox hypebox) { + try { + this.lootboxes.put(hypebox.getId(), hypebox); + this.plugin.getLogger().info("Successfully registered hypebox: " + hypebox.getId()); + } catch (Exception var3) { + System.err.println("&8(&c!&8) Failed to register hypebox, " + hypebox.getId()); + } + } + + public boolean isHypebox(String name) { + return (getHypebox(name) != null); + } + + public HypeBox getHypebox(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + return this.lootboxes.get(name); + } + + public void clearHypeboxMap() { + this.lootboxes.clear(); + } + + public void removeHypebox(String lootbox) { + this.lootboxes.remove(lootbox); + } + + public Collection getHypeboxObjects() { + return Collections.unmodifiableCollection(this.lootboxes.values()); + } + + public List getHypeboxesAsList() { + return new ArrayList<>(this.lootboxes.values()); + } + + public List getHypeboxesAsIDs() { + return getHypeboxesAsList().stream() + .map(HypeBox::getId) + .collect(Collectors.toList()); + } + + public HypeBox select(Collection lootboxCollection) { + return (lootboxCollection.size() > 0) ? ImmutableList.copyOf(lootboxCollection).get(ThreadLocalRandom.current().nextInt(lootboxCollection.size())) : null; + } + + +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxReward.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxReward.java new file mode 100644 index 0000000..e5d1f0b --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/HypeBoxReward.java @@ -0,0 +1,22 @@ +package net.crankedpvp.hypeboxes.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +@AllArgsConstructor +@Getter +public class HypeBoxReward { + + private final ItemStack itemStack; + private final double chance; + private final double value; + + public ItemStack buildWithInfo() { + ItemBuilder itemBuilder = new ItemBuilder(itemStack.clone()); + itemBuilder.addLore("", "&fChance: &e" + chance + "%", "&fValue: &e$" + value); + return itemBuilder.colorize().build(); + } +} \ No newline at end of file diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/battle/BattleInfo.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/battle/BattleInfo.java new file mode 100644 index 0000000..a1f5c2b --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/struct/battle/BattleInfo.java @@ -0,0 +1,29 @@ +package net.crankedpvp.hypeboxes.struct.battle; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.hypeboxes.struct.HypeBoxReward; + +import java.util.ArrayList; +import java.util.List; + +@Getter @AllArgsConstructor +public class BattleInfo { + private List hypeBoxRewardList; + + public BattleInfo() { + this.hypeBoxRewardList = new ArrayList<>(); + } + + public void addItem(HypeBoxReward hypeBoxReward) { + this.hypeBoxRewardList.add(hypeBoxReward); + } + + public double getValue() { + double value = 0; + for (HypeBoxReward hypeBoxReward : hypeBoxRewardList) { + value += hypeBoxReward.getValue(); + } + return value; + } +} diff --git a/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/utils/ItemStackSerializer.java b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/utils/ItemStackSerializer.java new file mode 100644 index 0000000..3ee4db6 --- /dev/null +++ b/HypeBoxes/src/main/java/net/crankedpvp/hypeboxes/utils/ItemStackSerializer.java @@ -0,0 +1,30 @@ +package net.crankedpvp.hypeboxes.utils; + +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class ItemStackSerializer { + public static ItemStack deserialize(String base64) throws IOException, ClassNotFoundException { + byte[] data = Base64Coder.decodeLines(base64); + ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); + BukkitObjectInputStream in = new BukkitObjectInputStream(bytesIn); + ItemStack itemStack = (ItemStack) in.readObject(); + in.close(); + return itemStack; + } + + public static String serialize(ItemStack itemStack) throws IOException { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + BukkitObjectOutputStream out = new BukkitObjectOutputStream(bytesOut); + out.writeObject(itemStack); + out.flush(); + out.close(); + return Base64Coder.encodeLines(bytesOut.toByteArray()); + } +} diff --git a/HypeBoxes/src/main/resources/config.yml b/HypeBoxes/src/main/resources/config.yml new file mode 100644 index 0000000..8559dc0 --- /dev/null +++ b/HypeBoxes/src/main/resources/config.yml @@ -0,0 +1,6 @@ +HYPEBOX_MATERIAL: CHEST +HYPEBOX_LORE: + - "&7Right-Click to receive a" + - "&7random reward" + - "" + - "&4&l(!) &7Obtained from &cbuy.crankedpvp.org &7(/buy)" \ No newline at end of file diff --git a/HypeBoxes/src/main/resources/language.yml b/HypeBoxes/src/main/resources/language.yml new file mode 100644 index 0000000..8e18cc9 --- /dev/null +++ b/HypeBoxes/src/main/resources/language.yml @@ -0,0 +1,18 @@ +PREFIX: "&cCranked&fPvP &8| " +FULL_INVENTORY: "&cYour inventory does not have enough slots to complete this action" +ALREADY_HYPEBOX: "&cA lootbox named %lootbox% is already registered" +CREATED_HYPEBOX: "&aYou have created the lootbox %lootbox%" +DELETED_HYPEBOX: "&aYou have deleted the lootbox %lootbox%" +HYPEBOX_INVALID: "&cThe lootbox with named %lootbox% could not be found" +HYPEBOX_DISABLED: "&aThe lootbox named %lootbox% has been disabled" +HYPEBOX_ENABLED: "&aThe lootbox named %lootbox% has been enabled" +RELOADED_ALL: "&aYou have reloaded ALL lootboxes" +RELOADED_SINGULAR: "&aYou have reloaded the %lootbox% lootbox" +HYPEBOX_RECEIVED: "&aYou have received the %lootbox% lootbox" +HYPEBOX_GIVEN: "&aYou have given the %lootbox% lootbox to %player%" +HYPEBOX_ADDITEM: "&aAdded %item%&r&a to %lootbox% lootbox" +HYPEBOX_ITEM_ALREADY_IN: "&cThis item is already in the %lootbox% lootbox" +HYPEBOX_ITEM_NOT_FOUND: "&cThis item is not in the %lootbox% lootbox" +HYPEBOX_REMOVE_ITEM: "&cDeleted %item%&r&c from %lootbox% lootbox" +HYPEBOX_OPENED: "&aYou have opened the %lootbox% lootbox" +PREVIEW_LOOT: "&aYou are now previewing the loot of the %lootbox% lootbox" diff --git a/HypeBoxes/src/main/resources/plugin.yml b/HypeBoxes/src/main/resources/plugin.yml new file mode 100644 index 0000000..6c60e37 --- /dev/null +++ b/HypeBoxes/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedHypeBoxes +main: net.crankedpvp.hypeboxes.HypeboxesPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/ItemFilter/pom.xml b/ItemFilter/pom.xml new file mode 100644 index 0000000..498ca99 --- /dev/null +++ b/ItemFilter/pom.xml @@ -0,0 +1,31 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + ItemFilter + + + 8 + 8 + + + + Utils + net.crankedpvp + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + \ No newline at end of file diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/ItemFilterPlugin.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/ItemFilterPlugin.java new file mode 100644 index 0000000..56ec341 --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/ItemFilterPlugin.java @@ -0,0 +1,66 @@ +package net.crankedpvp.itemfilter; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.itemfilter.command.Commandfilter; +import net.crankedpvp.itemfilter.data.FilterManager; +import net.crankedpvp.itemfilter.listeners.CommandListener; +import net.crankedpvp.itemfilter.listeners.FilterListener; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.ArrayList; +import java.util.List; + +@Getter +public class ItemFilterPlugin extends JavaPlugin { + + @Getter + private static ItemFilterPlugin instance; + private FilterManager filterManager; + private CommandManager commandManager; + + + @Override + public void onEnable() { + reloadConfig(); + instance = this; + this.commandManager = new CommandManager(this, true); + commandManager.register(new Commandfilter()); + filterManager = new FilterManager(this); + filterManager.loadAll(); + + Bukkit.getPluginManager().registerEvents(new FilterListener(), this); + Bukkit.getPluginManager().registerEvents(new CommandListener(), this); + + } + + @Override + public void onDisable() { + filterManager.saveAll(); + instance = null; + } + + @Override + public void reloadConfig() { + super.reloadConfig(); + saveDefaultConfig(); + getConfig().options().copyDefaults(true); + saveConfig(); + } + + public static String color(String input) { + return ChatColor.translateAlternateColorCodes('&', input); + } + + public static List colorList(List inputList) { + List output = new ArrayList<>(); + for(String input : inputList) + output.add(ChatColor.translateAlternateColorCodes('&', input)); + + return output; + } + +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/command/Commandfilter.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/command/Commandfilter.java new file mode 100644 index 0000000..7cab45a --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/command/Commandfilter.java @@ -0,0 +1,70 @@ +package net.crankedpvp.itemfilter.command; + +import java.util.Iterator; +import java.util.List; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import net.crankedpvp.itemfilter.data.FilterUser; +import net.crankedpvp.itemfilter.utils.MainInventory; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("filter") +@Alias({"ft", "filters"}) +public class Commandfilter + extends CommandBase { + + @Default + public void onDefeault(CommandSender sender) { + Iterator localObject1; + String localObject2; + for (localObject1 = ItemFilterPlugin.getInstance().getConfig().getStringList("messages.item-filter-usage").iterator(); localObject1.hasNext(); ) { + localObject2 = (String) ((Iterator) localObject1).next(); + sender.sendMessage(ItemFilterPlugin.color(localObject2)); + } + } + + @SubCommand("edit") + public void onEdit(CommandSender sender) { + MainInventory.getInstance().mainInventory((Player) sender); + } + + @SubCommand("toggle") + public void onToggle(CommandSender sender) { + Player player = (Player) sender; + Iterator localObject1; + String localObject2; + FilterUser filterUser = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(player.getUniqueId()); + if (filterUser.isEnabled()) { + + filterUser.setEnabled(false); + for (localObject1 = ItemFilterPlugin.getInstance().getConfig().getStringList("messages.item-filter-disable").iterator(); localObject1.hasNext(); ) { + localObject2 = (localObject1).next(); + sender.sendMessage(ItemFilterPlugin.color(localObject2)); + } + } else { + filterUser.setEnabled(true); + for (localObject1 = ItemFilterPlugin.getInstance().getConfig().getStringList("messages.item-filter-enable").iterator(); localObject1.hasNext(); ) { + localObject2 = localObject1.next(); + sender.sendMessage(ItemFilterPlugin.color(localObject2)); + } + } + } + + @Permission("filter.admin") + @SubCommand("reload") + public void onReload(CommandSender sender) { + Iterator localObject1; + String localObject2; + ItemFilterPlugin.getInstance().reloadConfig(); + for (localObject1 = ItemFilterPlugin.getInstance().getConfig().getStringList("messages.item-filter-reload").iterator(); localObject1.hasNext(); ) { + localObject2 = localObject1.next(); + sender.sendMessage(ItemFilterPlugin.color(localObject2)); + } + } + + +} \ No newline at end of file diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/data/FilterManager.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/data/FilterManager.java new file mode 100644 index 0000000..fc1c7bc --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/data/FilterManager.java @@ -0,0 +1,23 @@ +package net.crankedpvp.itemfilter.data; + +import lombok.Getter; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.UUID; + +@Getter +public class FilterManager extends SaveLoadManager { + public FilterManager(JavaPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "/data", FilterUser.class); + } + + public FilterUser getFilterUser(UUID uuid) { + if (!containsKey(uuid.toString())) { + FilterUser filterUser = new FilterUser(uuid); + addToCache(filterUser); + } + return getFromCache(uuid.toString()); + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/data/FilterUser.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/data/FilterUser.java new file mode 100644 index 0000000..94ec7bf --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/data/FilterUser.java @@ -0,0 +1,48 @@ +package net.crankedpvp.itemfilter.data; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.storageutils.utils.KeyToSave; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Getter +@Setter +public class FilterUser implements KeyToSave { + private UUID uuid; + private List filter; + private boolean enabled; + + public FilterUser(UUID uuid) { + this.filter = new ArrayList<>(); + this.uuid = uuid; + this.enabled = false; + } + + + @Override + public String getKey() { + return uuid.toString(); + } + + @Override + public void setKey(String s) { + this.uuid = UUID.fromString(s); + } + + public Player getPlayer() { + return Bukkit.getPlayer(uuid); + } + + public boolean canPickup(Material material) { + return this.filter.contains(material.name()); + } + +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/listeners/CommandListener.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/listeners/CommandListener.java new file mode 100644 index 0000000..9d3e437 --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/listeners/CommandListener.java @@ -0,0 +1,18 @@ +package net.crankedpvp.itemfilter.listeners; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +public class CommandListener implements Listener { + + @EventHandler + public void onCommandUse( PlayerCommandPreprocessEvent e) { + if (e.getMessage().startsWith("/filter ") || e.getMessage().equalsIgnoreCase("/filter")) { + e.setCancelled(true); + Bukkit.dispatchCommand((CommandSender)e.getPlayer(), e.getMessage().replace("/filter", "filters")); + } + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/listeners/FilterListener.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/listeners/FilterListener.java new file mode 100644 index 0000000..580f3d6 --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/listeners/FilterListener.java @@ -0,0 +1,181 @@ +package net.crankedpvp.itemfilter.listeners; + +import java.util.List; + +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import net.crankedpvp.itemfilter.data.FilterUser; +import net.crankedpvp.itemfilter.utils.*; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitRunnable; + +public class FilterListener + implements Listener { + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + if(event.getCurrentItem() == null) + return; + + Inventory localInventory = event.getInventory(); + Player localPlayer = (Player) event.getWhoClicked(); + if (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.title")))) { + event.setCancelled(true); + int i = event.getRawSlot(); + if ((i <= localInventory.getSize()) && + (event.getCurrentItem() != null)) { + if (i == ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Equipment.slot")) { + EquipmentInventory.getInstance().equipmentInventory(localPlayer); + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.category-open.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.category-open.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-pitch")); + } + } + if (i == ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Potion.slot")) { + PotionInventory.getInstance().potionInventory(localPlayer); + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.category-open.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.category-open.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-pitch")); + } + } + if (i == ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Raiding.slot")) { + RaidingInventory.getInstance().raidingInventory(localPlayer); + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.category-open.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.category-open.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-pitch")); + } + } + if (i == ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Food.slot")) { + FoodInventory.getInstance().foodInventory(localPlayer); + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.category-open.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.category-open.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-pitch")); + } + } + if (i == ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Specialty.slot")) { + SpecialtyInventory.getInstance().specialtyInventory(localPlayer); + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.category-open.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.category-open.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-pitch")); + } + } + if (i == ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Ores.slot")) { + OresInventory.getInstance().oresInventory(localPlayer); + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.category-open.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.category-open.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-open.sound-pitch")); + } + } + } + } + if ((localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.equipment-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.ores-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.specialty-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.food-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.raiding-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.potion-inventory.title"))))) { + event.setCancelled(true); + ItemStack localItemStack1 = event.getCurrentItem(); + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(localPlayer.getUniqueId()).getFilter(); + + if ((localItemStack1.hasItemMeta()) && + (localItemStack1.getItemMeta().hasDisplayName())) { + if (localList1.contains(String.valueOf(localItemStack1.getType().name()))) { + ItemStack localItemStack2 = localItemStack1; + + ItemMeta localItemMeta = localItemStack1.getItemMeta(); + String str = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.WillNot.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + List localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.WillNot.ItemLore")); + localItemMeta.setDisplayName(str); + localItemMeta.removeEnchant(Enchantment.DURABILITY); + localItemMeta.removeItemFlags(ItemFlag.HIDE_ENCHANTS); + localItemMeta.setLore(localList2); + localItemStack2.setItemMeta(localItemMeta); + localPlayer.updateInventory(); + + localList1.remove(String.valueOf(localItemStack1.getType().name())); + + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.filter-item-select.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.filter-item-select.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.filter-item-select.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.filter-item-select.sound-pitch")); + } + return; + } + + ItemStack localItemStack2 = localItemStack1; + ItemMeta localItemMeta = localItemStack2.getItemMeta(); + String str = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.Will.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + List localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.Will.ItemLore")); + localItemMeta.setDisplayName(str); + localItemMeta.setLore(localList2); + localItemMeta.addEnchant(Enchantment.DURABILITY, 1, true); + localItemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + localItemStack2.setItemMeta(localItemMeta); + localPlayer.updateInventory(); + + localList1.add(String.valueOf(localItemStack1.getType().name())); + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.filter-item-select.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.filter-item-select.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.filter-item-select.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.filter-item-select.sound-pitch")); + } + } + } + } + + @EventHandler + public void onCommand(PlayerCommandPreprocessEvent e) { + if(!e.getMessage().toLowerCase().equalsIgnoreCase("/ft")) { + return; + } + + e.setCancelled(true); + e.getPlayer().chat("/filters toggle"); + } + + + + @EventHandler + public void onItemPickup(PlayerPickupItemEvent paramPlayerPickupItemEvent) { + Player localPlayer = paramPlayerPickupItemEvent.getPlayer(); + Item localItem = paramPlayerPickupItemEvent.getItem(); + ItemStack localItemStack = localItem.getItemStack(); + FilterUser filterUser = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(localPlayer.getUniqueId()); + if(!filterUser.isEnabled()) + return; + + if (!filterUser.canPickup(localItemStack.getType())) { + paramPlayerPickupItemEvent.setCancelled(true); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent paramInventoryCloseEvent) { + Inventory localInventory = paramInventoryCloseEvent.getInventory(); + final Player localPlayer = (Player) paramInventoryCloseEvent.getPlayer(); + if ((localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.equipment-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.ores-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.specialty-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.food-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.raiding-inventory.title")))) || + (localInventory.getTitle().equalsIgnoreCase(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.potion-inventory.title"))))) { + new BukkitRunnable() { + public void run() { + MainInventory.getInstance().mainInventory(localPlayer); + cancel(); + } + } + + .runTaskTimer(ItemFilterPlugin.getInstance(), 5L, 0L); + if (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.category-close.enable")) { + localPlayer.playSound(localPlayer.getLocation(), Sound.valueOf(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.category-close.sound-effect")), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-close.sound-volume"), ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.settings.category-close.sound-pitch")); + } + } + } +} + diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/EquipmentInventory.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/EquipmentInventory.java new file mode 100644 index 0000000..a543957 --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/EquipmentInventory.java @@ -0,0 +1,100 @@ +package net.crankedpvp.itemfilter.utils; + +import java.util.ArrayList; +import java.util.List; + +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class EquipmentInventory { + private static EquipmentInventory ourInstance = new EquipmentInventory(); + private Inventory inventory; + + public static EquipmentInventory getInstance() { + return ourInstance; + } + + public Inventory equipmentInventory(Player paramPlayer) { + String str1 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.equipment-inventory.title")); + this.inventory = Bukkit.createInventory(null, 36, str1); + int i = 0; + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + for (ItemStack localItemStack1 : getFilterItems()) { + ItemStack localItemStack2; + ItemMeta localItemMeta; + String str2; + List localList2; + + if (localList1.contains(String.valueOf(localItemStack1.getType().name()))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.Will.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.Will.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.setLore(localList2); + localItemMeta.addEnchant(Enchantment.DURABILITY, 1, true); + localItemMeta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } else if (!localList1.contains(String.valueOf(localItemStack1))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.WillNot.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.WillNot.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.removeEnchant(Enchantment.DURABILITY); + localItemMeta.setLore(localList2); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } + i++; + } + paramPlayer.openInventory(this.inventory); + return this.inventory; + } + + private List itemStackList = new ArrayList(); + + public List getFilterItems() { + if (this.itemStackList.isEmpty()) { + this.itemStackList.add(new ItemFactory("298").display("Leather Helmet").build()); + this.itemStackList.add(new ItemFactory("306").display("Iron Helmet").build()); + this.itemStackList.add(new ItemFactory("314").display("Gold Helmet").build()); + this.itemStackList.add(new ItemFactory("310").display("Diamond Helmet").build()); + this.itemStackList.add(new ItemFactory("299").display("Leather Chestplate").build()); + this.itemStackList.add(new ItemFactory("307").display("Iron Chestplate").build()); + this.itemStackList.add(new ItemFactory("315").display("Gold Chestplate").build()); + this.itemStackList.add(new ItemFactory("311").display("Diamond Chestplate").build()); + this.itemStackList.add(new ItemFactory("300").display("Leather Leggings").build()); + this.itemStackList.add(new ItemFactory("308").display("Iron Leggings").build()); + this.itemStackList.add(new ItemFactory("316").display("Gold Leggings").build()); + this.itemStackList.add(new ItemFactory("312").display("Diamond Leggings").build()); + this.itemStackList.add(new ItemFactory("301").display("Leather Boots").build()); + this.itemStackList.add(new ItemFactory("309").display("Iron Boots").build()); + this.itemStackList.add(new ItemFactory("317").display("Gold Boots").build()); + this.itemStackList.add(new ItemFactory("313").display("Diamond Boots").build()); + this.itemStackList.add(new ItemFactory("267").display("Iron Sword").build()); + this.itemStackList.add(new ItemFactory("283").display("Gold Sword").build()); + this.itemStackList.add(new ItemFactory("276").display("Diamond Sword").build()); + this.itemStackList.add(new ItemFactory("258").display("Iron Axe").build()); + this.itemStackList.add(new ItemFactory("286").display("Gold Axe").build()); + this.itemStackList.add(new ItemFactory("279").display("Diamond Axe").build()); + this.itemStackList.add(new ItemFactory("261").display("Bow").build()); + this.itemStackList.add(new ItemFactory("292").display("Iron Hoe").build()); + this.itemStackList.add(new ItemFactory("294").display("Gold Hoe").build()); + this.itemStackList.add(new ItemFactory("293").display("Diamond Hoe").build()); + this.itemStackList.add(new ItemFactory("262").display("Arrow").build()); + this.itemStackList.add(new ItemFactory("368").display("Ender Pearl").build()); + this.itemStackList.add(new ItemFactory("373").display("Potions").build()); + this.itemStackList.add(new ItemFactory("397:3").display("Player Skulls").build()); + } + return this.itemStackList; + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/FoodInventory.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/FoodInventory.java new file mode 100644 index 0000000..c39ffea --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/FoodInventory.java @@ -0,0 +1,84 @@ +package net.crankedpvp.itemfilter.utils; + +import java.util.ArrayList; +import java.util.List; + +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class FoodInventory { + private static FoodInventory ourInstance = new FoodInventory(); + private Inventory inventory; + + public static FoodInventory getInstance() { + return ourInstance; + } + + public Inventory foodInventory(Player paramPlayer) { + String str1 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.food-inventory.title")); + this.inventory = Bukkit.createInventory(null, 18, str1); + int i = 0; + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + for (ItemStack localItemStack1 : getFilterItems()) { + ItemStack localItemStack2; + ItemMeta localItemMeta; + String str2; + List localList2; + if (localList1.contains(String.valueOf(localItemStack1.getType().name()))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.Will.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.Will.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.setLore(localList2); + localItemMeta.addEnchant(Enchantment.DURABILITY, 1, true); + localItemMeta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } else if (!localList1.contains(String.valueOf(localItemStack1))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.WillNot.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.WillNot.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.removeEnchant(Enchantment.DURABILITY); + localItemMeta.setLore(localList2); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } + i++; + } + paramPlayer.openInventory(this.inventory); + return this.inventory; + } + + private List itemStackList = new ArrayList(); + + public List getFilterItems() { + if (this.itemStackList.isEmpty()) { + this.itemStackList.add(new ItemFactory("352").display("Bone").build()); + this.itemStackList.add(new ItemFactory("391").display("Carrot Item").build()); + this.itemStackList.add(new ItemFactory("86").display("Pumpkin").build()); + this.itemStackList.add(new ItemFactory("103").display("Melon Block").build()); + this.itemStackList.add(new ItemFactory("360").display("Melon").build()); + this.itemStackList.add(new ItemFactory("363").display("Raw Beef").build()); + this.itemStackList.add(new ItemFactory("364").display("Cooked Beef").build()); + this.itemStackList.add(new ItemFactory("338").display("Sugar Cane").build()); + this.itemStackList.add(new ItemFactory("81").display("Cactus").build()); + this.itemStackList.add(new ItemFactory("319").display("Pork").build()); + this.itemStackList.add(new ItemFactory("320").display("Grilled Pork").build()); + this.itemStackList.add(new ItemFactory("322").display("Golden Apple").build()); + this.itemStackList.add(new ItemFactory("361").display("Pumpkin Seeds").build()); + this.itemStackList.add(new ItemFactory("362").display("Melon Seeds").build()); + this.itemStackList.add(new ItemFactory("295").display("Seeds").build()); + } + return this.itemStackList; + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/ItemFactory.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/ItemFactory.java new file mode 100644 index 0000000..f87d78f --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/ItemFactory.java @@ -0,0 +1,163 @@ +package net.crankedpvp.itemfilter.utils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +public class ItemFactory { + private Material material; + private int amount = 1; + private final short damage = 0; + private byte data = 0; + private boolean glow = false; + private String display = ""; + private List lore = new ArrayList<>(); + + public ItemFactory(Material Material) { + this.material = Material; + } + + public ItemFactory(String String, Material Material) { + String = String.toUpperCase().replace(" ", "_"); + if (String.contains(":")) { + String[] arrayOfString = String.split(":"); + try { + this.material = Material.getMaterial(Integer.parseInt(arrayOfString[0])); + this.material.getData(); + } catch (Exception localException2) { + this.material = Material.getMaterial(arrayOfString[0]); + } + try { + this.data = Byte.parseByte(arrayOfString[1]); + } catch (Exception localException3) { + } + } else { + try { + this.material = Material.getMaterial(Integer.parseInt(String)); + this.material.getData(); + } catch (Exception localException1) { + this.material = Material.getMaterial(String); + } + } + if (this.material == null) { + this.material = Material; + } + } + + public ItemFactory(String String) { + String = String.toUpperCase().replace(" ", "_"); + if (String != null) { + if (String.contains(":")) { + String[] arrayOfString = String.split(":"); + try { + this.material = Material.getMaterial(Integer.parseInt(arrayOfString[0])); + } catch (Exception localException2) { + this.material = Material.getMaterial(arrayOfString[0]); + } + try { + this.data = Byte.parseByte(arrayOfString[1]); + } catch (Exception localException3) { + } + } else { + try { + this.material = Material.getMaterial(Integer.parseInt(String)); + } catch (Exception localException1) { + this.material = Material.getMaterial(String); + } + } + } + } + + public ItemStack build() { + ItemStack localItemStack = new ItemStack(this.material); + localItemStack.setDurability((short) this.data); + if (this.amount > 0) { + localItemStack.setAmount(this.amount); + } else { + localItemStack.setAmount(1); + } + ItemMeta localItemMeta = localItemStack.getItemMeta(); + if (!this.display.equals("")) { + localItemMeta.setDisplayName(this.display); + } + if (this.glow) { + localItemMeta.addEnchant(Enchantment.DURABILITY, 1, true); + localItemMeta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + } + if (!this.lore.isEmpty()) { + localItemMeta.setLore(this.lore); + } + localItemStack.setItemMeta(localItemMeta); + return localItemStack; + } + + public ItemFactory amount(int Int) { + this.amount = Int; + return this; + } + + public ItemFactory display(String String) { + this.display = String; + return this; + } + + public ItemFactory display(char Char, String String) { + this.display = ChatColor.translateAlternateColorCodes(Char, String); + return this; + } + + public ItemFactory lore(List List) { + this.lore = List; + return this; + } + + public ItemFactory lore(char Char, List List) { + for (int i = 0; i < List.size(); i++) { + List.set(i, ChatColor.translateAlternateColorCodes(Char, (String) List.get(i))); + } + this.lore = List; + return this; + } + + public ItemFactory glow(boolean Boolean) { + this.glow = Boolean; + return this; + } + + public static ItemStack getPlayerSkull(String String1, String String2) { + ItemStack localItemStack = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal()); + SkullMeta localSkullMeta = (SkullMeta) localItemStack.getItemMeta(); + localSkullMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', String2)); + localSkullMeta.setOwner(String1); + localItemStack.setItemMeta(localSkullMeta); + return localItemStack; + } + + public static ItemStack replaceInMeta(ItemStack ItemStack, String... VarArgs) { + ItemStack = ItemStack.clone(); + ItemMeta localItemMeta = ItemStack.getItemMeta(); + for (int i = 0; i < VarArgs.length; i += 2) { + if (VarArgs.length > i) { + String str1 = VarArgs[i]; + String str2 = VarArgs[(i + 1)]; + localItemMeta.setDisplayName(localItemMeta.getDisplayName().replace(str1, str2)); + List localList = localItemMeta.hasLore() ? localItemMeta.getLore() : Collections.emptyList(); + for (int j = 0; j < localList.size(); j++) { + localList.set(j, ((String) localList.get(j)).replace(str1, str2)); + } + localItemMeta.setLore(localList); + } + } + ItemStack.setItemMeta(localItemMeta); + return ItemStack; + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/MainInventory.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/MainInventory.java new file mode 100644 index 0000000..d5f2dc4 --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/MainInventory.java @@ -0,0 +1,218 @@ +package net.crankedpvp.itemfilter.utils; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public class MainInventory { + private static MainInventory ourInstance = new MainInventory(); + private Inventory inventory; + + public static MainInventory getInstance() { + return ourInstance; + } + + public Inventory mainInventory(Player paramPlayer) { + int i = roundUpToNine(ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.size")); + String str1 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.title")); + this.inventory = Bukkit.createInventory(null, i, str1); + if ((ItemFilterPlugin.getInstance().getConfig().get("settings.main-inventory.settings.spacers") != null) && + (ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.spacers.enable"))) { + String str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.spacers.name")); + String str3 = ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.settings.spacers.id"); + List localList = ItemFilterPlugin.getInstance().getConfig().getStringList("settings.main-inventory.settings.spacers.lore"); + boolean bool = ItemFilterPlugin.getInstance().getConfig().getBoolean("settings.main-inventory.settings.spacers.glow"); + ItemStack localItemStack = new ItemFactory(str3).display(str2).lore('&', localList).glow(bool).build(); + for (int j = 0; j < i; j++) { + this.inventory.setItem(j, localItemStack); + } + } + if (ItemFilterPlugin.getInstance().getConfig().get("settings.main-inventory.items") != null) { + this.inventory.setItem(ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Equipment.slot"), loadEquipment(paramPlayer)); + this.inventory.setItem(ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Food.slot"), loadFood(paramPlayer)); + this.inventory.setItem(ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Ores.slot"), loadOres(paramPlayer)); + this.inventory.setItem(ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Potion.slot"), loadPotions(paramPlayer)); + this.inventory.setItem(ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Raiding.slot"), loadRaiding(paramPlayer)); + this.inventory.setItem(ItemFilterPlugin.getInstance().getConfig().getInt("settings.main-inventory.items.Specialty.slot"), loadSpecialty(paramPlayer)); + } + paramPlayer.openInventory(this.inventory); + return this.inventory; + } + + private ItemStack loadEquipment(Player paramPlayer) { + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + List itemsList = new ArrayList(); + int i = 1; + List lore = new ArrayList(); + + for (ItemStack localObject : EquipmentInventory.getInstance().getFilterItems() ) { + if (localList1.contains( localObject.getType().name())) { + itemsList.add(ChatColor.stripColor( localObject.getItemMeta().getDisplayName())); + } + } + + Object localObject; + if (!itemsList.isEmpty()) { + i = itemsList.size(); + lore.add(" "); + lore.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-items-line").replace("{0}", String.valueOf(itemsList.size())))); + Iterator localArrayList = itemsList.iterator(); + while (localArrayList.hasNext()) { + localObject = (String) localArrayList.next(); + lore.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-list-format").replace("{1}", (CharSequence) localObject))); + } + } + return new ItemFactory( + ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Equipment.id")) + .display('&', ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Equipment.name")) + .lore(lore) + .amount(i) + .build(); + } + + private ItemStack loadPotions(Player paramPlayer) { + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + ArrayList localArrayList1 = new ArrayList(); + int i = 1; + ArrayList localArrayList2 = new ArrayList(); + for (ItemStack localObject : PotionInventory.getInstance().getFilterItems() ) { + if (localList1.contains( localObject.getType().name())) { + localArrayList1.add(ChatColor.stripColor( localObject.getItemMeta().getDisplayName())); + } + } + Object localObject; + if (!localArrayList1.isEmpty()) { + i = localArrayList1.size(); + localArrayList2.add(" "); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-items-line").replace("{0}", String.valueOf(localArrayList1.size())))); + Iterator localArrayList = localArrayList1.iterator(); + while (localArrayList.hasNext()) { + localObject = (String) localArrayList.next(); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-list-format").replace("{1}", (CharSequence) localObject))); + } + } + return new ItemFactory(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Potion.id")).display('&', ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Potion.name")).lore(localArrayList2).amount(i).build(); + } + + private ItemStack loadRaiding(Player paramPlayer) { + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + ArrayList localArrayList1 = new ArrayList(); + int i = 1; + ArrayList localArrayList2 = new ArrayList(); + for (ItemStack localObject : RaidingInventory.getInstance().getFilterItems() ) { + if (localList1.contains( localObject.getType().name())) { + localArrayList1.add(ChatColor.stripColor( localObject.getItemMeta().getDisplayName())); + } + } + Object localObject; + if (!localArrayList1.isEmpty()) { + i = localArrayList1.size(); + localArrayList2.add(" "); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-items-line").replace("{0}", String.valueOf(localArrayList1.size())))); + Iterator localIterator = localList1.iterator(); + for (localIterator = localArrayList1.iterator(); localIterator.hasNext(); ) { + localObject = (String) localIterator.next(); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-list-format").replace("{1}", (CharSequence) localObject))); + } + } + return new ItemFactory(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Raiding.id")).display('&', ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Raiding.name")).lore(localArrayList2).amount(i).build(); + } + + private ItemStack loadFood(Player paramPlayer) { + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + ArrayList localArrayList1 = new ArrayList(); + int i = 1; + ArrayList localArrayList2 = new ArrayList(); + for (ItemStack localObject : FoodInventory.getInstance().getFilterItems() ) { + if (localList1.contains( localObject.getType().name())) { + localArrayList1.add(ChatColor.stripColor( localObject.getItemMeta().getDisplayName())); + } + } + Object localObject; + if (!localArrayList1.isEmpty()) { + i = localArrayList1.size(); + localArrayList2.add(" "); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-items-line").replace("{0}", String.valueOf(localArrayList1.size())))); + Iterator localArrayList = localArrayList1.iterator(); + while (localArrayList.hasNext()) { + localObject = (String) localArrayList.next(); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-list-format").replace("{1}", (CharSequence) localObject))); + } + } + return new ItemFactory(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Food.id")).display('&', ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Food.name")).lore(localArrayList2).amount(i).build(); + } + + private ItemStack loadSpecialty(Player paramPlayer) { + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + ArrayList localArrayList1 = new ArrayList(); + int i = 1; + ArrayList localArrayList2 = new ArrayList(); + for (ItemStack localObject : SpecialtyInventory.getInstance().getFilterItems() ) { + if (localList1.contains( localObject.getType().name())) { + localArrayList1.add(ChatColor.stripColor( localObject.getItemMeta().getDisplayName())); + } + } + Object localObject; + if (!localArrayList1.isEmpty()) { + i = localArrayList1.size(); + localArrayList2.add(" "); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-items-line").replace("{0}", String.valueOf(localArrayList1.size())))); + Iterator localArrayList = localArrayList1.iterator(); + while (localArrayList.hasNext()) { + localObject = (String) localArrayList.next(); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-list-format").replace("{1}", (CharSequence) localObject))); + } + } + return new ItemFactory(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Specialty.id")).display('&', ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Specialty.name")).lore(localArrayList2).amount(i).build(); + } + + private ItemStack loadOres(Player paramPlayer) { + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + ArrayList localArrayList1 = new ArrayList(); + int i = 1; + ArrayList localArrayList2 = new ArrayList(); + for (ItemStack localObject : OresInventory.getInstance().getFilterItems() ) { + if (localList1.contains( localObject.getType().name())) { + localArrayList1.add(ChatColor.stripColor( localObject.getItemMeta().getDisplayName())); + } + } + Object localObject; + if (!localArrayList1.isEmpty()) { + i = localArrayList1.size(); + localArrayList2.add(" "); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-items-line").replace("{0}", String.valueOf(localArrayList1.size())))); + Iterator localArrayList = localArrayList1.iterator(); + while (localArrayList.hasNext()) { + localObject = (String) localArrayList.next(); + localArrayList2.add(ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.filtered-list-format").replace("{1}", (CharSequence) localObject))); + } + } + return new ItemFactory(ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Ores.id")).display('&', ItemFilterPlugin.getInstance().getConfig().getString("settings.main-inventory.items.Ores.name")).lore(localArrayList2).amount(i).build(); + } + + public int roundUpToNine(int paramInt) { + if (paramInt * 9 <= 9) { + return 9; + } + if (paramInt * 9 <= 18) { + return 18; + } + if (paramInt * 9 <= 27) { + return 27; + } + if (paramInt * 9 <= 36) { + return 36; + } + if (paramInt * 9 <= 45) { + return 45; + } + return 54; + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/OresInventory.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/OresInventory.java new file mode 100644 index 0000000..96d8784 --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/OresInventory.java @@ -0,0 +1,90 @@ +package net.crankedpvp.itemfilter.utils; + +import java.util.ArrayList; +import java.util.List; + +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class OresInventory { + private static OresInventory ourInstance = new OresInventory(); + private Inventory inventory; + + public static OresInventory getInstance() { + return ourInstance; + } + + public Inventory oresInventory(Player paramPlayer) { + String str1 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.ores-inventory.title")); + this.inventory = Bukkit.createInventory(null, 27, str1); + int i = 0; + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + for (ItemStack localItemStack1 : getFilterItems()) { + ItemStack localItemStack2; + ItemMeta localItemMeta; + String str2; + List localList2; + if (localList1.contains(String.valueOf(localItemStack1.getType().name()))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.Will.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.Will.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.setLore(localList2); + localItemMeta.addEnchant(Enchantment.DURABILITY, 1, true); + localItemMeta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } else if (!localList1.contains(String.valueOf(localItemStack1))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.WillNot.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.WillNot.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.removeEnchant(Enchantment.DURABILITY); + localItemMeta.setLore(localList2); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } + i++; + } + paramPlayer.openInventory(this.inventory); + return this.inventory; + } + + private List itemStackList = new ArrayList(); + + public List getFilterItems() { + if (this.itemStackList.isEmpty()) { + this.itemStackList.add(new ItemFactory("15").display("Iron Ore").build()); + this.itemStackList.add(new ItemFactory("265").display("Iron Ingot").build()); + this.itemStackList.add(new ItemFactory("42").display("Iron Block").build()); + this.itemStackList.add(new ItemFactory("14").display("Gold Ore").build()); + this.itemStackList.add(new ItemFactory("266").display("Gold Ingot").build()); + this.itemStackList.add(new ItemFactory("41").display("Gold Block").build()); + this.itemStackList.add(new ItemFactory("73").display("Redstone Ore").build()); + this.itemStackList.add(new ItemFactory("331").display("Redstone Ore").build()); + this.itemStackList.add(new ItemFactory("152").display("Redstone Block").build()); + this.itemStackList.add(new ItemFactory("21").display("Lapis Ore").build()); + this.itemStackList.add(new ItemFactory("351:4").display("Lapis Lazuli").build()); + this.itemStackList.add(new ItemFactory("22").display("Lapis Block").build()); + this.itemStackList.add(new ItemFactory("16").display("Coal Ore").build()); + this.itemStackList.add(new ItemFactory("263").display("Coal").build()); + this.itemStackList.add(new ItemFactory("173").display("Coal Block").build()); + this.itemStackList.add(new ItemFactory("129").display("Emerlad Ore").build()); + this.itemStackList.add(new ItemFactory("388").display("Emerald").build()); + this.itemStackList.add(new ItemFactory("133").display("Emerald Block").build()); + this.itemStackList.add(new ItemFactory("56").display("Diamond Ore").build()); + this.itemStackList.add(new ItemFactory("264").display("Diamond").build()); + this.itemStackList.add(new ItemFactory("57").display("Diamond Block").build()); + } + return this.itemStackList; + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/PotionInventory.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/PotionInventory.java new file mode 100644 index 0000000..7f8338a --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/PotionInventory.java @@ -0,0 +1,90 @@ +package net.crankedpvp.itemfilter.utils; + +import java.util.ArrayList; +import java.util.List; + +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class PotionInventory { + private static PotionInventory ourInstance = new PotionInventory(); + private Inventory inventory; + + public static PotionInventory getInstance() { + return ourInstance; + } + + public Inventory potionInventory(Player paramPlayer) { + String str1 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.potion-inventory.title")); + this.inventory = Bukkit.createInventory(null, 27, str1); + int i = 0; + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + for (ItemStack localItemStack1 : getFilterItems()) { + ItemStack localItemStack2; + ItemMeta localItemMeta; + String str2; + List localList2; + if (localList1.contains(String.valueOf(localItemStack1.getType().name()))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.Will.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.Will.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.setLore(localList2); + localItemMeta.addEnchant(Enchantment.DURABILITY, 1, true); + localItemMeta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } else if (!localList1.contains(String.valueOf(localItemStack1))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.WillNot.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.WillNot.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.removeEnchant(Enchantment.DURABILITY); + localItemMeta.setLore(localList2); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } + i++; + } + paramPlayer.openInventory(this.inventory); + return this.inventory; + } + + private List itemStackList = new ArrayList(); + + public List getFilterItems() { + if (this.itemStackList.isEmpty()) { + this.itemStackList.add(new ItemFactory("375").display("Spider Eye").build()); + this.itemStackList.add(new ItemFactory("378").display("Magma Cream").build()); + this.itemStackList.add(new ItemFactory("370").display("Ghast Tear").build()); + this.itemStackList.add(new ItemFactory("341").display("Slime Ball").build()); + this.itemStackList.add(new ItemFactory("372").display("Nether Stalk").build()); + this.itemStackList.add(new ItemFactory("382").display("Speckled Melon").build()); + this.itemStackList.add(new ItemFactory("353").display("Sugar").build()); + this.itemStackList.add(new ItemFactory("348").display("Glowstone Dust").build()); + this.itemStackList.add(new ItemFactory("89").display("Glowstone").build()); + this.itemStackList.add(new ItemFactory("396").display("Golden Carrot").build()); + this.itemStackList.add(new ItemFactory("373").display("Potions").build()); + this.itemStackList.add(new ItemFactory("374").display("Glass Bottle").build()); + this.itemStackList.add(new ItemFactory("111").display("Water Lily").build()); + this.itemStackList.add(new ItemFactory("391").display("Carrot Item").build()); + this.itemStackList.add(new ItemFactory("406").display("Quartz").build()); + this.itemStackList.add(new ItemFactory("40").display("Red Mushroom").build()); + this.itemStackList.add(new ItemFactory("260").display("Apple").build()); + this.itemStackList.add(new ItemFactory("39").display("Brown Mushroom").build()); + this.itemStackList.add(new ItemFactory("351").display("Ink Sack").build()); + this.itemStackList.add(new ItemFactory("394").display("Poisonous Potato").build()); + this.itemStackList.add(new ItemFactory("322").display("Golden Apple").build()); + } + return this.itemStackList; + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/RaidingInventory.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/RaidingInventory.java new file mode 100644 index 0000000..c3aaea5 --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/RaidingInventory.java @@ -0,0 +1,89 @@ +package net.crankedpvp.itemfilter.utils; + +import java.util.ArrayList; +import java.util.List; + +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class RaidingInventory { + private static RaidingInventory ourInstance = new RaidingInventory(); + private Inventory inventory; + + public static RaidingInventory getInstance() { + return ourInstance; + } + + public Inventory raidingInventory(Player paramPlayer) { + String str1 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.raiding-inventory.title")); + this.inventory = Bukkit.createInventory(null, 27, str1); + int i = 0; + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + for (ItemStack localItemStack1 : getFilterItems()) { + ItemStack localItemStack2; + ItemMeta localItemMeta; + String str2; + List localList2; + if (localList1.contains(String.valueOf(localItemStack1.getType().name()))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.Will.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.Will.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.setLore(localList2); + localItemMeta.addEnchant(Enchantment.DURABILITY, 1, true); + localItemMeta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } else if (!localList1.contains(String.valueOf(localItemStack1))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.WillNot.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.WillNot.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.removeEnchant(Enchantment.DURABILITY); + localItemMeta.setLore(localList2); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } + i++; + } + paramPlayer.openInventory(this.inventory); + return this.inventory; + } + + private List itemStackList = new ArrayList(); + + public List getFilterItems() { + if (this.itemStackList.isEmpty()) { + this.itemStackList.add(new ItemFactory("331").display("Redstone").build()); + this.itemStackList.add(new ItemFactory("123").display("Redstone Lamp").build()); + this.itemStackList.add(new ItemFactory("76").display("Redstone Torch").build()); + this.itemStackList.add(new ItemFactory("73").display("Redstone Ore").build()); + this.itemStackList.add(new ItemFactory("404").display("Redstone Comparator").build()); + this.itemStackList.add(new ItemFactory("356").display("Redstone Repeater").build()); + this.itemStackList.add(new ItemFactory("327").display("Lava Bucket").build()); + this.itemStackList.add(new ItemFactory("326").display("Water Bucket").build()); + this.itemStackList.add(new ItemFactory("46").display("Tnt").build()); + this.itemStackList.add(new ItemFactory("30").display("Web").build()); + this.itemStackList.add(new ItemFactory("19").display("Sponge").build()); + this.itemStackList.add(new ItemFactory("79").display("Ice").build()); + this.itemStackList.add(new ItemFactory("174").display("Packed Ice").build()); + this.itemStackList.add(new ItemFactory("23").display("Dispenser").build()); + this.itemStackList.add(new ItemFactory("158").display("Dropper").build()); + this.itemStackList.add(new ItemFactory("383").display("Spawner Eggs").build()); + this.itemStackList.add(new ItemFactory("33").display("Piston").build()); + this.itemStackList.add(new ItemFactory("29").display("Sticky Piston").build()); + this.itemStackList.add(new ItemFactory("154").display("Hopper").build()); + this.itemStackList.add(new ItemFactory("259").display("Flint And Steel").build()); + } + return this.itemStackList; + } +} diff --git a/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/SpecialtyInventory.java b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/SpecialtyInventory.java new file mode 100644 index 0000000..57778f6 --- /dev/null +++ b/ItemFilter/src/main/java/net/crankedpvp/itemfilter/utils/SpecialtyInventory.java @@ -0,0 +1,91 @@ +package net.crankedpvp.itemfilter.utils; + +import java.util.ArrayList; +import java.util.List; + +import net.crankedpvp.itemfilter.ItemFilterPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class SpecialtyInventory { + private static SpecialtyInventory ourInstance = new SpecialtyInventory(); + private Inventory inventory; + + public static SpecialtyInventory getInstance() { + return ourInstance; + } + + public Inventory specialtyInventory(Player paramPlayer) { + String str1 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.specialty-inventory.title")); + this.inventory = Bukkit.createInventory(null, 27, str1); + int i = 0; + List localList1 = ItemFilterPlugin.getInstance().getFilterManager().getFilterUser(paramPlayer.getUniqueId()).getFilter(); + for (ItemStack localItemStack1 : getFilterItems()) { + ItemStack localItemStack2; + ItemMeta localItemMeta; + String str2; + List localList2; + if (localList1.contains(String.valueOf(localItemStack1.getType().name()))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.Will.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.Will.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.setLore(localList2); + localItemMeta.addEnchant(Enchantment.DURABILITY, 1, true); + localItemMeta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } else if (!localList1.contains(String.valueOf(localItemStack1))) { + localItemStack2 = localItemStack1; + localItemMeta = localItemStack2.getItemMeta(); + str2 = ItemFilterPlugin.color(ItemFilterPlugin.getInstance().getConfig().getString("settings.WillNot.ItemName").replace("{2}", ChatColor.stripColor(localItemStack1.getItemMeta().getDisplayName()))); + localList2 = ItemFilterPlugin.colorList(ItemFilterPlugin.getInstance().getConfig().getStringList("settings.WillNot.ItemLore")); + localItemMeta.setDisplayName(str2); + localItemMeta.removeEnchant(Enchantment.DURABILITY); + localItemMeta.setLore(localList2); + localItemStack2.setItemMeta(localItemMeta); + this.inventory.setItem(i, localItemStack2); + } + i++; + } + paramPlayer.openInventory(this.inventory); + return this.inventory; + } + + private List itemStackList = new ArrayList(); + + public List getFilterItems() { + if (this.itemStackList.isEmpty()) { + this.itemStackList.add(new ItemFactory("52").display("Monster Spawners").build()); + this.itemStackList.add(new ItemFactory("383").display("Spawner Eggs").build()); + this.itemStackList.add(new ItemFactory("421").display("Name Tag").build()); + this.itemStackList.add(new ItemFactory("54").display("Chest").build()); + this.itemStackList.add(new ItemFactory("146").display("Trapped Chest").build()); + this.itemStackList.add(new ItemFactory("130").display("Ender Chest").build()); + this.itemStackList.add(new ItemFactory("339").display("Paper").build()); + this.itemStackList.add(new ItemFactory("395").display("Empty Map").build()); + this.itemStackList.add(new ItemFactory("384").display("Exp Bottle").build()); + this.itemStackList.add(new ItemFactory("76").display("Redstone Torch").build()); + this.itemStackList.add(new ItemFactory("340").display("Book").build()); + this.itemStackList.add(new ItemFactory("351").display("Ink Sack").build()); + this.itemStackList.add(new ItemFactory("50").display("Torch").build()); + this.itemStackList.add(new ItemFactory("388").display("Emerald").build()); + this.itemStackList.add(new ItemFactory("378").display("Magma Cream").build()); + this.itemStackList.add(new ItemFactory("322").display("Golden Apple").build()); + this.itemStackList.add(new ItemFactory("264").display("Diamond").build()); + this.itemStackList.add(new ItemFactory("352").display("Bone").build()); + this.itemStackList.add(new ItemFactory("368").display("Ender Pearl").build()); + this.itemStackList.add(new ItemFactory("369").display("Blaze Rod").build()); + this.itemStackList.add(new ItemFactory("399").display("Nether Star").build()); + this.itemStackList.add(new ItemFactory("402").display("Firework Charge").build()); + } + return this.itemStackList; + } +} diff --git a/ItemFilter/src/main/resources/config.yml b/ItemFilter/src/main/resources/config.yml new file mode 100644 index 0000000..3ce9cfc --- /dev/null +++ b/ItemFilter/src/main/resources/config.yml @@ -0,0 +1,122 @@ +settings: + filtered-items-line: '&4&lFiltered Items (&f{0}&4&l)' + filtered-list-format: '&4&l* &f{1}' + Will: + ItemName: '&a{2}' + ItemLore: + - '&a&lWILL &7be picked up' + - '&7when item filter is &nenabled.' + WillNot: + ItemName: '&c{2}' + ItemLore: + - '&c&lWILL NOT &7be picked up' + - '&7when item filter is &nenabled.' + main-inventory: + title: 'Item Filter Categories' + size: 1 + settings: + # This is the sound effect when a player withdraws a banknote. + # Note: Please use a valid sound effect for the version of minecraft. + # Servers Running 1.9 & Above: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Sound.html + # Servers Running 1.7 or 1.8: http://docs.codelanx.com/Bukkit/1.8/org/bukkit/Sound.html + category-open: + enable: false + sound-effect: 'ENDERMAN_TELEPORT' + sound-volume: 3 + sound-pitch: 1 + # This is the sound effect when a player withdraws a banknote. + # Note: Please use a valid sound effect for the version of minecraft. + # Servers Running 1.9 & Above: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Sound.html + # Servers Running 1.7 or 1.8: http://docs.codelanx.com/Bukkit/1.8/org/bukkit/Sound.html + category-close: + enable: false + sound-effect: 'ENDERDRAGON_WINGS' + sound-volume: 3 + sound-pitch: 1 + # This is the sound effect when a player withdraws a banknote. + # Note: Please use a valid sound effect for the version of minecraft. + # Servers Running 1.9 & Above: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Sound.html + # Servers Running 1.7 or 1.8: http://docs.codelanx.com/Bukkit/1.8/org/bukkit/Sound.html + filter-item-select: + enable: false + sound-effect: 'ANVIL_USE' + sound-volume: 3 + sound-pitch: 1 + spacers: + enable: true + id: STAINED_GLASS_PANE:15 + name: ' ' + lore: [] + glow: false + items: + Equipment: + id: DIAMOND_CHESTPLATE + name: '&c&lEquipment' + slot: 1 + enable: true + Potion: + id: POTION + name: '&c&lPotion Supplies' + slot: 2 + enable: true + Raiding: + id: REDSTONE + name: '&c&lRaiding' + slot: 3 + enable: true + Food: + id: BREAD + name: '&c&lFood' + slot: 5 + enable: true + Specialty: + id: 52 + name: '&c&lSpecialty' + slot: 6 + enable: true + Ores: + id: DIAMOND_ORE + name: '&c&lOres' + slot: 7 + enable: true + equipment-inventory: + title: 'Item Filter: Equipment' + potion-inventory: + title: 'Item Filter: Potion Supplies' + raiding-inventory: + title: 'Item Filter: Raiding' + food-inventory: + title: 'Item Filter: Food' + specialty-inventory: + title: 'Item Filter: Specialty' + ores-inventory: + title: 'Item Filter: Ores' +messages: + item-filter-no-permission: + - '&4[&cSystem&4] &7You don''t have &cpermission&7 for that command!' + item-filter-reload: + - '&a&lItemFilter &ahas successfully reloaded!' + item-filter-reset-self: + - '&aYou have successfully reset your ItemFilter!' + item-filter-reset-other: + - '&aYou have successfully reset {player}''s ItemFilter!' + item-filter-target-not-found: + - '&c&n{player}&c has never joined this server before!' + item-filter-usage: + - '' + - '&c&lItem Filter Commands' + - '&f/filter toggle' + - '&7Toggle item pickup filter.' + - '' + - '&f/filter edit' + - '&7Edit items you pickup while the item filter is enabled.' + - '' + item-filter-enable: + - '' + - '&a&l(!) Item Filter &nEnabled' + - '&7Use &n/filter edit&7 to edit the items you will pickup.' + - '' + item-filter-disable: + - '' + - '&c&l(!) Item Filter &nDisabled' + - '' diff --git a/ItemFilter/src/main/resources/plugin.yml b/ItemFilter/src/main/resources/plugin.yml new file mode 100644 index 0000000..b8990a9 --- /dev/null +++ b/ItemFilter/src/main/resources/plugin.yml @@ -0,0 +1,5 @@ +name: CrankedItemFilter +main: net.crankedpvp.itemfilter.ItemFilterPlugin +version: 1.0 +depend: [CrankedUtils, StorageUtil] +commands: diff --git a/ItemFlip/pom.xml b/ItemFlip/pom.xml new file mode 100644 index 0000000..89bc9c8 --- /dev/null +++ b/ItemFlip/pom.xml @@ -0,0 +1,42 @@ + + + + net.crankedpvp + ProjectCranked + 1.0 + + + 4.0.0 + + ItemFlip + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + com.massivecraft + Factions + + + net.crankedpvp + Collect + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/CrankedItemFlipPlugin.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/CrankedItemFlipPlugin.java new file mode 100644 index 0000000..657c1ad --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/CrankedItemFlipPlugin.java @@ -0,0 +1,53 @@ +package net.crankedpvp.itemflip; + + +import net.crankedpvp.itemflip.commands.CommandItemFlip; +import net.crankedpvp.itemflip.data.ItemFlipData; +import net.crankedpvp.itemflip.data.ItemFlipPlayerData; +import net.crankedpvp.itemflip.listeners.ItemFlipLogicListener; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandExecutor; +import org.bukkit.event.Listener; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +public class CrankedItemFlipPlugin + extends JavaPlugin { + public void onEnable() { + GalacticItemFlipPlugin = this; + registerListeners(); + registerCommands(); + } + + private static CrankedItemFlipPlugin GalacticItemFlipPlugin; + + public void onDisable() { + for (int i = ItemFlipData.getFlipData().size() - 1; i >= 0; i--) { + ItemFlipData data = ItemFlipData.getFlipData().get(i); + if (data.getData().get(0).getPlayer().isOnline()) { + data.getData().get(0).getPlayer().closeInventory(); + } + if (data.getData().get(1).getPlayer().isOnline()) { + data.getData().get(1).getPlayer().closeInventory(); + } + data.remove(); + } + GalacticItemFlipPlugin = null; + } + + private void registerListeners() { + registerListener(new ItemFlipLogicListener()); + } + + private void registerCommands() { + getCommand("itemflip").setExecutor(new CommandItemFlip()); + } + + public static CrankedItemFlipPlugin getInstance() { + return GalacticItemFlipPlugin; + } + + public static void registerListener(Listener listener) { + Bukkit.getPluginManager().registerEvents(listener, GalacticItemFlipPlugin); + } +} diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/commands/CommandItemFlip.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/commands/CommandItemFlip.java new file mode 100644 index 0000000..b27c82a --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/commands/CommandItemFlip.java @@ -0,0 +1,87 @@ +package net.crankedpvp.itemflip.commands; + + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.itemflip.CrankedItemFlipPlugin; +import net.crankedpvp.itemflip.data.ItemFlipData; +import net.crankedpvp.itemflip.data.ItemFlipPlayerData; +import net.crankedpvp.itemflip.enums.Color; +import net.crankedpvp.itemflip.inventory.ItemFlipTradeInventory; +import net.crankedpvp.itemflip.struct.ItemFlipRequest; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; + +public class CommandItemFlip + implements CommandExecutor { + public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] args) { + if (!(sender instanceof Player)) { + return false; + } + + if (!((Player) sender).getLocation().getWorld().getName().equals("world") && !((Player) sender).getLocation().getWorld().getName().equals("nebula")) { + sender.sendMessage(CC.translate("&cYou cannot icf in this world.")); + return false; + } + final Player player = (Player) sender; + if (args.length >= 1) { + Player target = Bukkit.getPlayer(args[0]); + if (target == null || !target.isOnline()) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "That player is not online!"); + return false; + } + if (!target.getLocation().getWorld().getName().equals("world")) { + sender.sendMessage(CC.translate("&cYou cannot icf this person. This person is in a different world.")); + return false; + } + if (target == player) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You " + CC.Underline + "cannot" + CC.Red + " /itemflip yourself!"); + return false; + } + ItemFlipRequest request = ItemFlipRequest.findInstance(player); + if (request != null && request.getSender() == player) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You currently have a pending /itemflip!"); + return false; + } + if (request != null && request.getReceiver() == player) { + if (args[0].equalsIgnoreCase(request.getSender().getName())) { + final Player original_sender = request.getSender(); + original_sender.closeInventory(); + request.remove(); + Bukkit.getScheduler().runTaskLater((Plugin) CrankedItemFlipPlugin.getInstance(), (Runnable) new BukkitRunnable() { + public void run() { + if (!original_sender.isOnline() || !player.isOnline()) { + return; + } + ItemFlipPlayerData data_one = new ItemFlipPlayerData(player, Color.values()[0]); + ItemFlipPlayerData data_two = new ItemFlipPlayerData(original_sender, Color.values()[(Color.values()).length - 1]); + ItemFlipData data = new ItemFlipData(data_one, data_two); + Inventory inventory = ItemFlipTradeInventory.getInventory(data); + player.openInventory(inventory); + original_sender.openInventory(inventory); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 0.75F, 2.0F); + original_sender.playSound(player.getLocation(), Sound.CHEST_OPEN, 0.75F, 2.0F); + } + }, 1L); + } + return false; + } + request = new ItemFlipRequest(player, target); + request.send(); + return false; + } + player.sendMessage(CC.GoldB + CC.Underline + "Item Flip Commands"); + player.sendMessage(CC.Gold + "/itemflip "); + player.sendMessage(CC.Gray + "Sends an item flip request to the specified ."); + player.sendMessage(CC.Gray + "Item Flips are similar to Coin Flips (/cf) but instead of money,"); + player.sendMessage(CC.Gray + "you're wagering items."); + + return false; + } +} diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/data/ItemFlipData.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/data/ItemFlipData.java new file mode 100644 index 0000000..9b1208e --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/data/ItemFlipData.java @@ -0,0 +1,199 @@ +package net.crankedpvp.itemflip.data; + + +import com.google.common.collect.Lists; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.collect.CollectPlugin; +import net.crankedpvp.collect.struct.CollectCategory; +import net.crankedpvp.collect.struct.CollectType; +import net.crankedpvp.crankedutils.HoverText; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.JSONMessage; +import net.crankedpvp.itemflip.enums.Color; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class ItemFlipData { + private static final List flips = Lists.newArrayList(); + private int countdown = -1; + private final List data = Lists.newArrayList(); + private boolean active; + private Color active_color; + + public ItemFlipData(ItemFlipPlayerData data, ItemFlipPlayerData other) { + this.data.add(data); + this.data.add(other); + flips.add(this); + } + + public ItemFlipPlayerData findPlayer(Player player) { + Iterator var2 = this.data.iterator(); + + ItemFlipPlayerData data; + do { + if (!var2.hasNext()) { + return null; + } + + data = (ItemFlipPlayerData) var2.next(); + } while (data.getPlayer() != player); + + return data; + } + + public List getData() { + return this.data; + } + + public int getCountdown() { + return this.countdown; + } + + public boolean isActive() { + return this.active; + } + + public Color getActiveColor() { + return this.active_color; + } + + public void setCountdown(int countdown) { + this.countdown = countdown; + } + + public void setActiveColor(Color active_color) { + this.active_color = active_color; + } + + public void remove() { + if (this.isActive()) { + Color color = this.getActiveColor(); + Color other_color = this.getData().get(0).getColor() == color ? this.getData().get(1).getColor() : this.getData().get(0).getColor(); + Player winner = color == this.getData().get(0).getColor() ? this.getData().get(0).getPlayer() : this.getData().get(1).getPlayer(); + Player loser = winner == this.getData().get(0).getPlayer() ? this.getData().get(1).getPlayer() : this.getData().get(0).getPlayer(); + List items = Lists.newArrayList(); + items.addAll(this.getData().get(0).getItems()); + items.addAll(this.getData().get(1).getItems()); + + CollectPlugin.getInstance().getCollectManager().getOrCreate(winner.getUniqueId().toString()).add(new CollectCategory(CollectType.ITEMFLIP, items.toArray(new ItemStack[items.size() - 1]), CC.RedB + loser.getName() + "'s ItemFlip Items", System.currentTimeMillis())); + + loser.sendMessage(color.getPrefix() + CC.Bold + "(!) " + color.getPrefix() + winner.getName() + " has won the item flip with " + CC.Bold + color.getName() + "!"); + winner.sendMessage(color.getPrefix() + CC.Bold + "(!) " + color.getPrefix() + "You have won the item flip!"); + winner.playSound(winner.getLocation(), Sound.LEVEL_UP, 1.25F, 2.0F); + winner.playSound(winner.getLocation(), Sound.ANVIL_LAND, 1.25F, 2.0F); + FPlayer f_winner = FactionUtils.getFPlayer(winner); + FPlayer f_loser = FactionUtils.getFPlayer(loser); + + for (ItemFlipPlayerData flip_data : this.getData()) { + Player player = flip_data.getPlayer(); + FPlayer fp = FactionUtils.getFPlayer(player); + Relation rel_one = fp.getRelationTo(f_winner); + Relation rel_two = fp.getRelationTo(f_loser); + player.sendMessage(CC.GrayB + "** " + color.getPrefix() + "■ " + rel_one.getColor() + winner.getName() + CC.Gray + " has defeated " + other_color.getPrefix() + "■ " + rel_two.getColor() + loser.getName() + CC.Gray + " in an /itemflip:"); + + for(ItemStack item : items) { + JSONMessage msg = addItemToMessage(new JSONMessage(CC.GrayB + "* "), item); + msg.sendToPlayer(player); + } + } + winner.sendMessage(""); + winner.sendMessage(CC.translate("&3&l(&b&lCOLLECT&3&l)&b The ItemFlip Items from &f" + loser.getName() + "&b have been put into your &f/collect&b.")); + winner.sendMessage(""); + } + + flips.remove(this); + } + + public void setActive(boolean active) { + this.active = active; + } + + public static ItemFlipData findItemFlipData(Player player) { + ItemFlipPlayerData data; + for(ItemFlipData itemFlipData : flips) { + data = itemFlipData.findPlayer(player); + if(data != null) return itemFlipData; + } + return null; + } + + public static boolean isInMemory(ItemFlipData data) { + return flips.contains(data); + } + + public static ItemFlipPlayerData findItemFlipPlayerData(Player player) { + ItemFlipData data = findItemFlipData(player); + return data != null ? data.findPlayer(player) : null; + } + + private static JSONMessage addItemToMessage(JSONMessage msg, ItemStack is) { + HoverText text = is.hasItemMeta() && is.getItemMeta().hasDisplayName() ? formatColors(is.getItemMeta().getDisplayName()) : null; + msg.addItem(is, "" + ChatColor.WHITE + is.getAmount() + "x " + "" + (text != null ? ChatColor.RESET + text.getText() : StringUtils.capitalize(is.getType().name().toLowerCase().replace("_", " "))) + ChatColor.WHITE + " ", text != null && !text.getLastColors().isEmpty() ? text.getLastColors().get(0) : ChatColor.WHITE); + return msg; + } + + private static HoverText formatColors(String s) { + HoverText text = new HoverText(); + StringBuilder main = new StringBuilder(); + if (s.contains(" ")) { + List letterColors = new ArrayList(); + String[] var4 = s.split(" "); + + for(String word : var4) { + boolean foundColorChar = false; + boolean lastLetterLegit = true; + StringBuilder newWord = new StringBuilder(); + char[] var11 = word.toCharArray(); + + for(char c : var11) { + if(c == 167) { + foundColorChar = true; + if(lastLetterLegit) { + letterColors.clear(); + lastLetterLegit = false; + } + } else if(foundColorChar) { + ChatColor color = ChatColor.getByChar(c); + if(color != null) { + letterColors.add(color); + } + + foundColorChar = false; + } else { + + for(ChatColor color : letterColors) { + if(color != null) { + newWord.append(color); + } + } + + newWord.append(c); + lastLetterLegit = true; + } + } + + newWord.append(" "); + main.append(newWord); + } + } else { + main.append(s); + } + + text.setText(main.toString().trim()); + return text; + } + + public static List getFlipData() { + return flips; + } +} diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/data/ItemFlipPlayerData.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/data/ItemFlipPlayerData.java new file mode 100644 index 0000000..7bb5486 --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/data/ItemFlipPlayerData.java @@ -0,0 +1,45 @@ +package net.crankedpvp.itemflip.data; + +import com.google.common.collect.Lists; +import net.crankedpvp.itemflip.enums.Color; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class ItemFlipPlayerData { + private Player player; + private Color color; + private List items; + private boolean accepted; + + public ItemFlipPlayerData(Player player, Color color) { + this.player = player; + this.color = color; + this.items = Lists.newArrayList(); + } + + public Player getPlayer() { + return this.player; + } + + public Color getColor() { + return this.color; + } + + public void setAccepted(boolean accepted) { + this.accepted = accepted; + } + + public void setColor(Color color) { + this.color = color; + } + + public boolean isAccepted() { + return this.accepted; + } + + public List getItems() { + return this.items; + } +} diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/enums/Color.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/enums/Color.java new file mode 100644 index 0000000..c4b9411 --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/enums/Color.java @@ -0,0 +1,42 @@ + +package net.crankedpvp.itemflip.enums; + +import org.bukkit.ChatColor; + +public enum Color { + BLUE("Blue", ChatColor.BLUE, 3), + YELLOW("Yellow", ChatColor.YELLOW, 4), + PURPLE("Purple", ChatColor.LIGHT_PURPLE, 10), + RED("Red", ChatColor.RED, 14), + GREEN("Green", ChatColor.GREEN, 13), + BLACK("Black", ChatColor.BLACK, 15), + ORANGE("Orange", ChatColor.GOLD, 1), + WHITE("White", ChatColor.WHITE, 0), + GRAY("Gray", ChatColor.GRAY, 7); + + private String name; + private ChatColor prefix; + private short id; + + private Color(String name, ChatColor prefix, int id) { + this.name = name; + this.prefix = prefix; + this.id = (short)id; + } + + public String getName() { + return this.name; + } + + public ChatColor getPrefix() { + return this.prefix; + } + + public short getId() { + return this.id; + } + + public String getPrefixedName() { + return this.getPrefix() + this.getName(); + } +} diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/inventory/ItemFlipActiveInventory.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/inventory/ItemFlipActiveInventory.java new file mode 100644 index 0000000..618fc1a --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/inventory/ItemFlipActiveInventory.java @@ -0,0 +1,48 @@ + +package net.crankedpvp.itemflip.inventory; + + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.itemflip.data.ItemFlipData; +import net.crankedpvp.itemflip.enums.Color; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +public class ItemFlipActiveInventory { + public static Inventory getInventory(ItemFlipData data) { + Inventory inventory = Bukkit.createInventory(null, 9, CC.Gray + "Active Item Flip"); + inventory.setItem(0, getHead(data.getData().get(0).getColor(), data.getData().get(0).getPlayer())); + inventory.setItem(8, getHead(data.getData().get(1).getColor(), data.getData().get(1).getPlayer())); + inventory.setItem(1, getPane(data.getData().get(0).getColor(), data.getData().get(0).getPlayer())); + inventory.setItem(7, getPane(data.getData().get(1).getColor(), data.getData().get(1).getPlayer())); + if (data.getActiveColor() != null) { + inventory.setItem(4, getActiveFlipPane(data.getActiveColor())); + } + + return inventory; + } + + private static ItemStack getHead(Color color, Player taker) { + ItemStack item = (new ItemBuilder(Material.SKULL_ITEM)).setDurability((short)3).setName(CC.WhiteB + taker.getName()).setLore(CC.Green + "Balance: $" + NumberUtils.formatMoney(EconomyUtils.getBalance(taker))).build(); + SkullMeta meta = (SkullMeta)item.getItemMeta(); + String name = taker.getName(); + meta.setOwner(name); + item.setItemMeta(meta); + return item; + } + + private static ItemStack getPane(Color color, Player taker) { + return (new ItemBuilder(Material.STAINED_GLASS_PANE)).setDurability(color.getId()).setName(color.getPrefix() + CC.Bold + color.getName()).setDurability(color.getId()).setLore(CC.Gray + taker.getName() + "'s Color").build(); + } + + private static ItemStack getActiveFlipPane(Color color) { + return (new ItemBuilder(Material.STAINED_GLASS)).setDurability(color.getId()).setName(color.getPrefix() + CC.Bold + color.getName()).setDurability(color.getId()).build(); + } +} diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/inventory/ItemFlipTradeInventory.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/inventory/ItemFlipTradeInventory.java new file mode 100644 index 0000000..9f00235 --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/inventory/ItemFlipTradeInventory.java @@ -0,0 +1,82 @@ +package net.crankedpvp.itemflip.inventory; + + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.itemflip.data.ItemFlipData; +import net.crankedpvp.itemflip.data.ItemFlipPlayerData; +import net.crankedpvp.itemflip.enums.Color; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +public class ItemFlipTradeInventory { + public static Inventory getInventory(ItemFlipData flip) { + ItemFlipPlayerData data = flip.getData().get(0); + ItemFlipPlayerData other = flip.getData().get(1); + Inventory inventory = Bukkit.createInventory(null, 54, CC.Gray + "Item Flip Inventory"); + inventory.setItem(0, getStakeAcceptPane((flip.getCountdown() > 0) ? flip.getCountdown() : 1, data.isAccepted())); + inventory.setItem(8, getStakeAcceptPane((flip.getCountdown() > 0) ? flip.getCountdown() : 1, other.isAccepted())); + Iterator colors = Arrays.asList(Color.values()).iterator(); + for (int i = inventory.getSize() - 9; i < inventory.getSize() && + colors.hasNext(); i++) { + Color color = colors.next(); + inventory.setItem(i, getColorPane(color, (data.getColor() == color) ? data.getPlayer() : ( + (other.getColor() == color) ? other.getPlayer() : null))); + } + ItemStack pane = (new ItemBuilder(Material.STAINED_GLASS_PANE)).setDurability((short)7).setName(CC.GrayB).build(); + int j; + for (j = 4; j < inventory.getSize() - 18; j += 9) + inventory.setItem(j, pane); + for (j = 36; j < 45; j++) + inventory.setItem(j, pane); + List slots = Arrays.asList(1, 2, 3, 9, 10, 11, 12, 18, 19, 20, + 21, 27, 28, 29, 30); + int k; + for (k = 0; k < data.getItems().size(); k++) + inventory.setItem(slots.get(k), data.getItems().get(k)); + slots = Arrays.asList(5, 6, 7, 14, 15, 16, 17, 23, 24, 25, + 26, 32, 33, 34, 35); + for (k = 0; k < other.getItems().size(); k++) + inventory.setItem(slots.get(k), other.getItems().get(k)); + return inventory; + } + + private static ItemStack getStakeAcceptPane(int amount, boolean accepted) { + return (new ItemBuilder(Material.STAINED_GLASS_PANE)).setDurability((short)(accepted ? 5 : 14)).setName(accepted ? (CC.Green + "Stakes Accepted") : (CC.Red + "Stakes Declined")).setLore(accepted ? (CC.Gray + "Modify the stakes to cancel.") : (CC.Gray + "Click to accept the stake.")).setAmount(amount).build(); + } + + private static ItemStack getColorPane(Color color, Player taker) { + ItemBuilder builder = (new ItemBuilder(Material.WOOL)).setDurability(color.getId()).setName(color.getPrefix() + CC.Bold + color.getName()); + if (taker != null) + builder.setLore(color.getPrefix() + taker.getName()); + ItemStack item = builder.build(); + NBTItem wrapper = new NBTItem(item); + wrapper.setString("item_flip_color", color.name()); + item = wrapper.getItem(); + if (taker != null) { + addGlow(item); + } + return item; + } + + private static ItemStack setAmount(ItemStack item, int amount) { + item.setAmount(amount); + return item; + } + + public static void addGlow(ItemStack item) { + ItemMeta meta = item.getItemMeta(); + meta.addEnchant(Enchantment.DURABILITY, 10, true); + item.setItemMeta(meta); + } +} diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/listeners/ItemFlipLogicListener.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/listeners/ItemFlipLogicListener.java new file mode 100644 index 0000000..b7e0c77 --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/listeners/ItemFlipLogicListener.java @@ -0,0 +1,191 @@ +package net.crankedpvp.itemflip.listeners; + + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.itemflip.CrankedItemFlipPlugin; +import net.crankedpvp.itemflip.data.ItemFlipData; +import net.crankedpvp.itemflip.data.ItemFlipPlayerData; +import net.crankedpvp.itemflip.enums.Color; +import net.crankedpvp.itemflip.inventory.ItemFlipTradeInventory; +import net.crankedpvp.itemflip.struct.ItemFlipRequest; +import net.crankedpvp.itemflip.tasks.TradeCountdownTask; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +public class ItemFlipLogicListener implements Listener { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onClick(InventoryClickEvent event) { + List slots; + List items; + if (event.getInventory().getTitle().equals(CC.Gray + "Active Item Flip")) { + event.setCancelled(true); + return; + } + if (event.getInventory().getTitle().contentEquals(CC.Gray + "Item Flip Inventory")) + event.setCancelled(true); + Player player = (Player)event.getWhoClicked(); + ItemFlipData data = ItemFlipData.findItemFlipData(player); + if (data == null) + return; + event.setCancelled(true); + if (data.isActive()) + return; + int slot = event.getSlot(); + Inventory inventory = event.getInventory(); + ItemStack item = event.getCurrentItem(); + if (data.getData().get(0).getPlayer() == player) { + slots = Arrays.asList(1, 2, 3, 9, 10, 11, 12, 18, 19, 20, + 21, 27, 28, 29, 30); + items = data.getData().get(0).getItems(); + } else { + slots = Arrays.asList(5, 6, 7, 14, 15, 16, 17, 23, 24, 25, + 26, 32, 33, 34, 35); + items = data.getData().get(1).getItems(); + } + if (inventory != event.getClickedInventory()) { + if (item == null || item.getType() == Material.AIR) + return; + for(Integer integer : slots) { + int pos = integer; + if(inventory.getItem(pos) == null || inventory.getItem(pos).getType() == Material.AIR) { + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 50.0F, 50.0F); + items.add(event.getCurrentItem().clone()); + event.setCurrentItem(null); + ItemFlipPlayerData flip_data = (player == data.getData().get(0).getPlayer()) ? data.getData().get(0) : data.getData().get(1); + flip_data.setAccepted(false); + data.setCountdown(-1); + Inventory refresh_inventory = ItemFlipTradeInventory.getInventory(data); + for(int i = 0; i < refresh_inventory.getSize(); i++) { + ItemStack new_item = refresh_inventory.getItem(i); + inventory.setItem(i, new_item); + } + data.getData().get(0).getPlayer().updateInventory(); + data.getData().get(1).getPlayer().updateInventory(); + return; + } + } + return; + } + if (item != null && item.getType() != Material.AIR && slots.contains(slot)) { + items.remove(item); + event.setCurrentItem(null); + Inventory refresh_inventory = ItemFlipTradeInventory.getInventory(data); + Bukkit.getScheduler().runTaskLater(CrankedItemFlipPlugin.getInstance(), () -> player.getInventory().addItem(new ItemStack[] { item }), 20L); + ItemFlipPlayerData flip_data = (player == data.getData().get(0).getPlayer()) ? data.getData().get(0) : data.getData().get(1); + flip_data.setAccepted(false); + data.setCountdown(-1); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 50.0F, 50.0F); + for (int i = 0; i < refresh_inventory.getSize(); i++) { + ItemStack new_item = refresh_inventory.getItem(i); + inventory.setItem(i, new_item); + } + data.getData().get(0).getPlayer().updateInventory(); + data.getData().get(1).getPlayer().updateInventory(); + return; + } + if (item != null && item.getType() != Material.AIR && (new NBTItem(item)).hasKey("item_flip_color")) { + Color color = Color.valueOf((new NBTItem(item)).getString("item_flip_color")); + ItemFlipPlayerData flip_data = (player == data.getData().get(0).getPlayer()) ? data.getData().get(0) : data.getData().get(1); + if (color == data.getData().get(0).getColor() || color == data.getData().get(1).getColor()) + return; + flip_data.setColor(color); + Inventory refresh_inventory = ItemFlipTradeInventory.getInventory(data); + for (int i = 0; i < refresh_inventory.getSize(); i++) { + ItemStack new_item = refresh_inventory.getItem(i); + inventory.setItem(i, new_item); + } + data.getData().get(0).getPlayer().updateInventory(); + data.getData().get(1).getPlayer().updateInventory(); + return; + } + if ((slot == 0 && player == data.getData().get(0).getPlayer()) || (slot == 8 && player == data.getData().get(1).getPlayer())) { + if (data.getCountdown() != -1 && (!data.getData().get(0).isAccepted() || !data.getData().get(1).isAccepted())) + return; + ItemFlipPlayerData flip_data = (player == data.getData().get(0).getPlayer()) ? data.getData().get(0) : data.getData().get(1); + if (flip_data.getItems().size() == 0) { + player.playSound(player.getLocation(), Sound.ITEM_BREAK, 0.75F, 2.0F); + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You must wager atleast one item!"); + return; + } + if (data.getData().get(0).isAccepted() && data.getData().get(1).isAccepted()) + data.setCountdown(-1); + flip_data.setAccepted(!flip_data.isAccepted()); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 25.0F, 25.0F); + Inventory refresh_inventory = ItemFlipTradeInventory.getInventory(data); + for (int i = 0; i < refresh_inventory.getSize(); i++) { + ItemStack new_item = refresh_inventory.getItem(i); + inventory.setItem(i, new_item); + } + data.getData().get(0).getPlayer().updateInventory(); + data.getData().get(1).getPlayer().updateInventory(); + if (data.getData().get(0).isAccepted() && data.getData().get(1).isAccepted()) { + data.setCountdown(10); + (new TradeCountdownTask(data, inventory)).runTaskTimer(CrankedItemFlipPlugin.getInstance(), 20L, 20L); + } + } + } + + @EventHandler + public void onLeave(PlayerQuitEvent event) { + Player player = event.getPlayer(); + ItemFlipData data = ItemFlipData.findItemFlipData(player); + if (data != null && data.isActive()) + data.remove(); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryClose(InventoryCloseEvent event) { + Player player = (Player)event.getPlayer(); + ItemFlipData data = ItemFlipData.findItemFlipData(player); + if (data == null || data.isActive()) + return; + Player other = (player == data.getData().get(0).getPlayer()) ? data.getData().get(1).getPlayer() : data.getData().get(0).getPlayer(); + data.remove(); + other.sendMessage(CC.RedB + "(!) " + CC.Red + player.getName() + " has closed out of the Item Flip Inventory!"); + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You have closed out of the item flip inventory!"); + other.closeInventory(); + data.getData().get(0).getItems().forEach(item -> data.getData().get(0).getPlayer().getInventory().addItem(new ItemStack[] { item })); + data.getData().get(1).getItems().forEach(item -> data.getData().get(1).getPlayer().getInventory().addItem(new ItemStack[] { item })); + } + + @EventHandler + public void onFlipRequestLogout(PlayerQuitEvent event) { + Player player = event.getPlayer(); + ItemFlipRequest request = ItemFlipRequest.findInstance(player); + if (request != null) + request.remove(); + } + + @EventHandler + public void onTeleport(PlayerTeleportEvent e) { + if (e.getTo().getWorld().getName().equals("world") || e.getTo().getWorld().getName().equals("flat")) + + return; + Player player = e.getPlayer(); + ItemFlipRequest request = ItemFlipRequest.findInstance(player); + if (request == null) return; + Player sender = request.getSender(); + Player receiver = request.getReceiver(); + request.remove(); + if (sender.isOnline()) + sender.sendMessage(CC.RedB + "(/ITEMFLIP) " + CC.Red + "Your Item Flip Request to " + receiver.getName() + " has expired!"); + if (receiver.isOnline()) + receiver.sendMessage(CC.RedB + "(/ITEMFLIP) " + CC.Red + sender.getName() + "'s Item Flip Request to you has expired!"); + } +} diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/struct/ItemFlipRequest.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/struct/ItemFlipRequest.java new file mode 100644 index 0000000..ed39e9e --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/struct/ItemFlipRequest.java @@ -0,0 +1,81 @@ + package net.crankedpvp.itemflip.struct; + + import com.google.common.collect.Lists; + import net.crankedpvp.crankedutils.utils.CC; + import net.crankedpvp.itemflip.CrankedItemFlipPlugin; + import org.bukkit.Bukkit; + import org.bukkit.entity.Player; + import org.bukkit.plugin.Plugin; + import org.bukkit.scheduler.BukkitRunnable; + + import java.util.List; + + + public class ItemFlipRequest + { + private static List requests = Lists.newArrayList(); + + private Player sender; + private Player receiver; + private long created; + + public ItemFlipRequest(Player sender, Player receiver) { + this.sender = sender; + this.receiver = receiver; + requests.add(this); + } + + public Player getSender() { + return this.sender; + } + + public Player getReceiver() { + return this.receiver; + } + + public long getTimeout() { + return this.created + 10000L - System.currentTimeMillis(); + } + + public boolean canTimeout() { + return (getTimeout() <= 0L); + } + + public void remove() { + requests.remove(this); + } + + public void send() { + this.created = System.currentTimeMillis(); + this.sender.sendMessage(""); + this.sender.sendMessage(CC.GoldB + "(/ITEMFLIP) " + CC.Gold + "You sent an Item Flip Request to " + CC.Gray + this.receiver.getName() + CC.Gold + "!"); + this.sender.sendMessage(""); + this.receiver.sendMessage(""); + this.receiver.sendMessage(CC.GoldB + "(/ITEMFLIP " + this.sender.getName() + ") " + CC.Gold + "You have received a /itemflip request from " + CC.Gray + this.sender.getName() + CC.Gold + "!"); + this.receiver.sendMessage(""); + final ItemFlipRequest instance = this; + Bukkit.getScheduler().runTaskLater((Plugin) CrankedItemFlipPlugin.getInstance(), (Runnable)new BukkitRunnable() + { + public void run() { + if (ItemFlipRequest.requests.contains(instance)) { + ItemFlipRequest.requests.remove(instance); + if (ItemFlipRequest.this.sender.isOnline()) { + ItemFlipRequest.this.sender.sendMessage(CC.RedB + "(/ITEMFLIP) " + CC.Red + "Your Item Flip Request to " + ItemFlipRequest.this.receiver.getName() + " has expired!"); + } + if (ItemFlipRequest.this.receiver.isOnline()) { + ItemFlipRequest.this.receiver.sendMessage(CC.RedB + "(/ITEMFLIP) " + CC.Red + ItemFlipRequest.this.sender.getName() + "'s Item Flip Request to you has expired!"); + } + } + } + }, 200L); + } + + public static ItemFlipRequest findInstance(Player player) { + for (ItemFlipRequest request : requests) { + if (request.getReceiver() == player || request.getSender() == player) { + return request; + } + } + return null; + } + } diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/tasks/ItemFlipTask.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/tasks/ItemFlipTask.java new file mode 100644 index 0000000..bb4ef93 --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/tasks/ItemFlipTask.java @@ -0,0 +1,67 @@ + package net.crankedpvp.itemflip.tasks; + + + import net.crankedpvp.itemflip.CrankedItemFlipPlugin; + import net.crankedpvp.itemflip.data.ItemFlipData; + import net.crankedpvp.itemflip.data.ItemFlipPlayerData; + import net.crankedpvp.itemflip.enums.Color; + import net.crankedpvp.itemflip.inventory.ItemFlipActiveInventory; + import org.bukkit.Bukkit; + import org.bukkit.Sound; + import org.bukkit.entity.Player; + import org.bukkit.inventory.Inventory; + import org.bukkit.inventory.ItemStack; + import org.bukkit.plugin.Plugin; + import org.bukkit.scheduler.BukkitRunnable; + + public class ItemFlipTask + extends BukkitRunnable { + private final ItemFlipData data; + + public ItemFlipTask(final ItemFlipData data) { + this.data = data; + this.ticks = 0; + this.inventory = ItemFlipActiveInventory.getInventory(this.data); + this.data.setActive(true); + this.data.getData().get(0).getPlayer().closeInventory(); + this.data.getData().get(1).getPlayer().closeInventory(); + Bukkit.getScheduler().runTaskLater(CrankedItemFlipPlugin.getInstance(), (Runnable)new BukkitRunnable() + { + public void run() { + if (!ItemFlipData.isInMemory(data)) { + return; + } + data.getData().get(0).getPlayer().openInventory(ItemFlipTask.this.inventory); + data.getData().get(1).getPlayer().openInventory(ItemFlipTask.this.inventory); + } + }, 1L); + } + private int ticks; private final Inventory inventory; + + public void run() { + if (!ItemFlipData.isInMemory(this.data)) { + return; + } + Color color_one = this.data.getData().get(0).getColor(); + Color color_two = this.data.getData().get(1).getColor(); + Color new_color = (Math.random() < 0.5D) ? color_one : color_two; + this.data.setActiveColor(new_color); + Player sender = this.data.getData().get(0).getPlayer(); + Player receiver = this.data.getData().get(1).getPlayer(); + sender.playSound(sender.getLocation(), Sound.ORB_PICKUP, 25.0F, 25.0F); + receiver.playSound(receiver.getLocation(), Sound.ORB_PICKUP, 25.0F, 25.0F); + Inventory refresh_inventory = ItemFlipActiveInventory.getInventory(this.data); + for (int i = 0; i < refresh_inventory.getSize(); i++) { + ItemStack new_item = refresh_inventory.getItem(i); + this.inventory.setItem(i, new_item); + } + sender.updateInventory(); + receiver.updateInventory(); + this.ticks++; + if (this.ticks >= 16) { + cancel(); + this.data.remove(); + return; + } + } + } diff --git a/ItemFlip/src/main/java/net/crankedpvp/itemflip/tasks/TradeCountdownTask.java b/ItemFlip/src/main/java/net/crankedpvp/itemflip/tasks/TradeCountdownTask.java new file mode 100644 index 0000000..588ce1b --- /dev/null +++ b/ItemFlip/src/main/java/net/crankedpvp/itemflip/tasks/TradeCountdownTask.java @@ -0,0 +1,50 @@ +package net.crankedpvp.itemflip.tasks; + + +import net.crankedpvp.itemflip.CrankedItemFlipPlugin; +import net.crankedpvp.itemflip.data.ItemFlipData; +import net.crankedpvp.itemflip.data.ItemFlipPlayerData; +import net.crankedpvp.itemflip.inventory.ItemFlipTradeInventory; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; + +public class TradeCountdownTask extends BukkitRunnable { + private final ItemFlipData data; + + public TradeCountdownTask(ItemFlipData data, Inventory inventory) { + this.data = data; + this.inventory = inventory; + } + + private final Inventory inventory; + + public void run() { + if (!ItemFlipData.isInMemory(this.data)) { + cancel(); + return; + } + if (!this.data.getData().get(0).isAccepted() || !this.data.getData().get(1).isAccepted()) { + this.data.setCountdown(-1); + cancel(); + return; + } + Inventory inventory = ItemFlipTradeInventory.getInventory(this.data); + for (int i = 0; i < inventory.getSize(); i++) { + this.inventory.setItem(i, inventory.getItem(i)); + } + Player sender = this.data.getData().get(0).getPlayer(); + Player receiver = this.data.getData().get(1).getPlayer(); + sender.updateInventory(); + receiver.updateInventory(); + sender.playSound(sender.getLocation(), Sound.ORB_PICKUP, 25.0F, 25.0F); + receiver.playSound(receiver.getLocation(), Sound.ORB_PICKUP, 25.0F, 25.0F); + this.data.setCountdown(this.data.getCountdown() - 1); + if (this.data.getCountdown() <= -1) { + (new ItemFlipTask(this.data)).runTaskTimer(CrankedItemFlipPlugin.getInstance(), 5L, 5L); + cancel(); + } + } +} diff --git a/ItemFlip/src/main/resources/plugin.yml b/ItemFlip/src/main/resources/plugin.yml new file mode 100644 index 0000000..f449baf --- /dev/null +++ b/ItemFlip/src/main/resources/plugin.yml @@ -0,0 +1,13 @@ +name: CrankedItemFlip +main: net.crankedpvp.itemflip.CrankedItemFlipPlugin +version: ${git.total.commit.count}.0 +commands: + itemflip: + description: /itemflip + aliases: [iflip, icf] +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - StorageUtil + - CrankedCollect \ No newline at end of file diff --git a/Keys/pom.xml b/Keys/pom.xml new file mode 100644 index 0000000..4c98c48 --- /dev/null +++ b/Keys/pom.xml @@ -0,0 +1,43 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Keys + + + 8 + 8 + + + + Utils + net.crankedpvp + + + LootFilter + net.crankedpvp + + + net.crankedpvp + Leaderboards + + + LootTable + net.crankedpvp + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + \ No newline at end of file diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/CrankedCrateKeysAPI.java b/Keys/src/main/java/net/crankedpvp/cratekeys/CrankedCrateKeysAPI.java new file mode 100644 index 0000000..9ce74ce --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/CrankedCrateKeysAPI.java @@ -0,0 +1,193 @@ +package net.crankedpvp.cratekeys; + +import com.google.common.collect.Lists; +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.cratekeys.data.CrateData; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.cratekeys.items.CrateKeyItem; +import net.crankedpvp.cratekeys.managers.CrateDataManager; +import net.crankedpvp.lootfilter.LootFilterAPI; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.data.LootTable; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Map; + +public class CrankedCrateKeysAPI { + public static void addCrate(CrateKeyType type, Location location) { + FileConfiguration file = CrankedCrateKeysPlugin.getInstance().getConfig(); + List crates = file.contains("crates") ? file.getStringList("crates") : Lists.newArrayList(); + crates.add(type.name() + ":" + toStringLocation(location)); + file.set("crates", crates); + CrankedCrateKeysPlugin.getInstance().saveConfig(); + CrankedCrateKeysPlugin.getInstance().reloadConfig(); + } + + + public static void givePlayerKeys(Player player, CrateKeyType type, int amount) { + while (amount != 0) { + PlayerUtils.giveOrDropProtectedItem(player, CrateKeyItem.getItem(type), 60); + amount--; + } + } + + public static void giveCrateKeyLoot(Player player, LootTableType type) { + LootFilterAPI.giveLootTableItem(player, type, LootTableAPI.getRandomLootItem(type)); + /* + ItemStack item = LootTableAPI.getRandomLootItem(type); + //getRandomItem(CrankedCrateKeysPlugin.getInstance().getCrateLootManager().getCachedCrateLoot().get(type)); + PlayerUtils.giveOrDropProtectedItem(player, item, 60); + + */ + + } + + public static Double getTotalPercentageOfItems(Map items) { + double totalPercentage = 0.0D; + for (Map.Entry entry : items.entrySet()) + totalPercentage += entry.getValue(); + return totalPercentage; + } + + /* + public static ItemStack getRandomItem(Map items) { + double totalPercentage = getTotalPercentageOfItems(items); + double find = ThreadLocalRandom.current().nextDouble(0.0D, totalPercentage); + double total = 0.0D; + for (Map.Entry entry : items.entrySet()) { + double value = entry.getValue(); + if (value + total >= find) + return entry.getKey(); + total += value; + } + return null; + } + + */ + + public static boolean isCrateKey(ItemStack item) { + if (ItemUtils.isAirOrNull(item)) + return false; + NBTItem wrapper = new NBTItem(item); + if (!wrapper.hasKey("cosmicData")) + return false; + NBTCompound tag = wrapper.getCompound("cosmicData"); + if (tag == null) return false; + return tag.hasKey("crate_type"); + } + + public static void removeCrate(Location location) { + FileConfiguration file = CrankedCrateKeysPlugin.getInstance().getConfig(); + String loc = toStringLocation(location); + List crates = file.contains("crates") ? file.getStringList("crates") : Lists.newArrayList(); + for (int i = 0; i < crates.size(); i++) { + if (crates.get(i).split(":")[1].equals(loc)) { + crates.remove(i); + file.set("crates", crates); + CrankedCrateKeysPlugin.getInstance().saveConfig(); + CrankedCrateKeysPlugin.getInstance().reloadConfig(); + } + } + } + + public static void clearCrates() { + CrateDataManager.clearCrates(); + } + + public static void deleteCrates() { + FileConfiguration file = CrankedCrateKeysPlugin.getInstance().getConfig(); + file.set("crates", null); + CrankedCrateKeysPlugin.getInstance().saveConfig(); + CrankedCrateKeysPlugin.getInstance().reloadConfig(); + } + + public static List getCrates() { + List crates = Lists.newArrayList(); + FileConfiguration file = CrankedCrateKeysPlugin.getInstance().getConfig(); + List list = file.contains("crates") ? file.getStringList("crates") : Lists.newArrayList(); + for (String data : list) { + String[] split = data.split(":"); + crates.add(new CrateData(CrateKeyType.valueOf(split[0]), fromStringLocation(split[1]))); + } + return crates; + } + + public static CrateData findCrate(Location location) { + List crates = CrateDataManager.getCrates(); + for (CrateData data : crates) { + if (data.getLocation().getX() == location.getX() && + data.getLocation().getY() == location.getY() && data.getLocation().getZ() == location.getZ() && + data.getLocation().getWorld().getName().equals(location.getWorld().getName())) + return data; + } + return null; + } + + public static String toStringLocation(Location location) { + double x = location.getX(); + double y = location.getY(); + double z = location.getZ(); + float yaw = location.getYaw(); + float pitch = location.getPitch(); + String world = location.getWorld().getName(); + String result = world + " " + x + " " + y + " " + z + " " + yaw + " " + pitch; + return result; + } + + public static Location fromStringLocation(String location) { + String[] list = location.split(" "); + World world = Bukkit.getWorld(list[0]); + double x = Double.parseDouble(list[1]); + double y = Double.parseDouble(list[2]); + double z = Double.parseDouble(list[3]); + float yaw = Float.parseFloat(list[4]); + float pitch = Float.parseFloat(list[5]); + Location l = new Location(world, x, y, z); + l.setPitch(pitch); + l.setYaw(yaw); + return l; + } + + + /* + public static void setItems(CrateType type, Map items) { + String key = type.name().toLowerCase() + ".items"; + List list = Lists.newArrayList(); + for (Map.Entry entry : items.entrySet()) { + list.add(ItemStackSerializer.serialize(entry.getKey()) + ":" + entry.getValue()); + } + CrankedCrateKeysPlugin.getInstance().getConfig().set(key, list); + CrankedCrateKeysPlugin.getInstance().saveConfig(); + CrankedCrateKeysPlugin.getInstance().reloadConfig(); + } + + */ + + /* + public static Map getItems(CrateType type) { + String key = type.name().toLowerCase() + ".items"; + if (!CrankedCrateKeysPlugin.getInstance().getConfig().contains(key)) + return Maps.newLinkedHashMap(); + Map map = Maps.newLinkedHashMap(); + List items = CrankedCrateKeysPlugin.getInstance().getConfig().getStringList(key); + for (String item : items) { + String[] split = item.split(":"); + map.put(ItemStackSerializer.deserialize(split[0]), Double.valueOf(split[1])); + } + return map; + } + + */ + +} diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/CrankedCrateKeysPlugin.java b/Keys/src/main/java/net/crankedpvp/cratekeys/CrankedCrateKeysPlugin.java new file mode 100644 index 0000000..d26795e --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/CrankedCrateKeysPlugin.java @@ -0,0 +1,66 @@ +package net.crankedpvp.cratekeys; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.cratekeys.commands.CommandAdminCrate; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.cratekeys.listeners.CrateKeyInventoryListener; +import net.crankedpvp.cratekeys.listeners.CrateLogicListener; +import net.crankedpvp.cratekeys.managers.CrateDataManager; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.event.Listener; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +@Getter +public class CrankedCrateKeysPlugin extends JavaPlugin { + public static CrankedCrateKeysPlugin AstroCrateKeysPlugin; + public static FileConfiguration config; + private CommandManager commandManager; + + + + public void onEnable() { + AstroCrateKeysPlugin = this; + registerListeners(); + CrateDataManager.init(); + config = getConfig(); + this.commandManager = new CommandManager(this, true); + this.registerCommandParameters(); + this.commandManager.register(new CommandAdminCrate()); + + + } + + public void onDisable() { + CrateDataManager.onDisable(); + AstroCrateKeysPlugin = null; + } + + + private void registerListeners() { + registerListener(new CrateLogicListener()); + registerListener(new CrateKeyInventoryListener()); + } + + public static void registerListener(Listener listener) { + Bukkit.getPluginManager().registerEvents(listener, (Plugin) AstroCrateKeysPlugin); + } + + + public static CrankedCrateKeysPlugin getInstance() { + return AstroCrateKeysPlugin; + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(CrateKeyType.class, argument -> { + CrateKeyType crateType = CrateKeyType.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(crateType, argument); + }); + } + + +} diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/commands/CommandAdminCrate.java b/Keys/src/main/java/net/crankedpvp/cratekeys/commands/CommandAdminCrate.java new file mode 100644 index 0000000..ccad00d --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/commands/CommandAdminCrate.java @@ -0,0 +1,110 @@ +package net.crankedpvp.cratekeys.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.cratekeys.items.CratePlacementItem; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Command("admincrate") +@Alias({"acrate","acrates", "admincrates"}) +public class CommandAdminCrate extends CommandBase { + + @Default + @Permission("cratekeys.admin") + public void defaultCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + player.sendMessage(""); + player.sendMessage(CC.RedB + "Admin Crate Commands"); + //player.sendMessage(CC.Red + "/acrate additem "); + //player.sendMessage(CC.Red + "/acrate removeitem "); + player.sendMessage(CC.Red + "/acrate givekey [IGN]"); + player.sendMessage(CC.Red + "/acrate givecrate "); + + player.sendMessage(""); + } + + /* + @Permission("cratekeys.admin") + @SubCommand("additem") + public void addItem(CommandSender sender, @Completion("#range:0-100") Double chance, @Completion("#enum") CrateType type) { + Player player = ((Player)sender); + ItemStack item = player.getItemInHand().clone(); + if (item == null || item.getType() == Material.AIR) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You can't add air to a crate!"); + return; + } + LootTableAPI.g + Map items = CrankedCrateKeysAPI.getItems(type); + items.put(item, chance); + CrankedCrateKeysAPI.setItems(type, items); + CrankedCrateKeysPlugin.getInstance().getCrateLootManager().getCachedCrateLoot().put(type, CrankedCrateKeysAPI.getItems(type)); + player.sendMessage(CC.translate("&a&l(!)&a Added " + item.getItemMeta().getDisplayName() + " &ato " + type.getPrefixedName() + " &awith a &7" + chance + " &a% chance.")); + } + + @Permission("cratekeys.admin") + @SubCommand("removeitem") + public void removeItem(CommandSender sender, @Completion("#enum") CrateType type) { + Player player = ((Player)sender); + ItemStack item = player.getItemInHand().clone(); + if (item == null || item.getType() == Material.AIR) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You can't remove air from a crate!"); + return; + } + Map items = CrankedCrateKeysAPI.getItems(type); + for (Map.Entry entry : items.entrySet()) { + if (entry.getKey().equals(item)) { + item = entry.getKey(); + break; + } + } + if (!items.containsKey(item)) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "Could not find item!"); + return; + } + items.remove(item); + CrankedCrateKeysAPI.setItems(type, items); + CrankedCrateKeysPlugin.getInstance().getCrateLootManager().getCachedCrateLoot().put(type, CrankedCrateKeysAPI.getItems(type)); + player.sendMessage(CC.translate("&a&l(!)&a Removed " + item.getItemMeta().getDisplayName() + " &afrom " + type.getPrefixedName() + "&a.")); + } + + */ + + @Permission("cratekeys.admin") + @SubCommand("givekey") + public void giveKey(CommandSender sender, @Completion("#enum") CrateKeyType type, Integer amount, @Optional Player forPlayer) { + if (amount == null) { + amount = 1; + } + if (forPlayer == null) { + if (sender instanceof Player) { + Player player = ((Player) sender); + CrankedCrateKeysAPI.givePlayerKeys(player, type, amount); + player.sendMessage(CC.translate("&a&l(!)&a You have received " + amount + " &a " + type.getPrefixedName() + " &acratekeys.")); + } + } else { + CrankedCrateKeysAPI.givePlayerKeys(forPlayer, type, amount); + forPlayer.sendMessage(CC.translate("&a&l(!)&a You have received " + amount + " &a " + type.getPrefixedName() + " &acratekeys.")); + + } + + } + + @Permission("cratekeys.admin") + @SubCommand("givecrate") + public void giveCrate(Player sender, @Completion("#enum") CrateKeyType type) { + sender.sendMessage(CC.translate("&a&l(!)&a You have received a " +type.getName() + " Crate.")); + ItemStack item = CratePlacementItem.getItem(type); + PlayerUtils.giveOrDropProtectedItem(sender, item, 60); + + } + + + + +} diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/data/CrateData.java b/Keys/src/main/java/net/crankedpvp/cratekeys/data/CrateData.java new file mode 100644 index 0000000..0d2eddb --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/data/CrateData.java @@ -0,0 +1,23 @@ +package net.crankedpvp.cratekeys.data; + + +import lombok.Getter; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import org.bukkit.Location; + +public class CrateData { + + private final CrateKeyType crate; + @Getter + private final Location location; + + public CrateData(CrateKeyType crate, Location location) { + this.crate = crate; + this.location = location; + } + + public CrateKeyType getCrateType() { + return this.crate; + } + +} diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/enums/CrateKeyType.java b/Keys/src/main/java/net/crankedpvp/cratekeys/enums/CrateKeyType.java new file mode 100644 index 0000000..2e390b6 --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/enums/CrateKeyType.java @@ -0,0 +1,47 @@ +package net.crankedpvp.cratekeys.enums; + + +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; + +public enum CrateKeyType { + + ABYSS_KEY("Abyss", "&c", ""), + MYTHIC_KEY("Mythic", "&e", ""), + SEASON_KEY("Winter", "&b", "&3"); + + @Getter + private final String name; + @Getter + private final String prefix; + private final String prefix2; + + CrateKeyType(String name, String prefix, String prefix2) { + this.name = name; + this.prefix = CC.translate(prefix); + this.prefix2 = CC.translate(prefix2); + + } + + public String getPrefixedName() { + if (this == SEASON_KEY) { + StringBuilder prefix = new StringBuilder(); + boolean color = true; + String currentColor; + for (String letter : this.getName().split("")) { + if (color) { + currentColor = this.prefix; + color = false; + } else { + currentColor = this.prefix2; + color = true; + } + currentColor += "&l"; + prefix.append(currentColor).append(letter); + } + return CC.translate(prefix + "&r&l" + " &f&lCrate Key"); + } else { + return CC.translate(getPrefix() + CC.Bold + getName() + " &f&lCrate Key"); + } + } +} diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/inventory/LootPreviewGUI.java b/Keys/src/main/java/net/crankedpvp/cratekeys/inventory/LootPreviewGUI.java new file mode 100644 index 0000000..0661f65 --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/inventory/LootPreviewGUI.java @@ -0,0 +1,97 @@ +package net.crankedpvp.cratekeys.inventory; + +import com.google.common.collect.Lists; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.List; + +public class LootPreviewGUI { + @Getter + private final PaginatedGui cratePreviewInventory; + + public LootPreviewGUI(CrateKeyType type) { + + this.cratePreviewInventory = new PaginatedGui(6, 28, type.getName() + " Crate Loot Preview"); + cratePreviewInventory.setDefaultClickAction(event -> event.setCancelled(true)); + cratePreviewInventory.getFiller().fillBorder(new GuiItem(GuiUtil.createFillerItem())); + + cratePreviewInventory.setItem(6, 1, new GuiItem(GuiUtil.createPreviousItem(), event -> { + cratePreviewInventory.previous(); + event.setCancelled(true); + })); + cratePreviewInventory.setItem(6, 9, new GuiItem(GuiUtil.createNextItem(), event -> { + cratePreviewInventory.next(); + event.setCancelled(true); + })); + + cratePreviewInventory.setItem(1, 5, new GuiItem(createGUIItem())); + + for(ItemStack itemStack : LootTableAPI.getAllLootFromLootTable(LootTableType.valueOf(type.name()))) { + this.cratePreviewInventory.addItem(new GuiItem(itemStack, event -> { + event.getWhoClicked().sendMessage(CC.Gray + "All items in this crate have a same chance to be pulled."); + if(event.getWhoClicked().isOp()) event.getWhoClicked().getInventory().addItem(itemStack); + })); + } + + /* + for (Map.Entry entry : itemList.entrySet()) { + ItemStack item = entry.getKey().clone(); + double chance = entry.getValue(); + + ItemBuilder itemBuilder = new ItemBuilder(item); + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine(CC.translate("&c&l* &7Chance: &f" + chance + "%")); + itemBuilder.addLoreLine(""); + this.expShopUI.addItem(new GuiItem(itemBuilder.build(), event -> { + ItemStack found = null; + if (player.isOp() && event.isShiftClick() && event.isRightClick()) { + for (ItemStack i : itemList.keySet()) { + if (i.getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())) { + found = i; + } + } + + itemList.remove(found); + CrankedCrateKeysAPI.setItems(type, itemList); + CrankedCrateKeysPlugin.getInstance().getCrateLootManager().getCachedCrateLoot().put(type, CrankedCrateKeysAPI.getItems(type)); + player.sendMessage(CC.translate("&a&l(!)&a Removed " + found.getItemMeta().getDisplayName() + "&f from the " + type.getPrefixedName() + "&a!")); + LootPreviewGUI lootPreviewGUI = new LootPreviewGUI(player, type); + lootPreviewGUI.getLootGUI().open(player); + } + + })); + } + + */ + + + } + + + public ItemStack createGUIItem() { + ItemStack item = new ItemStack(Material.BOOK); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&6&lCrates Info")); + List lore = Lists.newArrayList(); + lore.add(CC.Gray + "Crate Keys can be unlocked from"); + lore.add(CC.Gray + "killings mobs, /shards shop,"); + lore.add(CC.Gray + "fighting bosses, koth, envoy"); + lore.add(CC.Gray + "and many more other ways."); + meta.setLore(lore); + item.setItemMeta(meta); + return item; + } + +} + + diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/items/CrateKeyItem.java b/Keys/src/main/java/net/crankedpvp/cratekeys/items/CrateKeyItem.java new file mode 100644 index 0000000..446aab0 --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/items/CrateKeyItem.java @@ -0,0 +1,45 @@ +package net.crankedpvp.cratekeys.items; + + + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.cratekeys.enums.CrateKeyType; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class CrateKeyItem { + public static ItemStack getItem(CrateKeyType type) { + if (type == null) + return null; + ItemBuilder item = new ItemBuilder(Material.TRIPWIRE_HOOK); + item.setName(type.getPrefixedName()); + item.addLoreLine(CC.translate("&7Right-Click on a " + type.getPrefix() +type.getName() + " &7Crate to open.")); + item.addLoreLine(""); + item.addLoreLine(CC.translate(type.getPrefix() + CC.Bold +"(!) " + type.getPrefix() + "Type &f/warp crates " + type.getPrefix() + " to open this crate key.")); + ItemStack built = item.build(); + NBTItem wrapper = new NBTItem(built); + NBTCompound tag = wrapper.getOrCreateCompound("cosmicData"); + tag.setString("crate_type", type.name()); + if (type.name().contains("MUTATED")) { + tag.setString("tintColor", "-10237440"); + } + return new ItemBuilder(wrapper.getItem()).setGlowing().build(); + } + + public static CrateKeyType getCrateType(ItemStack item) { + if (item == null || item.getType() == Material.AIR) + return null; + NBTItem wrapper = new NBTItem(item); + if (!wrapper.hasKey("cosmicData")) + return null; + NBTCompound tag = wrapper.getOrCreateCompound("cosmicData"); + if (!tag.hasKey("crate_type")) + return null; + return CrateKeyType.valueOf(tag.getString("crate_type")); + } + +} diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/items/CratePlacementItem.java b/Keys/src/main/java/net/crankedpvp/cratekeys/items/CratePlacementItem.java new file mode 100644 index 0000000..15d90d5 --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/items/CratePlacementItem.java @@ -0,0 +1,36 @@ +package net.crankedpvp.cratekeys.items; + + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +public class CratePlacementItem { + public static ItemStack getItem(CrateKeyType type) { + if (type == null) + return null; + ItemBuilder item = new ItemBuilder(Material.CHEST); + item.setName(type.getPrefixedName() + " Crate"); + item.addLoreLine(CC.Gray + "Right-Click to place crate."); + ItemStack built = item.build(); + NBTItem wrapper = new NBTItem(built); + NBTCompound tag = wrapper.getOrCreateCompound("cosmicData"); + tag.setString("crate_place_type", type.name()); + return wrapper.getItem(); + } + + public static CrateKeyType getCrateType(ItemStack item) { + if (item == null || item.getType() == Material.AIR) + return null; + NBTItem wrapper = new NBTItem(item); + if (!wrapper.hasKey("cosmicData")) + return null; + NBTCompound tag = wrapper.getOrCreateCompound("cosmicData"); + if (!tag.hasKey("crate_place_type")) + return null; + return CrateKeyType.valueOf(tag.getString("crate_place_type")); + } +} diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/listeners/CrateKeyInventoryListener.java b/Keys/src/main/java/net/crankedpvp/cratekeys/listeners/CrateKeyInventoryListener.java new file mode 100644 index 0000000..5cf7d9b --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/listeners/CrateKeyInventoryListener.java @@ -0,0 +1,77 @@ +package net.crankedpvp.cratekeys.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.cratekeys.data.CrateData; +import net.crankedpvp.cratekeys.items.CrateKeyItem; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.Chest; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class CrateKeyInventoryListener implements Listener { + + @EventHandler + public void onClick(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + return; + Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + if ((block.getState() instanceof Chest)) { + Chest chest = (Chest) block.getState(); + CrateData data = CrankedCrateKeysAPI.findCrate(chest.getLocation()); + if (data == null) { + return; + } + event.setCancelled(true); + if (!CrankedCrateKeysAPI.isCrateKey(player.getItemInHand())) { + player.sendMessage(CC.translate("&c&l(!)&c Please hold a " + data.getCrateType().getPrefix() + CC.Bold + + data.getCrateType().getName() + "&f&l Crate Key&c to open this crate.")); + return; + } + if (CrateKeyItem.getCrateType(player.getItemInHand()) != data.getCrateType()) { + player.sendMessage(CC.translate("&c&l(!)&c This is not the correct crate type. You need to click the " + CrateKeyItem.getCrateType(player.getItemInHand()).getPrefix() + + CC.Bold + CrateKeyItem.getCrateType(player.getItemInHand()).getName() + CC.Bold + "&f&l Crate&c to open this key.")); + return; + } + if (!InventoryUtils.hasAvailableSlot(player)) { + player.sendMessage(CC.translate("&c&l(!)&c Your inventory is full. Clear some space before opening more keys!")); + return; + } + + if (player.isSneaking()) { + int amountOfKeys = player.getItemInHand().getAmount(); + while (amountOfKeys != 0) { + CrankedCrateKeysAPI.giveCrateKeyLoot(player, LootTableType.valueOf(data.getCrateType().name())); + amountOfKeys--; + } + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).addCrateKeysOpened(amountOfKeys); + player.setItemInHand(null); + } else { + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).addCrateKeysOpened(1); + CrankedCrateKeysAPI.giveCrateKeyLoot(player, LootTableType.valueOf(data.getCrateType().name())); + if (player.getItemInHand().getAmount() > 1) { + player.getItemInHand().setAmount(player.getItemInHand().getAmount() - 1); + } else { + player.setItemInHand(null); + } + } + + player.playSound(player.getLocation(), Sound.LEVEL_UP, 1f, 1f); + } + + } + + + + +} + + diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/listeners/CrateLogicListener.java b/Keys/src/main/java/net/crankedpvp/cratekeys/listeners/CrateLogicListener.java new file mode 100644 index 0000000..331dffe --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/listeners/CrateLogicListener.java @@ -0,0 +1,76 @@ +package net.crankedpvp.cratekeys.listeners; + +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.cratekeys.data.CrateData; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.cratekeys.inventory.LootPreviewGUI; +import net.crankedpvp.cratekeys.items.CratePlacementItem; +import net.crankedpvp.cratekeys.managers.CrateDataManager; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Chest; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class CrateLogicListener implements Listener { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + ItemStack item = event.getPlayer().getItemInHand(); + CrateKeyType type = CratePlacementItem.getCrateType(item); + if (type == null) + return; + final Block block = event.getBlock(); + CrateDataManager.newInstance(type, block.getLocation()); + } + + @EventHandler(priority = EventPriority.LOW) + public void placeKey(PlayerInteractEvent event) { + if(event.getItem() == null || event.getItem().getType() == Material.AIR) return; + if(event.getItem().getType() != Material.TRIPWIRE_HOOK) return; + if(CrankedCrateKeysAPI.isCrateKey(event.getItem())) { + event.setCancelled(true); + return; + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBreak(BlockBreakEvent event) { + Block block = event.getBlock(); + if (!(block.getState() instanceof Chest)) + return; + Chest chest = (Chest) block.getState(); + CrateData data = CrankedCrateKeysAPI.findCrate(chest.getLocation()); + if (data == null) + return; + CrateDataManager.removeInstance(data); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + if (event.getAction() != Action.LEFT_CLICK_BLOCK) + return; + Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + if (!(block.getState() instanceof Chest)) + return; + Chest chest = (Chest) block.getState(); + CrateData data = CrankedCrateKeysAPI.findCrate(chest.getLocation()); + if (data == null) + return; + + if (player.isSneaking() && player.isOp()) return; + + event.setCancelled(true); + + LootPreviewGUI lootPreviewGUI = new LootPreviewGUI(data.getCrateType()); + lootPreviewGUI.getCratePreviewInventory().open(player); + } + +} diff --git a/Keys/src/main/java/net/crankedpvp/cratekeys/managers/CrateDataManager.java b/Keys/src/main/java/net/crankedpvp/cratekeys/managers/CrateDataManager.java new file mode 100644 index 0000000..7769a1b --- /dev/null +++ b/Keys/src/main/java/net/crankedpvp/cratekeys/managers/CrateDataManager.java @@ -0,0 +1,49 @@ +package net.crankedpvp.cratekeys.managers; + +import lombok.Getter; +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.cratekeys.data.CrateData; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import org.bukkit.Location; +import org.bukkit.Material; + +import java.util.List; + +public class CrateDataManager { + + @Getter + private static List crates; + + public static void init() { + crates = CrankedCrateKeysAPI.getCrates(); + } + + public static void onDisable() { + CrankedCrateKeysAPI.deleteCrates(); + crates.forEach(crate -> CrankedCrateKeysAPI.addCrate(crate.getCrateType(), crate.getLocation())); + for (int i = crates.size() - 1; i >= 0; i--) { + CrateData data = crates.get(i); + if (data.getLocation().getBlock().getType() != Material.CHEST) + crates.remove(i); + } + } + + public static void clearCrates() { + crates.clear(); + } + + public static void newInstance(CrateKeyType type, Location location) { + CrateData data = new CrateData(type, location); + crates.add(data); + } + + public static void removeInstance(CrateData crate) { + for (int i = 0; i < crates.size(); i++) { + CrateData data = crates.get(i); + if (data.equals(crate)) { + crates.remove(i); + return; + } + } + } +} diff --git a/Keys/src/main/resources/config.yml b/Keys/src/main/resources/config.yml new file mode 100644 index 0000000..e69de29 diff --git a/Keys/src/main/resources/plugin.yml b/Keys/src/main/resources/plugin.yml new file mode 100644 index 0000000..9ddff69 --- /dev/null +++ b/Keys/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedCrateKeys +main: net.crankedpvp.cratekeys.CrankedCrateKeysPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/KillCounters/pom.xml b/KillCounters/pom.xml new file mode 100644 index 0000000..691947e --- /dev/null +++ b/KillCounters/pom.xml @@ -0,0 +1,26 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + KillCounters + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + + \ No newline at end of file diff --git a/KillCounters/src/main/java/net/crankedpvp/killcounters/KillCounterAPI.java b/KillCounters/src/main/java/net/crankedpvp/killcounters/KillCounterAPI.java new file mode 100644 index 0000000..5dd4b38 --- /dev/null +++ b/KillCounters/src/main/java/net/crankedpvp/killcounters/KillCounterAPI.java @@ -0,0 +1,92 @@ +package net.crankedpvp.killcounters; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.List; + +public class KillCounterAPI { + + public static ItemStack addOrbToItem(ItemStack itemStack) { + ItemMeta meta = itemStack.getItemMeta(); + List lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); + KillCounterPlugin.getInstance().getConfig().getStringList("Applied.Lore").forEach(line -> lore.add(CC.translate(line.replace("%kills%", "0")))); + meta.setLore(lore); + itemStack.setItemMeta(meta); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setBoolean("killCounterApplied", true); + nbtItem.setInteger("killCount", 0); + return nbtItem.getItem(); + } + + public static ItemStack incrementKillsOnCounter(ItemStack itemStack, int amount) { + if(itemStack == null) return null; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getBoolean("killCounterApplied")) return null; + if(!nbtItem.hasKey("killCount")) return null; + ItemMeta meta = itemStack.getItemMeta(); + List lore = meta.getLore(); + KillCounterPlugin.getInstance().getConfig().getStringList("Applied.Lore").forEach(configLine -> { + configLine = configLine.replace("%kills%", String.valueOf(nbtItem.getInteger("killCount"))); + String finalConfigLine = configLine; + lore.removeIf(line -> CC.translate(line).equals(CC.translate(finalConfigLine))); + }); + KillCounterPlugin.getInstance().getConfig().getStringList("Applied.Lore").forEach(configLine -> { + lore.add(CC.translate(configLine.replace("%kills%", String.valueOf(nbtItem.getInteger("killCount") + amount)))); + }); + meta.setLore(lore); + + itemStack.setItemMeta(meta); + + NBTItem nbtItem1 = new NBTItem(itemStack); + nbtItem1.setInteger("killCount", nbtItem1.getInteger("killCount") + amount); + return nbtItem1.getItem(); + } + + public static ItemStack removeKillsOnCounter(ItemStack itemStack, int amount) { + if(itemStack == null) return null; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getBoolean("killCounterApplied")) return null; + if(!nbtItem.hasKey("killCount")) return null; + ItemMeta meta = itemStack.getItemMeta(); + List lore = meta.getLore(); + KillCounterPlugin.getInstance().getConfig().getStringList("Applied.Lore").forEach(configLine -> { + configLine = configLine.replace("%kills%", String.valueOf(nbtItem.getInteger("killCount"))); + String finalConfigLine = configLine; + lore.removeIf(line -> CC.translate(line).equals(CC.translate(finalConfigLine))); + }); + KillCounterPlugin.getInstance().getConfig().getStringList("Applied.Lore").forEach(configLine -> { + lore.add(CC.translate(configLine.replace("%kills%", String.valueOf(nbtItem.getInteger("killCount") - amount)))); + }); + meta.setLore(lore); + + itemStack.setItemMeta(meta); + + NBTItem nbtItem1 = new NBTItem(itemStack); + nbtItem1.setInteger("killCount", nbtItem1.getInteger("killCount") + amount); + return nbtItem1.getItem(); + } + + public static ItemStack deleteKillCounterFromItem(ItemStack itemStack) { + if(itemStack == null) return null; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getBoolean("killCounterApplied")) return null; + if(!nbtItem.hasKey("killCount")) return null; + ItemMeta meta = itemStack.getItemMeta(); + List lore = meta.getLore(); + KillCounterPlugin.getInstance().getConfig().getStringList("Applied.Lore").forEach(configLine -> { + configLine = configLine.replace("%kills%", String.valueOf(nbtItem.getInteger("killCount"))); + String finalConfigLine = configLine; + lore.removeIf(line -> CC.translate(line).equals(CC.translate(finalConfigLine))); + }); + itemStack.setItemMeta(meta); + NBTItem nbtItem1 = new NBTItem(itemStack); + nbtItem1.removeKey("killCount"); + nbtItem1.removeKey("killCounterApplied"); + return nbtItem1.getItem(); + } + +} diff --git a/KillCounters/src/main/java/net/crankedpvp/killcounters/KillCounterPlugin.java b/KillCounters/src/main/java/net/crankedpvp/killcounters/KillCounterPlugin.java new file mode 100644 index 0000000..6347b84 --- /dev/null +++ b/KillCounters/src/main/java/net/crankedpvp/killcounters/KillCounterPlugin.java @@ -0,0 +1,66 @@ +package net.crankedpvp.killcounters; + + +import de.tr7zw.nbtapi.NBTItem; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.killcounters.commands.KillCounterCommand; +import net.crankedpvp.killcounters.file.FileHandler; +import net.crankedpvp.killcounters.listeners.CounterApplyListener; +import net.crankedpvp.killcounters.listeners.DeathEventListener; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class KillCounterPlugin extends JavaPlugin { + + private static KillCounterPlugin instance; + private CommandManager commandManager; + private ItemStack killCounterOrbItemStack; + private FileHandler fileHandler; + + @Override + public void onEnable() { + instance = this; + saveDefaultConfig(); + setupKillCounterOrbItemStack(); + this.fileHandler = new FileHandler(this); + this.fileHandler.load(); + this.commandManager = new CommandManager(this); + this.commandManager.register(new KillCounterCommand(this)); + this.registerListeners(); + } + + private void setupKillCounterOrbItemStack() { + ConfigurationSection configurationSection = this.getConfig().getConfigurationSection("Item"); + ItemStack itemStack = new ItemBuilder(Material.getMaterial(configurationSection.getString("Material"))) + .setName(configurationSection.getString("Name")) + .setLore(configurationSection.getStringList("Lore")) + .colorize() + .build(); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("savageCustomItem", "killCounter"); + this.killCounterOrbItemStack = nbtItem.getItem(); + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new CounterApplyListener(this), this); + pluginManager.registerEvents(new DeathEventListener(), this); + } + + public ItemStack getKillCounterOrbItemStack() { + return this.killCounterOrbItemStack; + } + + public static KillCounterPlugin getInstance() { + return instance; + } + + public FileHandler getFileHandler() { + return fileHandler; + } + +} diff --git a/KillCounters/src/main/java/net/crankedpvp/killcounters/commands/KillCounterCommand.java b/KillCounters/src/main/java/net/crankedpvp/killcounters/commands/KillCounterCommand.java new file mode 100644 index 0000000..c0e0b2d --- /dev/null +++ b/KillCounters/src/main/java/net/crankedpvp/killcounters/commands/KillCounterCommand.java @@ -0,0 +1,94 @@ +package net.crankedpvp.killcounters.commands; + +import de.tr7zw.nbtapi.NBTItem; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.killcounters.KillCounterAPI; +import net.crankedpvp.killcounters.KillCounterPlugin; +import net.crankedpvp.killcounters.file.Language; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +@Command("killcounter") +@Alias({"astrokillcounter", "savagekillcounter"}) +public class KillCounterCommand extends CommandBase { + + private final KillCounterPlugin plugin; + public KillCounterCommand(KillCounterPlugin plugin) { + this.plugin = plugin; + } + + + @Default + @Permission("killcounter.*") + public void defaultCommand(final CommandSender commandSender) { + commandSender.sendMessage(CC.translate("&c/killcounter give ")); + } + + @SubCommand("give") + @Permission("killcounter.*") + @WrongUsage("&cCranked&fPvP &8| &7Usage: /killcounter give ") + public void giveKillCounter(final CommandSender commandSender, @Completion("#players") Player player) { + Player sender = (Player) commandSender; + if(this.plugin.getKillCounterOrbItemStack() == null) return; + player.getInventory().addItem(this.plugin.getKillCounterOrbItemStack()); + player.sendMessage(CC.translate(Language.KILLCOUNTER_RECEIVED.getValue().replace("%giving%", sender.getName()).replace("%receiving%", player.getName()))); + sender.sendMessage(CC.translate(Language.KILLCOUNTER_GIVEN.getValue().replace("%giving%", sender.getName()).replace("%receiving%", player.getName()))); + } + + @SubCommand("addkills") + @Permission("killcounter.*") + @WrongUsage("&cCranked&fPvP &8| &7Usage: /killcounter addkills ") + public void addKills(final CommandSender commandSender, Integer amount) { + Player sender = (Player) commandSender; + ItemStack itemStack = sender.getItemInHand(); + if(itemStack == null) return; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getBoolean("killCounterApplied")) return; + if(!nbtItem.hasKey("killCount")) return; + sender.setItemInHand(KillCounterAPI.incrementKillsOnCounter(sender.getItemInHand(), amount)); + sender.sendMessage(CC.translate(Language.KILLCOUNTER_INCREMENTED.getValue().replace("%amount%", String.valueOf(amount)))); + } + + @SubCommand("removekills") + @Permission("killcounter.*") + @WrongUsage("&cCranked&fPvP &8| &7Usage: /killcounter removekills ") + public void removeKills(final CommandSender commandSender, Integer amount) { + Player sender = (Player) commandSender; + ItemStack itemStack = sender.getItemInHand(); + if(itemStack == null) return; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getBoolean("killCounterApplied")) return; + if(!nbtItem.hasKey("killCount")) return; + sender.setItemInHand(KillCounterAPI.removeKillsOnCounter(sender.getItemInHand(), amount)); + sender.sendMessage(CC.translate(Language.KILLCOUNTER_REMOVED.getValue().replace("%amount%", String.valueOf(amount)))); + } + + @SubCommand("deletecounter") + @Permission("killcounter.*") + @WrongUsage("&cCranked&fPvP &8| &7Usage: /killcounter deletecounter") + public void deleteCounter(final CommandSender commandSender) { + Player sender = (Player) commandSender; + ItemStack itemStack = sender.getItemInHand(); + if(itemStack == null) return; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getBoolean("killCounterApplied")) return; + if(!nbtItem.hasKey("killCount")) return; + sender.setItemInHand(KillCounterAPI.deleteKillCounterFromItem(sender.getItemInHand())); + Language.KILLCOUNTER_DELETED.send(sender); + } + + @SubCommand("reload") + @Permission("killcounter.*") + @WrongUsage("&cCranked&fPvP &8| &7Usage: /killcounter reload") + public void reload(final CommandSender commandSender) { + Player sender = (Player) commandSender; + plugin.saveConfig(); + plugin.getFileHandler().load(); + Language.KILLCOUNTER_RELOADED.send(sender); + } + +} diff --git a/KillCounters/src/main/java/net/crankedpvp/killcounters/file/FileHandler.java b/KillCounters/src/main/java/net/crankedpvp/killcounters/file/FileHandler.java new file mode 100644 index 0000000..4da5369 --- /dev/null +++ b/KillCounters/src/main/java/net/crankedpvp/killcounters/file/FileHandler.java @@ -0,0 +1,47 @@ +package net.crankedpvp.killcounters.file; + +import net.crankedpvp.killcounters.KillCounterPlugin; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; + +public final class FileHandler { + + private final KillCounterPlugin pluginDelegate; + + public FileHandler(KillCounterPlugin pluginDelegate) { + this.pluginDelegate = pluginDelegate; + } + + public void load() { + loadLanguage(); + } + + + private void loadLanguage() { + File file = new File(pluginDelegate.getDataFolder(), "language.yml"); + YamlConfiguration config = new YamlConfiguration(); + + if (!file.exists()) { + file.getParentFile().mkdir(); + pluginDelegate.saveResource(file.getName(),false); + } + + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + throw new RuntimeException(e); + } finally { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + } +} \ No newline at end of file diff --git a/KillCounters/src/main/java/net/crankedpvp/killcounters/file/Language.java b/KillCounters/src/main/java/net/crankedpvp/killcounters/file/Language.java new file mode 100644 index 0000000..6703123 --- /dev/null +++ b/KillCounters/src/main/java/net/crankedpvp/killcounters/file/Language.java @@ -0,0 +1,81 @@ +package net.crankedpvp.killcounters.file; + + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + KILLCOUNTER_GIVEN("Messages.Given"), + KILLCOUNTER_RECEIVED("Messages.Received"), + KILLCOUNTER_APPLIED("Messages.Applied"), + KILLCOUNTER_ALREADY_APPLIED("Messages.Already.Applied"), + KILLCOUNTER_INCREMENTED("Messages.Incremented"), + KILLCOUNTER_REMOVED("Messages.Removed"), + KILLCOUNTER_DELETED("Messages.Deleted"), + KILLCOUNTER_RELOADED("Messages.Reloaded") + + ; + + + private final String path; + private String value; + private ImmutableList valueList; + + Language(String path) { + this.path = path; + } + + public String getValue() { + return value != null ? value : path; + } + + public String getValue(UnaryOperator function) { + return value != null ? function.apply(value) : path; + } + + public String getPath() { + return path; + } + + public ImmutableList getValuesAsList() { + return valueList; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(getValue())); + } + + public void send(Player player) { + player.sendMessage(CC.translate(getValue())); + } +} \ No newline at end of file diff --git a/KillCounters/src/main/java/net/crankedpvp/killcounters/listeners/CounterApplyListener.java b/KillCounters/src/main/java/net/crankedpvp/killcounters/listeners/CounterApplyListener.java new file mode 100644 index 0000000..3619d05 --- /dev/null +++ b/KillCounters/src/main/java/net/crankedpvp/killcounters/listeners/CounterApplyListener.java @@ -0,0 +1,54 @@ +package net.crankedpvp.killcounters.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.killcounters.KillCounterAPI; +import net.crankedpvp.killcounters.KillCounterPlugin; +import net.crankedpvp.killcounters.file.Language; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class CounterApplyListener implements Listener { + + private final KillCounterPlugin plugin; + public CounterApplyListener(KillCounterPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void applyKillCounterOrb(InventoryClickEvent event) { + if(event.getCursor() == null || event.getCurrentItem() == null || event.getCursor().getType() == Material.AIR || event.getCurrentItem().getType() == Material.AIR) return; + if(!itemIsWeapon(event.getCurrentItem())) return; + final NBTItem nbtClickedItem = new NBTItem(event.getCurrentItem()); + final NBTItem nbtCursorItem = new NBTItem(event.getCursor()); + if(!nbtCursorItem.hasKey("savageCustomItem")) return; + if(!nbtCursorItem.getString("savageCustomItem").equals("killCounter")) return; + event.setCancelled(true); + if(nbtClickedItem.hasKey("killCounterApplied")) { + Language.KILLCOUNTER_ALREADY_APPLIED.send(event.getWhoClicked()); + ((Player) event.getWhoClicked()).getPlayer().playSound(event.getWhoClicked().getLocation(), Sound.ANVIL_LAND, 3F, 1.2F); + return; + } + event.setCursor(removeHeldItem(event.getCursor(), 1)); + event.setCurrentItem(KillCounterAPI.addOrbToItem(event.getCurrentItem())); + String displayName = event.getCurrentItem().getItemMeta().hasDisplayName() ? event.getCurrentItem().getItemMeta().getDisplayName() : event.getCurrentItem().getType().name(); + event.getWhoClicked().sendMessage(Language.KILLCOUNTER_APPLIED.getValue().replace("%item%", displayName)); + ((Player) event.getWhoClicked()).getPlayer().playSound(event.getWhoClicked().getLocation(), Sound.SUCCESSFUL_HIT, 5F, 1.2F); + } + + private boolean itemIsWeapon(ItemStack itemStack) { + return itemStack.getType().name().endsWith("_SWORD") || itemStack.getType().name().endsWith("_AXE") || itemStack.getType().name().endsWith("_HOE"); + } + + private ItemStack removeHeldItem(ItemStack itemStack, int amount) { + if (itemStack.getAmount() > amount) { + itemStack.setAmount(itemStack.getAmount() - amount); + return itemStack; + } + return new ItemStack(Material.AIR); + } +} diff --git a/KillCounters/src/main/java/net/crankedpvp/killcounters/listeners/DeathEventListener.java b/KillCounters/src/main/java/net/crankedpvp/killcounters/listeners/DeathEventListener.java new file mode 100644 index 0000000..59f89fc --- /dev/null +++ b/KillCounters/src/main/java/net/crankedpvp/killcounters/listeners/DeathEventListener.java @@ -0,0 +1,33 @@ +package net.crankedpvp.killcounters.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.killcounters.KillCounterAPI; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.inventory.ItemStack; + + +public class DeathEventListener implements Listener { + + @EventHandler + public void killCounterIncrement(EntityDeathEvent event) { + if(event.getEntity() == null) return; + if(event.getEntity().getKiller() == null) return; + if(!(event.getEntity() instanceof Player)) return; + + + ItemStack itemStack = event.getEntity().getKiller().getItemInHand(); + + if(itemStack == null || itemStack.getType() == Material.AIR) return; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getBoolean("killCounterApplied")) return; + if(!nbtItem.hasKey("killCount")) return; + + event.getEntity().getKiller().setItemInHand(KillCounterAPI.incrementKillsOnCounter(itemStack, 1)); + event.getEntity().getKiller().playSound(event.getEntity().getKiller().getLocation(), Sound.ORB_PICKUP, 2.0F, 2.0F); + } +} diff --git a/KillCounters/src/main/resources/config.yml b/KillCounters/src/main/resources/config.yml new file mode 100644 index 0000000..0b48dc3 --- /dev/null +++ b/KillCounters/src/main/resources/config.yml @@ -0,0 +1,11 @@ +Item: + Material: SLIME_BALL + Name: "&6&lKill Counter Orb &7(Apply)" + Lore: + - "&7Drag n' Drop this orb onto any &fweapon" + - "&7to start &ftracking &7the amount of kills" + - "&7you get while wielding it!" +Applied: + Lore: + - "&f&l(&c&l*&f&l) &cKill Count: &f%kills%" + # Use %kills% as a place holder for the amount of kills the kill counter has \ No newline at end of file diff --git a/KillCounters/src/main/resources/language.yml b/KillCounters/src/main/resources/language.yml new file mode 100644 index 0000000..42d3b9a --- /dev/null +++ b/KillCounters/src/main/resources/language.yml @@ -0,0 +1,19 @@ +Messages: + Given: "&cCranked&fPvP &8| &7You have given a kill counter orb to %receiving%" + # Use %giving% as a placeholder for the player that is running the command + # Use %receiving% as a placeholder for the player that is receiving the item + Received: "&cCranked&fPvP &8| &7You have received a kill counter orb from %giving%" + # Use %giving% as a placeholder for the player that has given the item (defaulted to Console) + # Use %receiving% as a placeholder for the player that is receiving the item + Applied: "&cCranked&fPvP &8| &7You have applied a kill counter orb to your weapon" + # Use %item% as a placeholder for the name of the item being equipped to + Incremented: "&cCranked&fPvP &8| &7Your items kill counter has been incremented by %amount%" + # Use %amount% as the amount the kill counter has been increased by + Removed: "&cCranked&fPvP &8| &7Your items kill counter has had %amount% kills removed from it" + # Use %amount% as the amount the kill counter has been decreased by + Deleted: "&cCranked&fPvP &8| &7Your items kill counter has been deleted" + + Reloaded: "&cCranked&fPvP &8| &7Kill counters language.yml reloaded." + + Already: + Applied: "&cCranked&fPvP &8| &7This item already has a kill counter applied" \ No newline at end of file diff --git a/KillCounters/src/main/resources/plugin.yml b/KillCounters/src/main/resources/plugin.yml new file mode 100644 index 0000000..77520fc --- /dev/null +++ b/KillCounters/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedKillCounters +main: net.crankedpvp.killcounters.KillCounterPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/Leaderboards/pom.xml b/Leaderboards/pom.xml new file mode 100644 index 0000000..536fb4d --- /dev/null +++ b/Leaderboards/pom.xml @@ -0,0 +1,44 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Leaderboards + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + TempTournament + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + net.astropvp + FactionsKore + 0.1 + system + ${project.basedir}/../.lib/FactionsKore-1.3.431.jar + + + + diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/LeaderboardsAPI.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/LeaderboardsAPI.java new file mode 100644 index 0000000..186596a --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/LeaderboardsAPI.java @@ -0,0 +1,147 @@ +package net.crankedpvp.leaderboards; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.RandomUtils; +import net.crankedpvp.crankedutils.utils.SortUtils; +import net.crankedpvp.leaderboards.struct.Leaderboard; +import net.crankedpvp.leaderboards.struct.PlayerStats; +import net.crankedpvp.tournaments.CrankedTournaments; +import net.crankedpvp.tournaments.objects.TournamentPlayer; +import org.bukkit.Bukkit; + +import java.text.DecimalFormat; +import java.util.*; + +public class LeaderboardsAPI { + + public static Map> leaderboardListMap = new HashMap<>(); + + private static final DecimalFormat format = new DecimalFormat("#,###"); + private static final DecimalFormat decimalFormat = new DecimalFormat("#,###.#"); + + public static PlayerStats getPlayerStats(UUID uuid) { + return LeaderboardsPlugin.getInstance().getPlayerStatsManager().getPlayerStats(uuid); + } + + public static void updateLeaderboard(Leaderboard leaderboard) { + List list = new ArrayList<>(); + Map map = SortUtils.sort(getUpdatedLeaderboardRankings(leaderboard)); + int index = 1; + list.add("&8&m------------------"); + for(Map.Entry playerDoubleEntry : map.entrySet()) { + String value = playerDoubleEntry.getValue() % 1 == 0 ? format.format(playerDoubleEntry.getValue().intValue()) : decimalFormat.format(playerDoubleEntry.getValue()); + list.add("&7" + index + ". " + leaderboard.getPrimaryColor() + Bukkit.getOfflinePlayer(playerDoubleEntry.getKey()).getName() + + " &7[" + leaderboard.getSecondaryColor() + value + "&7]"); + if(index++==10) break; + } + list.add("&8&m------------------"); + leaderboardListMap.put(leaderboard, list); + } + + public static List getTopThreeAsStrings(Leaderboard leaderboard) { + List list = new ArrayList<>(); + Map map = SortUtils.sort(getUpdatedLeaderboardRankings(leaderboard)); + int index = 1; + list.add(CC.translate(leaderboard.getSecondaryColor() + "Top 3 '" + leaderboard.getName() + "' Leaderboard")); + //list.add("&8&m------------------"); + for(Map.Entry playerDoubleEntry : map.entrySet()) { + String value = playerDoubleEntry.getValue() % 1 == 0 ? format.format(playerDoubleEntry.getValue().intValue()) : decimalFormat.format(playerDoubleEntry.getValue()); + list.add(" &7" + index + ". " + leaderboard.getPrimaryColor() + Bukkit.getOfflinePlayer(playerDoubleEntry.getKey()).getName() + + " &7[" + leaderboard.getSecondaryColor() + value + "&7]"); + if(index++==3) break; + } + //list.add("&8&m------------------"); + return list; + } + + public static void updateLeaderboard(String leaderboard) { + updateLeaderboard(LeaderboardsPlugin.getInstance().getLeaderboardRegister().getLeaderboardFromID(leaderboard)); + } + + public static Leaderboard selectRandomLeaderboard() { + return RandomUtils.getRandomCollectionElement(LeaderboardsPlugin.getInstance().getLeaderboardRegister().getLeaderboards()); + } + + private static Map getUpdatedLeaderboardRankings(Leaderboard leaderboard) { + Map map = new HashMap<>(); + String leaderboardId = leaderboard.getID().toLowerCase(Locale.ROOT); + + for(PlayerStats playerStats : LeaderboardsPlugin.getInstance().getPlayerStatsManager().getCacheValues()) { + switch(leaderboardId) { + case "kills": + map.put(playerStats.getUuid(), (double) playerStats.getKills()); + break; + case "deaths": + map.put(playerStats.getUuid(), (double) playerStats.getDeaths()); + break; + case "kdr": + map.put(playerStats.getUuid(), playerStats.getKDR()); + break; + case "petuses": + map.put(playerStats.getUuid(), (double) playerStats.getPetsUsed()); + break; + case "staritemsapplied": + map.put(playerStats.getUuid(), (double) playerStats.getStarItemsApplied()); + break; + case "bosskills": + map.put(playerStats.getUuid(), (double) playerStats.getBossKills()); + break; + case "mobkills": + map.put(playerStats.getUuid(), (double) playerStats.getMobKills()); + break; + case "expgained": + map.put(playerStats.getUuid(), (double) playerStats.getExpGained()); + break; + case "envoysopened": + map.put(playerStats.getUuid(), (double) playerStats.getEnvoysOpened()); + break; + case "averagexppermob": + map.put(playerStats.getUuid(), playerStats.getAverageXPPerMobKilled()); + break; + case "coresbroken": + map.put(playerStats.getUuid(), (double) playerStats.getCoresBroken()); + break; + case "shardsspent": + map.put(playerStats.getUuid(), playerStats.getShardsSpent()); + break; + case "underworldmobskilled": + map.put(playerStats.getUuid(), (double) playerStats.getUnderworldMobsKilled()); + break; + case "underworldessencegained": + map.put(playerStats.getUuid(), (double) playerStats.getUnderworldEssenceGained()); + break; + case "underworldskipsused": + map.put(playerStats.getUuid(), (double) playerStats.getUnderworldSkipsUsed()); + break; + case "tournamentkills": + map.put(playerStats.getUuid(), getTournamentStat(playerStats.getUuid(), false)); + break; + case "tournamentwins": + map.put(playerStats.getUuid(), getTournamentStat(playerStats.getUuid(), true)); + break; + case "cratekeysopened": + map.put(playerStats.getUuid(), (double) playerStats.getCrateKeysOpened()); + break; + } + } + return map; + } + + private static double getTournamentStat(UUID uuid, boolean wins) { + try { + CrankedTournaments tournaments = CrankedTournaments.getInstance(); + if (tournaments == null || tournaments.getTournamentManager() == null) { + return 0; + } + + TournamentPlayer player = tournaments.getTournamentManager().getFromCache(uuid.toString()); + if (player == null) { + return 0; + } + return wins ? player.getTournamenWins() : player.getKills(); + } catch (NoClassDefFoundError | NoSuchMethodError unavailableLegacyApi) { + // The newer CrankedTournaments plugin does not provide the legacy stats API. + return 0; + } + } +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/LeaderboardsPlugin.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/LeaderboardsPlugin.java new file mode 100644 index 0000000..3d1f39d --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/LeaderboardsPlugin.java @@ -0,0 +1,72 @@ +package net.crankedpvp.leaderboards; + +import com.gmail.filoghost.holographicdisplays.api.Hologram; +import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; +import lombok.Getter; +import lombok.Setter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.leaderboards.commands.LeaderboardCommand; +import net.crankedpvp.leaderboards.inventory.LeaderboardsInventory; +import net.crankedpvp.leaderboards.listeners.PlayerDeathListener; +import net.crankedpvp.leaderboards.struct.LeaderboardRegister; +import net.crankedpvp.leaderboards.struct.PlayerStatsManager; +import net.crankedpvp.leaderboards.tasks.HologramUpdateTask; +import net.crankedpvp.leaderboards.tasks.LeaderboardUpdateTask; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class LeaderboardsPlugin extends JavaPlugin { + + @Getter @Setter + private LeaderboardsInventory leaderboardsInventory; + + @Getter + private static LeaderboardsPlugin instance; + + private CommandManager commandManager; + + @Getter + private LeaderboardRegister leaderboardRegister; + + @Getter + private PlayerStatsManager playerStatsManager; + + @Getter + private Hologram hologram; + + @Override + public void onEnable() { + instance = this; + + this.commandManager = new CommandManager(this); + this.commandManager.register(new LeaderboardCommand(this)); + this.leaderboardRegister = new LeaderboardRegister(); + this.leaderboardRegister.initialize(); + + this.playerStatsManager = new PlayerStatsManager(this); + this.playerStatsManager.loadAll(); + + new LeaderboardUpdateTask().runTaskTimer(this, 0L, 300 * 20L); + + this.hologram = HologramsAPI.createHologram(this, this.getLeaderboardRegister().getHologramLocation()); + for (int i = 0; i < 12; i++) { + hologram.appendTextLine(""); + } + + + this.registerListeners(); + new HologramUpdateTask().runTaskTimer(this, 60L, 10 * 20L); + //new BroadcastRandomLeaderboardTask().runTaskTimer(this, 10 * 20L, 10 * 60 * 20L); + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new PlayerDeathListener(this), this); + } + + @Override + public void onDisable() { + this.playerStatsManager.saveAll(); + this.playerStatsManager = null; + } +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/commands/LeaderboardCommand.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/commands/LeaderboardCommand.java new file mode 100644 index 0000000..b1af051 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/commands/LeaderboardCommand.java @@ -0,0 +1,59 @@ +package net.crankedpvp.leaderboards.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.leaderboards.LeaderboardsPlugin; +import net.crankedpvp.leaderboards.inventory.LeaderboardsInventory; +import net.crankedpvp.leaderboards.struct.Leaderboard; +import net.crankedpvp.leaderboards.struct.PlayerStats; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("leaderboard") +@Alias("leaderboards") +public class LeaderboardCommand extends CommandBase { + + private final LeaderboardsPlugin plugin; + public LeaderboardCommand(LeaderboardsPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(Player sender, @Optional Player toFind) { + if(toFind == null) { + LeaderboardsInventory leaderboardsInventory = this.plugin.getLeaderboardsInventory(); + leaderboardsInventory.getUI().open(sender); + return; + } + + PlayerStats playerStats = this.plugin.getPlayerStatsManager().getPlayerStats(toFind.getUniqueId()); + for(String statString : playerStats.getAllStats()) { + sender.sendMessage(statString); + } + } + + @SubCommand("sync") + @Permission("cranked.admin") + public void locationCommand(CommandSender commandSender) { + long millis = System.currentTimeMillis(); + for(Leaderboard leaderboard : LeaderboardsPlugin.getInstance().getLeaderboardRegister().getLeaderboards()) { + LeaderboardsAPI.updateLeaderboard(leaderboard); + } + LeaderboardsPlugin.getInstance().setLeaderboardsInventory(new LeaderboardsInventory()); + commandSender.sendMessage(CC.translate("&aLeaderboards synced in " + (System.currentTimeMillis() - millis) + "ms")); + } + + @SubCommand("print") + @Permission("cranked.admin") + public void print(CommandSender commandSender, String leaderboardName) { + Leaderboard leaderboard = this.plugin.getLeaderboardRegister().getLeaderboardFromID(leaderboardName); + Bukkit.broadcastMessage(""); + Bukkit.broadcastMessage(CC.translate(leaderboard.getSecondaryColor() + leaderboard.getName() + " Leaderboard")); + for(String string : LeaderboardsAPI.leaderboardListMap.get(leaderboard)) { + Bukkit.broadcastMessage(CC.translate(string)); + } + } +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/inventory/LeaderboardsInventory.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/inventory/LeaderboardsInventory.java new file mode 100644 index 0000000..7e12064 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/inventory/LeaderboardsInventory.java @@ -0,0 +1,44 @@ +package net.crankedpvp.leaderboards.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.leaderboards.struct.Leaderboard; +import net.crankedpvp.leaderboards.struct.LeaderboardRegister; + +import java.text.DecimalFormat; +import java.util.*; + +public class LeaderboardsInventory { + + private static final DecimalFormat format = new DecimalFormat("#,###"); + private static final DecimalFormat decimalFormat = new DecimalFormat("#,###.#"); + + private final Gui leaderboardInventory; + + public Gui getUI() { + return this.leaderboardInventory; + } + + Collection allLeaderboards = LeaderboardRegister.getInstance().getLeaderboards(); + + public LeaderboardsInventory() { + this.leaderboardInventory = new Gui(3, "Leaderboards"); + this.leaderboardInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + for(Leaderboard Leaderboard : this.allLeaderboards) { + this.addLeaderboardItemToInventory(Leaderboard); + } + } + + private void addLeaderboardItemToInventory(Leaderboard leaderboard) { + ItemBuilder itemBuilder = new ItemBuilder(leaderboard.getMaterial(), leaderboard.getSecondaryColor() + leaderboard.getName() + " Leaderboard"); + for(String string : LeaderboardsAPI.leaderboardListMap.get(leaderboard)) { + itemBuilder.addLoreLine(string); + } + this.leaderboardInventory.addItem(new GuiItem(itemBuilder.colorize().build())); + } + + +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/listeners/PlayerDeathListener.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/listeners/PlayerDeathListener.java new file mode 100644 index 0000000..03b77d7 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/listeners/PlayerDeathListener.java @@ -0,0 +1,25 @@ +package net.crankedpvp.leaderboards.listeners; + +import net.crankedpvp.leaderboards.LeaderboardsPlugin; +import net.crankedpvp.leaderboards.struct.PlayerStats; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; + +public class PlayerDeathListener implements Listener { + + private LeaderboardsPlugin plugin; + public PlayerDeathListener(LeaderboardsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void playerDeathEvent(PlayerDeathEvent event) { + if(event.getEntity() == null) return; + PlayerStats victimStats = this.plugin.getPlayerStatsManager().getPlayerStats(event.getEntity().getUniqueId()); + victimStats.incrementDeaths(); + if(event.getEntity().getKiller() == null) return; + PlayerStats killerStats = this.plugin.getPlayerStatsManager().getPlayerStats(event.getEntity().getKiller().getUniqueId()); + killerStats.incrementKills(); + } +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/Leaderboard.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/Leaderboard.java new file mode 100644 index 0000000..aca03d2 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/Leaderboard.java @@ -0,0 +1,26 @@ +package net.crankedpvp.leaderboards.struct; + +import lombok.Getter; +import org.bukkit.Material; + +import java.util.Locale; + +@Getter +public class Leaderboard { + + private final String name; + private final String primaryColor; + private final String secondaryColor; + private final Material material; + + public Leaderboard(String name, String primaryColor, String secondaryColor, Material material) { + this.name = name; + this.primaryColor = primaryColor; + this.secondaryColor = secondaryColor; + this.material = material; + } + + public String getID() { return this.getName().toLowerCase(Locale.ROOT).replace(" ", ""); } + + +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/LeaderboardRegister.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/LeaderboardRegister.java new file mode 100644 index 0000000..1842217 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/LeaderboardRegister.java @@ -0,0 +1,106 @@ +package net.crankedpvp.leaderboards.struct; + +import lombok.Getter; +import lombok.Setter; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; + +import java.util.*; + +public class LeaderboardRegister { + + @Getter + private static LeaderboardRegister instance; + private final Map leaderboards; + @Setter + @Getter + private Location hologramLocation; + + + public LeaderboardRegister() { + instance = this; + this.leaderboards = new HashMap<>(); + this.hologramLocation = new Location(Bukkit.getWorld("world"), -18.5, 193.8, -6.5); + } + + public void initialize() { + this.registerAll( + new Leaderboard("Kills", "&2", "&a", Material.DIAMOND_SWORD), + new Leaderboard("KDR", "&3", "&b", Material.IRON_SWORD), + new Leaderboard("Deaths", "&4", "&c", Material.REDSTONE), + new Leaderboard("Envoys Opened", "&6", "&e", Material.CHEST), + new Leaderboard("Boss Kills", "&4", "&c", Material.DRAGON_EGG), + new Leaderboard("Mob Kills", "&1", "&3", Material.BLAZE_POWDER), + new Leaderboard("EXP Gained", "&6", "&e", Material.EXP_BOTTLE), + new Leaderboard("Pet Uses", "&3", "&b", Material.EGG), + new Leaderboard("Star Items Applied", "&5", "&d", Material.NETHER_STAR), + new Leaderboard("Average XP Per Mob", "&e", "&6", Material.BLAZE_ROD), + new Leaderboard("Cores Broken", "&e", "&6", Material.BEACON), + new Leaderboard("Shards Spent", "&3", "&b", Material.PRISMARINE_SHARD), + new Leaderboard("Tournament Kills", "&e", "&6", Material.STONE_SWORD), + new Leaderboard("Tournament Wins", "&4", "&c", Material.DIAMOND), + new Leaderboard("Underworld Mobs Killed", "&c", "&4", Material.EYE_OF_ENDER), + new Leaderboard("Underworld Skips Used", "&b", "&3", Material.PRISMARINE_CRYSTALS), + new Leaderboard("Crate Keys Opened", "&a", "&2", Material.TRIPWIRE_HOOK), + //new Leaderboard("Walking Distance Travelled", "&e", "&6", Material.LEATHER_BOOTS), + //new Leaderboard("Flying Distance Travelled", "&f", "&b", Material.IRON_BOOTS), + new Leaderboard("Underworld Essence Gained", "&3", "&b", Material.FEATHER) + ); + } + + public void registerAll(Leaderboard... leaderboards) { + for (Leaderboard leaderboard : leaderboards) { + this.register(leaderboard); + } + } + + public void register(Leaderboard Leaderboard) { + try { + this.leaderboards.put(Leaderboard.getID(), Leaderboard); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register Leaderboard " + Leaderboard.getID()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.leaderboards.clear(); + } + + public void unregister(Leaderboard Leaderboard) { + this.leaderboards.remove(Leaderboard.getID()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isLeaderboard(String name) { + return (this.getLeaderboardFromID(name) != null); + } + + public Leaderboard getLeaderboardFromID(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + return this.leaderboards.get(name.toLowerCase()); + } + + public Leaderboard getLeaderboardFromName(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + name = this.getLeaderboardIDFromName(name); + return this.leaderboards.get(name.toLowerCase()); + } + + public String getLeaderboardIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getLeaderboards() { + return Collections.unmodifiableCollection(this.leaderboards.values()); + } + +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/PlayerStats.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/PlayerStats.java new file mode 100644 index 0000000..f224169 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/PlayerStats.java @@ -0,0 +1,151 @@ +package net.crankedpvp.leaderboards.struct; + +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.storageutils.struct.NewKeyToSave; +import org.bukkit.Bukkit; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Getter +public class PlayerStats implements NewKeyToSave { + + private UUID uuid; + private int kills; + private int deaths; + private int petsUsed; + private int starItemsApplied; + private int envoysOpened; + private int bossKills; + private long mobKills; + private long expGained; + private int coresBroken; + private double shardsSpent; + private int underworldMobsKilled; + private int underworldEssenceGained; + private int underworldSkipsUsed; + private int crateKeysOpened; + + public PlayerStats(UUID uuid) { + this.uuid = uuid; + this.kills = 0; + this.deaths = 0; + this.petsUsed = 0; + this.starItemsApplied = 0; + this.envoysOpened = 0; + this.bossKills = 0; + this.mobKills = 0; + this.expGained = 0; + this.coresBroken = 0; + this.shardsSpent = 0; + this.underworldMobsKilled = 0; + this.underworldEssenceGained = 0; + this.underworldSkipsUsed = 0; + this.crateKeysOpened = 0; + } + + public List getAllStats() { + List allStats = new ArrayList<>(); + allStats.add("&6Player Stats: " + Bukkit.getOfflinePlayer(this.uuid).getName()); + allStats.add("&2Kills: &7[&a" + this.kills + "&7]"); + allStats.add("&4Deaths: &7[&c" + this.deaths + "&7]"); + allStats.add("&3KDR: &7[&b" + this.getKDR() + "&7]"); + allStats.add("&3Pets Used: &7[&b" + this.petsUsed + "&7]"); + allStats.add("&5Star Items Applied: &7[&d" + this.starItemsApplied + "&7]"); + allStats.add("&6Envoys Opened: &7[&e" + this.envoysOpened + "&7]"); + allStats.add("&4Boss Kills: &7[&c" + this.bossKills + "&7]"); + allStats.add("&1Mob Kills: &3[&a" + this.mobKills + "&7]"); + allStats.add("&6EXP Gained: &7[&e" + this.expGained + "&7]"); + allStats.add("&eAverage EXP Per Mob: &7[&6" + this.getAverageXPPerMobKilled() + "&7]"); + allStats.add("&eCores Broken: &7[&6" + this.coresBroken + "&7]"); + allStats.add("&6Shards Spent: &7[&e" + this.shardsSpent + "&7]"); + allStats.add("&cUnderworld Mobs Killed: &7[&4" + this.underworldMobsKilled + "&7]"); + allStats.add("&3Underworld Essence Gained: &7[&b" + this.underworldEssenceGained + "&7]"); + allStats.add("&bUnderworld Skips Used: &7[&3" + this.underworldSkipsUsed + "&7]"); + allStats.add("&aCrate Keys Opened: &7[&2" + this.crateKeysOpened + "&7]"); + allStats.add(""); + return allStats.stream().map(CC::translate).collect(Collectors.toList()); + } + + public double getKDR() { + if(this.deaths <= 1) return this.kills; + if(this.kills == 0) return 0.0D; + return (double) this.kills / this.deaths; + } + + public double getAverageXPPerMobKilled() { + if(this.mobKills == 0 || this.expGained == 1) return 0.0D; + return (double) this.expGained / this.mobKills; + } + + public void incrementKills() { + this.kills++; + } + + public void incrementDeaths() { + this.deaths++; + } + + public void incrementPetsUsed() { + this.petsUsed++; + } + + public void incrementStarItemsApplied() { + this.starItemsApplied++; + } + + public void incrementEnvoysOpened() { + this.envoysOpened++; + } + + public void incrementBossKills() { + this.bossKills++; + } + + public void incrementCoresBroken() { + this.coresBroken++; + } + + public void incrementUnderworldSkipsUsed() { + this.underworldSkipsUsed++; + } + + public void incrementUnderworldMobsKilled() { + this.underworldMobsKilled++; + } + + public void addMobsKilled(int mobsKilled) { + this.mobKills = this.mobKills + mobsKilled; + } + + public void addShardsSpent(double shardsSpent) { + this.shardsSpent = this.shardsSpent + shardsSpent; + } + + public void addEXPGained(int expGained) { + this.expGained = this.expGained + expGained; + } + + public void addUnderworldEssenceGained(int essenceGained) { + this.underworldEssenceGained = this.underworldEssenceGained + essenceGained; + } + + public void addCrateKeysOpened(int crateKeysOpened) { + this.crateKeysOpened = this.crateKeysOpened + crateKeysOpened; + } + + + @Override + public UUID getKey() { + return uuid; + } + + @Override + public void setKey(UUID uuid) { + this.uuid = uuid; + } + +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/PlayerStatsManager.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/PlayerStatsManager.java new file mode 100644 index 0000000..2233d32 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/struct/PlayerStatsManager.java @@ -0,0 +1,32 @@ +package net.crankedpvp.leaderboards.struct; + +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.struct.NewSaveLoadManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.UUID; + +public class PlayerStatsManager extends NewSaveLoadManager { + + public PlayerStatsManager(JavaPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "data/", PlayerStats.class); + } + + @Override + public String serialize(UUID uuid) { + return uuid.toString(); + } + + @Override + public UUID deserialize(String s) { + return UUID.fromString(s); + } + + public PlayerStats getPlayerStats(UUID uuid) { + if (!containsKey(uuid)) { + PlayerStats playerStats = new PlayerStats(uuid); + addToCache(playerStats); + } + return getFromCache(uuid); + } +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/BroadcastRandomLeaderboardTask.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/BroadcastRandomLeaderboardTask.java new file mode 100644 index 0000000..300b2ce --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/BroadcastRandomLeaderboardTask.java @@ -0,0 +1,17 @@ +package net.crankedpvp.leaderboards.tasks; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import org.bukkit.Bukkit; +import org.bukkit.scheduler.BukkitRunnable; + +public class BroadcastRandomLeaderboardTask extends BukkitRunnable { + + @Override + public void run() { + for(String topThreeAsString : LeaderboardsAPI.getTopThreeAsStrings(LeaderboardsAPI.selectRandomLeaderboard())) { + Bukkit.broadcastMessage(CC.translate(topThreeAsString)); + } + } + +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/HologramUpdateTask.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/HologramUpdateTask.java new file mode 100644 index 0000000..28719a6 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/HologramUpdateTask.java @@ -0,0 +1,44 @@ +package net.crankedpvp.leaderboards.tasks; + +import com.gmail.filoghost.holographicdisplays.api.Hologram; +import com.gmail.filoghost.holographicdisplays.api.line.TextLine; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.leaderboards.LeaderboardsPlugin; +import net.crankedpvp.leaderboards.struct.Leaderboard; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Collections; +import java.util.List; + +public class HologramUpdateTask extends BukkitRunnable { + + private final LeaderboardsPlugin plugin = LeaderboardsPlugin.getInstance(); + + @Override + public void run() { + Hologram hologram = plugin.getHologram(); + if (hologram == null || hologram.isDeleted() || plugin.getLeaderboardRegister().getLeaderboards().isEmpty()) { + return; + } + + Leaderboard leaderboard = LeaderboardsAPI.selectRandomLeaderboard(); + List stringList = LeaderboardsAPI.leaderboardListMap.get(leaderboard); + if (stringList == null) { + stringList = Collections.singletonList("&7Leaderboard data is loading..."); + } + + int lineCount = stringList.size() + 1; + while (hologram.size() < lineCount) { + hologram.appendTextLine(""); + } + while (hologram.size() > lineCount) { + hologram.removeLine(hologram.size() - 1); + } + + ((TextLine) hologram.getLine(0)).setText(CC.translate(leaderboard.getSecondaryColor() + "&l" + leaderboard.getName() + " Leaderboard")); + for (int i = 0; i < stringList.size(); i++) { + ((TextLine) hologram.getLine(i + 1)).setText(CC.translate(stringList.get(i))); + } + } +} diff --git a/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/LeaderboardUpdateTask.java b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/LeaderboardUpdateTask.java new file mode 100644 index 0000000..8494332 --- /dev/null +++ b/Leaderboards/src/main/java/net/crankedpvp/leaderboards/tasks/LeaderboardUpdateTask.java @@ -0,0 +1,27 @@ +package net.crankedpvp.leaderboards.tasks; + +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.leaderboards.LeaderboardsPlugin; +import net.crankedpvp.leaderboards.inventory.LeaderboardsInventory; +import net.crankedpvp.leaderboards.struct.Leaderboard; +import org.bukkit.Bukkit; +import org.bukkit.scheduler.BukkitRunnable; + +public class LeaderboardUpdateTask extends BukkitRunnable { + + @Override + public void run() { + for(Leaderboard leaderboard : LeaderboardsPlugin.getInstance().getLeaderboardRegister().getLeaderboards()) { + LeaderboardsAPI.updateLeaderboard(leaderboard); + } + + this.updateInventory(); + } + + private void updateInventory() { + Bukkit.getLogger().info("[Leaderboard] Started updating leaderboard inventory"); + LeaderboardsPlugin.getInstance().setLeaderboardsInventory(new LeaderboardsInventory()); + Bukkit.getLogger().info("[Leaderboard] Finished updating leaderboard inventory"); + } + +} diff --git a/Leaderboards/src/main/resources/plugin.yml b/Leaderboards/src/main/resources/plugin.yml new file mode 100644 index 0000000..bdb2d09 --- /dev/null +++ b/Leaderboards/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedLeaderboards +main: net.crankedpvp.leaderboards.LeaderboardsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedTournaments \ No newline at end of file diff --git a/LootFilter/pom.xml b/LootFilter/pom.xml new file mode 100644 index 0000000..cdc29fb --- /dev/null +++ b/LootFilter/pom.xml @@ -0,0 +1,50 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + LootFilter + + + 8 + 8 + + + + + + Core + net.crankedpvp + + + + net.crankedpvp + Utils + + + net.crankedpvp + LootTable + + + com.massivecraft + Factions + + + net.crankedpvp + Lootboxes + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + \ No newline at end of file diff --git a/LootFilter/src/main/java/net/crankedpvp/lootfilter/LootFilterAPI.java b/LootFilter/src/main/java/net/crankedpvp/lootfilter/LootFilterAPI.java new file mode 100644 index 0000000..08aa034 --- /dev/null +++ b/LootFilter/src/main/java/net/crankedpvp/lootfilter/LootFilterAPI.java @@ -0,0 +1,40 @@ +package net.crankedpvp.lootfilter; + +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.lootboxes.struct.LootboxManager; +import net.crankedpvp.lootfilter.data.LootFilterData; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class LootFilterAPI { + public static void giveLootTableItem(Player player, LootTableType lootTable, ItemStack item) { + LootFilterData lootFilterData = LootFilterPlugin.getInstance().getLootFilterManager().getLootFilterData(player.getUniqueId()); + if (lootFilterData.isFiltered(lootTable, item)) { + if (CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(player.getUniqueId()).isLootTableMessageEnabled()) { + player.sendMessage(CC.translate("&c&l(!)&c " + item.getItemMeta().getDisplayName() + " &chas been filtered out, type &7\"/lootfilter\"&c to edit your &l" + lootTable.getFancy() + " Filter&c.")); + } + return; + } + if (CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(player.getUniqueId()).isLootTableMessageEnabled()) { + player.sendMessage(CC.translate("&a&l(!)&a You have received " + item.getItemMeta().getDisplayName() + " &afrom the &l" + lootTable.getFancy() + "&a. Type &7\"/lootfilter\"&a to edit your &l" + lootTable.getFancy() + " Filter&a.")); + } + + if(LootboxManager.doesLootboxBroadcast(item)) { + Bukkit.broadcastMessage(CC.translate(LuckpermUtils.getDisplayName(player) + "&f has received a " + ItemUtils.getDisplayName(item) + " &ffrom the " + lootTable.getColor() + lootTable.getFancy() + "&f loottable!")); + } + + PlayerUtils.giveOrDropProtectedItem(player, item, 60); + } + + public static boolean isFiltered(Player player, LootTableType lootTable, ItemStack item) { + LootFilterData lootFilterData = LootFilterPlugin.getInstance().getLootFilterManager().getLootFilterData(player.getUniqueId()); + return lootFilterData.isFiltered(lootTable, item); + } + +} diff --git a/LootFilter/src/main/java/net/crankedpvp/lootfilter/LootFilterPlugin.java b/LootFilter/src/main/java/net/crankedpvp/lootfilter/LootFilterPlugin.java new file mode 100644 index 0000000..1205c0a --- /dev/null +++ b/LootFilter/src/main/java/net/crankedpvp/lootfilter/LootFilterPlugin.java @@ -0,0 +1,36 @@ +package net.crankedpvp.lootfilter; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.lootfilter.commands.LootFilterCommand; +import net.crankedpvp.lootfilter.data.LootFilterManager; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +@Getter +public class LootFilterPlugin extends JavaPlugin { + @Getter + private static LootFilterPlugin instance; + public LootFilterManager lootFilterManager; + private CommandManager commandManager; + + + @Override + public void onEnable() { + instance = this; + this.lootFilterManager = new LootFilterManager(); + lootFilterManager.loadAll(); + this.commandManager = new CommandManager(this); + this.commandManager.register(new LootFilterCommand()); + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, () -> { + lootFilterManager.saveAll(); + },60L, 10*20*60); + } + + @Override + public void onDisable() { + lootFilterManager.saveAll(); + instance = null; + + } +} diff --git a/LootFilter/src/main/java/net/crankedpvp/lootfilter/commands/LootFilterCommand.java b/LootFilter/src/main/java/net/crankedpvp/lootfilter/commands/LootFilterCommand.java new file mode 100644 index 0000000..30cdefd --- /dev/null +++ b/LootFilter/src/main/java/net/crankedpvp/lootfilter/commands/LootFilterCommand.java @@ -0,0 +1,44 @@ +package net.crankedpvp.lootfilter.commands; + + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedcore.CrankedCore; +import net.crankedpvp.crankedcore.data.CrankedUser; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.lootfilter.guis.LootFilterMainGUI; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +@Command("lootfilter") +@Alias({"lootft","lootfilters", "ftloot"}) +public class LootFilterCommand extends CommandBase { + @Default + public void defaultCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + LootFilterMainGUI lootFilterMainGUI = new LootFilterMainGUI(player.getUniqueId()); + lootFilterMainGUI.getLootFilterMainGUI().open(player.getPlayer()); + } + + @Permission("loottable.admin") + @SubCommand("update") + public void updateCommand(Player player) { + //LootTable.SPACE.setLoot(AstroSpaceGrindingAPI.getListItems(MonsterType.SPACE_ALIEN)); + player.sendMessage(CC.translate("&a&l(!)&a Force updated all loottable filters!")); + + } + + @SubCommand("togglemessage") + public void toggleMessage(Player player) { + CrankedUser astroPlayer = CrankedCore.getInstance().getCrankedUserManager().getCrankedUser(player.getUniqueId()); + if (astroPlayer.isLootTableMessageEnabled()) { + astroPlayer.setLootTableMessageEnabled(false); + player.sendMessage(CC.translate("&a&lCore &8➥ &7You &c&lDISABLED&7 Lootfilter Messages")); + } else { + astroPlayer.setLootTableMessageEnabled(true); + player.sendMessage(CC.translate("&a&lCore &8➥ &7You &a&lENABLED&7 Lootfilter Messages")); + } + + } +} diff --git a/LootFilter/src/main/java/net/crankedpvp/lootfilter/data/LootFilterData.java b/LootFilter/src/main/java/net/crankedpvp/lootfilter/data/LootFilterData.java new file mode 100644 index 0000000..2e1be8c --- /dev/null +++ b/LootFilter/src/main/java/net/crankedpvp/lootfilter/data/LootFilterData.java @@ -0,0 +1,65 @@ +package net.crankedpvp.lootfilter.data; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.storageutils.utils.KeyToSave; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +@Getter +@Setter +@AllArgsConstructor +public class LootFilterData implements KeyToSave { + + private UUID uuid; + private Map> filteredItems; + + public void filterItem(LootTableType lootTable, ItemStack item) { + if (!filteredItems.containsKey(lootTable)) { + List itemList = new ArrayList<>(); + getPlayer().sendMessage(CC.translate("&a&l(!)&a Added " + item.getItemMeta().getDisplayName() + " &ato " + lootTable.getColor() + "&l" + lootTable.getColor() + " &aFilter.")); + itemList.add(item); + filteredItems.put(lootTable, itemList); + } else if (filteredItems.get(lootTable).contains(item)) { + getPlayer().sendMessage(CC.translate("&c&l(!)&c Removed " + item.getItemMeta().getDisplayName() + " &cfrom " + lootTable.getColor() + "&l" + lootTable.getColor() + " &cFilter.")); + filteredItems.get(lootTable).remove(item); + } else { + getPlayer().sendMessage(CC.translate("&a&l(!)&a Added " + item.getItemMeta().getDisplayName() + " &ato " + lootTable.getColor() + "&l" + lootTable.getColor() + " &aFilter.")); + filteredItems.get(lootTable).add(item); + } + } + + public boolean isFiltered(LootTableType lootTable, ItemStack item) { + if (!filteredItems.containsKey(lootTable)) { + return false; + } + return filteredItems.get(lootTable).contains(item); + } + + public int getFilteredItemsAmount(LootTableType lootTable) { + if (!filteredItems.containsKey(lootTable)) { + return 0; + } + return filteredItems.get(lootTable).size(); + } + + public Player getPlayer () { + return Bukkit.getPlayer(uuid); + } + + @Override + public String getKey() { + return uuid.toString(); + } + + @Override + public void setKey(String s) { + this.uuid = UUID.fromString(s); + } +} diff --git a/LootFilter/src/main/java/net/crankedpvp/lootfilter/data/LootFilterManager.java b/LootFilter/src/main/java/net/crankedpvp/lootfilter/data/LootFilterManager.java new file mode 100644 index 0000000..e584f52 --- /dev/null +++ b/LootFilter/src/main/java/net/crankedpvp/lootfilter/data/LootFilterManager.java @@ -0,0 +1,21 @@ +package net.crankedpvp.lootfilter.data; + +import net.crankedpvp.lootfilter.LootFilterPlugin; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; + +import java.util.HashMap; +import java.util.UUID; + +public class LootFilterManager extends SaveLoadManager { + public LootFilterManager() { + super(LootFilterPlugin.getInstance(), StorageUtils.getInstance().getGson(), "data/", LootFilterData.class); + } + + public LootFilterData getLootFilterData(UUID uuid) { + if (getFromCache(uuid.toString()) == null) { + addToCache(new LootFilterData(uuid, new HashMap<>())); + } + return getFromCache(uuid.toString()); + } +} diff --git a/LootFilter/src/main/java/net/crankedpvp/lootfilter/guis/LootFilterMainGUI.java b/LootFilter/src/main/java/net/crankedpvp/lootfilter/guis/LootFilterMainGUI.java new file mode 100644 index 0000000..eea5bf3 --- /dev/null +++ b/LootFilter/src/main/java/net/crankedpvp/lootfilter/guis/LootFilterMainGUI.java @@ -0,0 +1,36 @@ +package net.crankedpvp.lootfilter.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.lootfilter.LootFilterPlugin; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Bukkit; + +import java.util.UUID; + +@Getter +public class LootFilterMainGUI { + private final PaginatedGui lootFilterMainGUI; + + public LootFilterMainGUI(UUID uuid) { + this.lootFilterMainGUI = new PaginatedGui(3, 27, "Loot Filter Menu"); + this.lootFilterMainGUI.setDefaultClickAction(event -> event.setCancelled(true)); + for (LootTableType lootTable : LootTableType.values()) { + lootFilterMainGUI.addItem(new GuiItem(new ItemBuilder(lootTable.getMaterial(), lootTable.getColor() + "&l" + lootTable.getFancy() + " Filter") + .addLoreLine("&7Click to edit this loot filter.") + .addLoreLine("") + .addLoreLine(lootTable.getColor() + "Filtered Items: &f" + LootFilterPlugin.getInstance().getLootFilterManager().getLootFilterData(uuid).getFilteredItemsAmount(lootTable)) + .colorize() + .build(), event -> { + LootFilterSubGUI lootFilterSubGUI = new LootFilterSubGUI(uuid, lootTable); + lootFilterSubGUI.getLootFilterSubGUI().open(Bukkit.getPlayer(uuid)); + })); + + } + } + +} + + diff --git a/LootFilter/src/main/java/net/crankedpvp/lootfilter/guis/LootFilterSubGUI.java b/LootFilter/src/main/java/net/crankedpvp/lootfilter/guis/LootFilterSubGUI.java new file mode 100644 index 0000000..47ef5b7 --- /dev/null +++ b/LootFilter/src/main/java/net/crankedpvp/lootfilter/guis/LootFilterSubGUI.java @@ -0,0 +1,66 @@ +package net.crankedpvp.lootfilter.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.lootfilter.LootFilterPlugin; +import net.crankedpvp.lootfilter.data.LootFilterData; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.UUID; + +@Getter +public class LootFilterSubGUI { + private final PaginatedGui lootFilterSubGUI; + + public LootFilterSubGUI(UUID uuid, LootTableType lootTable) { + this.lootFilterSubGUI = new PaginatedGui(6, 54, lootTable.getFancy() + " Filter"); + this.lootFilterSubGUI.setDefaultClickAction(event -> event.setCancelled(true)); + + LootFilterData data = LootFilterPlugin.getInstance().getLootFilterManager().getLootFilterData(uuid); + for (ItemStack item : LootTableAPI.getAllLootFromLootTable(lootTable)) { + if (data.isFiltered(lootTable, item)) { + lootFilterSubGUI.addItem(new GuiItem(createFilteredItem(item), event -> { + data.filterItem(lootTable, item); + LootFilterSubGUI lootFilterSubGUI = new LootFilterSubGUI(uuid, lootTable); + lootFilterSubGUI.getLootFilterSubGUI().open(Bukkit.getPlayer(uuid)); + })); + } else { + lootFilterSubGUI.addItem(new GuiItem(item, event -> { + data.filterItem(lootTable, item); + LootFilterSubGUI lootFilterSubGUI = new LootFilterSubGUI(uuid, lootTable); + lootFilterSubGUI.getLootFilterSubGUI().open(Bukkit.getPlayer(uuid)); + })); + } + + } + + this.lootFilterSubGUI.setItem(6, 9, new GuiItem(createBackItem(), event -> { + new LootFilterMainGUI(uuid).getLootFilterMainGUI().open(Bukkit.getPlayer(uuid)); + })); + } + + public ItemStack createFilteredItem(ItemStack filterItem) { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.WHITE.getData()); + ItemMeta meta = filterItem.getItemMeta().clone(); + ItemMeta newMeta = item.getItemMeta(); + newMeta.setDisplayName(meta.getDisplayName()); + newMeta.setLore(meta.getLore()); + item.setItemMeta(newMeta); + ItemBuilder itemBuilder = new ItemBuilder(item); + itemBuilder.setGlowing(); + return itemBuilder.build(); + } + + private ItemStack createBackItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&cGo back"), CC.translate("&7Click to go back to the main menu")).build(); + } +} diff --git a/LootFilter/src/main/resources/plugin.yml b/LootFilter/src/main/resources/plugin.yml new file mode 100644 index 0000000..89d1fef --- /dev/null +++ b/LootFilter/src/main/resources/plugin.yml @@ -0,0 +1,10 @@ +name: CrankedLootFilter +main: net.crankedpvp.lootfilter.LootFilterPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - StorageUtil + - CrankedLootTables + - CrankedLootboxes \ No newline at end of file diff --git a/LootTable/pom.xml b/LootTable/pom.xml new file mode 100644 index 0000000..a898e69 --- /dev/null +++ b/LootTable/pom.xml @@ -0,0 +1,31 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + LootTable + + + 8 + 8 + + + + Utils + net.crankedpvp + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + \ No newline at end of file diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/LootTableAPI.java b/LootTable/src/main/java/net/crankedpvp/loottable/LootTableAPI.java new file mode 100644 index 0000000..7e24057 --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/LootTableAPI.java @@ -0,0 +1,39 @@ +package net.crankedpvp.loottable; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.RandomUtils; +import net.crankedpvp.loottable.data.LootTable; +import net.crankedpvp.loottable.data.LootTableManager; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class LootTableAPI { + + private static LootTableManager lootTableManager = LootTablePlugin.getInstance().getLootTableManager(); + + public static ItemStack getRandomLootItem(LootTableType lootTableType) { + LootTable lootTable = lootTableManager.getLootTable(lootTableType); + if (lootTable.getLootMap().isEmpty()) { + Bukkit.getConsoleSender().sendMessage(CC.translate("&c[LootTableAPI] LootTable " + lootTableType.getFancy() + " is empty, cannot get item, returned grass instead.")); + return new ItemStack(Material.GRASS); + } + return RandomUtils.getRandomItem(lootTable.getLootMap()); + } + + public static List getAllLootFromLootTable(LootTableType type) { + LootTable lootTable = lootTableManager.getLootTable(type); + Set loot = lootTable.getLootMap().keySet(); + return loot.stream().sorted(Comparator.comparing(ItemStack::getType)).collect(Collectors.toList()); + + } + + + +} diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/LootTablePlugin.java b/LootTable/src/main/java/net/crankedpvp/loottable/LootTablePlugin.java new file mode 100644 index 0000000..325120d --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/LootTablePlugin.java @@ -0,0 +1,62 @@ +package net.crankedpvp.loottable; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.loottable.commands.LootTableCommand; +import net.crankedpvp.loottable.data.LootTableManager; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.loottable.typeadapters.LootMapSerializer; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.gson.Gson; +import net.crankedpvp.storageutils.gson.reflect.TypeToken; +import org.bukkit.Bukkit; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; + +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +@Getter +public class LootTablePlugin extends JavaPlugin { + @Getter + private static LootTablePlugin instance; + private LootTableManager lootTableManager; + private CommandManager commandManager; + private final Type mapType = new TypeToken>(){}.getType(); + private Gson gson; + @Override + public void onEnable() { + instance = this; + this.gson = StorageUtils.getInstance().getGson().newBuilder().registerTypeAdapter(mapType, new LootMapSerializer()).create(); + this.lootTableManager = new LootTableManager(this); + lootTableManager.loadAll(); + this.commandManager = new CommandManager(this, true); + registerCommandParameters(); + registerCommandCompletion(); + commandManager.register(new LootTableCommand()); + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, ()-> { + lootTableManager.saveAll(); + + }, 60L, 10*20*60); + } + + @Override + public void onDisable() { + lootTableManager.saveAll(); + instance = null; + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(LootTableType.class, argument -> { + LootTableType type = LootTableType.valueOf(String.valueOf(argument)); + return new TypeResult(type, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#loottables", input -> Arrays.stream(LootTableType.values()).map(LootTableType::name).collect(Collectors.toList())); + } +} diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/commands/LootTableCommand.java b/LootTable/src/main/java/net/crankedpvp/loottable/commands/LootTableCommand.java new file mode 100644 index 0000000..6645124 --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/commands/LootTableCommand.java @@ -0,0 +1,52 @@ +package net.crankedpvp.loottable.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.LootTablePlugin; +import net.crankedpvp.loottable.guis.LootTableMainGUI; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("loottable") +@Alias({"loottables", "loot"}) +public class LootTableCommand extends CommandBase { + @Permission("cranked.admin") + @Default + public void onDefault(CommandSender sender) { + LootTableMainGUI lootTableMainGUI = new LootTableMainGUI((Player) sender); + lootTableMainGUI.getMainGUI().open((Player)sender); + } + + + @Permission("cranked.admin") + @SubCommand("save") + public void onSave(CommandSender sender) { + LootTablePlugin.getInstance().getLootTableManager().saveAll(); + sender.sendMessage(CC.Green + "Saved!!!"); + } + + @Permission("cranked.admin") + @SubCommand("random") + public void onRandomItem(CommandSender sender, @Completion("#players") Player receiver, @Completion("#loottables") LootTableType lootTableType) { + PlayerUtils.giveOrDropProtectedItem(receiver, LootTableAPI.getRandomLootItem(lootTableType), 60); + sender.sendMessage(CC.translate("&aGiven " + receiver.getName() + " a random " + lootTableType.getFancy() + " item.")); + receiver.sendMessage(CC.translate("&aReceived a random " + lootTableType.getFancy() + " item.")); + } + + @Permission("cranked.admin") + @SubCommand("additem") + @WrongUsage("&c/loottable additem ") + public void addItem(Player player, @Completion("#loottables") LootTableType lootTableType, Double chance) { + if (ItemUtils.isAirOrNull(player.getItemInHand())) { + player.sendMessage(CC.translate("&c&l(!)&c Please hold an item!")); + return; + } + player.sendMessage(CC.translate("&a&l(!)&a Added " + ItemUtils.getDisplayName(player.getItemInHand()) + " &ato the " + lootTableType.getFancy() + " &aLoottable!")); + LootTablePlugin.getInstance().getLootTableManager().getLootTable(lootTableType).addItem(chance, player.getItemInHand().clone()); + } +} diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/data/LootTable.java b/LootTable/src/main/java/net/crankedpvp/loottable/data/LootTable.java new file mode 100644 index 0000000..69551c0 --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/data/LootTable.java @@ -0,0 +1,42 @@ +package net.crankedpvp.loottable.data; + + +import lombok.Getter; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.storageutils.utils.KeyToSave; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Getter +public class LootTable implements KeyToSave { + private Map lootMap; + private String lootTableType; + + public LootTable(LootTableType lootTableType) { + this.lootTableType = lootTableType.name(); + this.lootMap = new HashMap<>(); + } + + public void addItem(double chance, ItemStack item) { + lootMap.put(item, chance); + } + + public void removeItem(ItemStack item) { + lootMap.remove(item); + } + + + @Override + public String getKey() { + return lootTableType; + } + + @Override + public void setKey(String key) { + this.lootTableType = key; + } +} diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/data/LootTableManager.java b/LootTable/src/main/java/net/crankedpvp/loottable/data/LootTableManager.java new file mode 100644 index 0000000..fcf652c --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/data/LootTableManager.java @@ -0,0 +1,21 @@ +package net.crankedpvp.loottable.data; + +import net.crankedpvp.loottable.LootTablePlugin; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; + +public class LootTableManager extends SaveLoadManager { + public LootTableManager(LootTablePlugin plugin) { + super(plugin, LootTablePlugin.getInstance().getGson(), "/data", LootTable.class); + } + + public LootTable getLootTable(LootTableType lootTableType) { + if (!containsKey(lootTableType.name())) { + LootTable lootTable = new LootTable(lootTableType); + addToCache(lootTable); + } + return getFromCache(lootTableType.name()); + + } +} diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/guis/LootTableEditGUI.java b/LootTable/src/main/java/net/crankedpvp/loottable/guis/LootTableEditGUI.java new file mode 100644 index 0000000..4f6315f --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/guis/LootTableEditGUI.java @@ -0,0 +1,53 @@ +package net.crankedpvp.loottable.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.loottable.LootTablePlugin; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.loottable.struct.LootTableType; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Map; + +@Getter +public class LootTableEditGUI { + private PaginatedGui lootEditGUI; + + public LootTableEditGUI(LootTableType lootTableType) { + this.lootEditGUI = new PaginatedGui(6, 54, lootTableType.getFancy() + " Loot"); + this.lootEditGUI.setItem(6, 1, new GuiItem(createPreviousItem(), event -> { + LootTableMainGUI lootTableMainGUI = new LootTableMainGUI((Player) event.getWhoClicked()); + lootTableMainGUI.getMainGUI().open(event.getWhoClicked()); + })); + + lootEditGUI.setDefaultClickAction(event -> { + event.setCancelled(true); + }); + for (Map.Entry entry : LootTablePlugin.getInstance().getLootTableManager().getLootTable(lootTableType).getLootMap().entrySet()) { + ItemStack item = entry.getKey(); + double chance = entry.getValue(); + if (ItemUtils.isAirOrNull(item)) continue; + lootEditGUI.addItem(new GuiItem(new ItemBuilder(item.clone()).addLoreLine("").addLoreLine(CC.translate(lootTableType.getColor() + "Chance: &f" + chance + "%")).addLoreLine("").addLoreLine(CC.translate("&cRight-Click &7items in gui to remove")).build(), event -> { + if (event.isRightClick()) { + event.getWhoClicked().sendMessage(CC.translate("&c&l(!)&c Removed " + ItemUtils.getDisplayName(item) + "&c from the " + lootTableType.getFancy() + " - " + lootTableType.getFancy())); + lootEditGUI.removeItem(event.getSlot()); + LootTablePlugin.getInstance().getLootTableManager().getLootTable(lootTableType).removeItem(item); + LootTableEditGUI editGUI = new LootTableEditGUI(lootTableType); + editGUI.getLootEditGUI().open(event.getWhoClicked()); + } else { + event.getWhoClicked().getInventory().addItem(item); + } + })); + } + } + + public ItemStack createPreviousItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&c<- Go Back"), CC.translate("&7Right-Click&7 to go back.")).build(); + } +} diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/guis/LootTableMainGUI.java b/LootTable/src/main/java/net/crankedpvp/loottable/guis/LootTableMainGUI.java new file mode 100644 index 0000000..aaddcb4 --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/guis/LootTableMainGUI.java @@ -0,0 +1,27 @@ +package net.crankedpvp.loottable.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.loottable.LootTablePlugin; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.entity.Player; + +@Getter + +public class LootTableMainGUI { + private PaginatedGui mainGUI; + + public LootTableMainGUI(Player player) { + this.mainGUI = new PaginatedGui(3, 27, "Loottable Menu"); + mainGUI.setDefaultClickAction(event -> event.setCancelled(true)); + for (LootTableType tableType : LootTableType.values()) { + mainGUI.addItem(new GuiItem(new ItemBuilder(tableType.getMaterial(), CC.translate(tableType.getColor() + "&l" + tableType.getFancy()), CC.translate("&7Click to open this loottable.")).build(), event -> { + LootTableEditGUI lootTableEditGUI = new LootTableEditGUI(tableType); + lootTableEditGUI.getLootEditGUI().open(event.getWhoClicked()); + })); + } + } +} diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/struct/LootTableType.java b/LootTable/src/main/java/net/crankedpvp/loottable/struct/LootTableType.java new file mode 100644 index 0000000..c1d6387 --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/struct/LootTableType.java @@ -0,0 +1,41 @@ +package net.crankedpvp.loottable.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.Material; + +@AllArgsConstructor +@Getter +public enum LootTableType { + KOTH(Material.STICK, ChatColor.LIGHT_PURPLE), + ABYSS_KEY(Material.TRIPWIRE_HOOK, ChatColor.RED), + MYTHIC_KEY(Material.TRIPWIRE_HOOK, ChatColor.YELLOW), + SEASON_KEY(Material.TRIPWIRE_HOOK, ChatColor.BLUE), + UNDERWORLD_TIER_1(Material.CHEST, ChatColor.GRAY), + UNDERWORLD_TIER_2(Material.TRAPPED_CHEST, ChatColor.GREEN), + UNDERWORLD_TIER_3(Material.ENDER_CHEST, ChatColor.AQUA), + UNDERWORLD_TIER_4(Material.ENCHANTMENT_TABLE, ChatColor.YELLOW), + UNDERWORLD_TIER_5(Material.ENDER_PORTAL_FRAME, ChatColor.RED), + UNDERWORLD_TIER_6(Material.BEACON, ChatColor.DARK_RED), + SLOTBOT(Material.PAPER, ChatColor.AQUA), + ENVOY(Material.CHEST, ChatColor.YELLOW), + //EVENT(Material.WATCH, ChatColor.GOLD), + //VOYAGE_TIER_1(Material.ENDER_PORTAL_FRAME, ChatColor.GRAY), + //VOYAGE_TIER_2(Material.ENDER_PORTAL_FRAME, ChatColor.GREEN), + //VOYAGE_TIER_3(Material.ENDER_PORTAL_FRAME, ChatColor.AQUA), + //VOYAGE_TIER_4(Material.ENDER_PORTAL_FRAME, ChatColor.YELLOW), + //VOYAGE_TIER_5(Material.ENDER_PORTAL_FRAME, ChatColor.RED), + //VOYAGE_TIER_6(Material.ENDER_PORTAL_FRAME, ChatColor.DARK_RED), + WARZONE_CHEST(Material.CHEST, ChatColor.AQUA), + ; + + public String getFancy() { + return StringUtils.getProperCase(this.name().replace("_", " ")); + } + private final Material material; + private final ChatColor color; + + +} diff --git a/LootTable/src/main/java/net/crankedpvp/loottable/typeadapters/LootMapSerializer.java b/LootTable/src/main/java/net/crankedpvp/loottable/typeadapters/LootMapSerializer.java new file mode 100644 index 0000000..df12808 --- /dev/null +++ b/LootTable/src/main/java/net/crankedpvp/loottable/typeadapters/LootMapSerializer.java @@ -0,0 +1,26 @@ +package net.crankedpvp.loottable.typeadapters; + + +import net.crankedpvp.storageutils.gson.*; +import net.crankedpvp.storageutils.utils.ItemStackSerializer; +import org.bukkit.inventory.ItemStack; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.Map; + +public class LootMapSerializer implements JsonSerializer> { + + @Override + public JsonElement serialize(Map itemStackDoubleMap, Type type, JsonSerializationContext jsonSerializationContext) { + JsonObject jsonObject = new JsonObject(); + itemStackDoubleMap.forEach((itemStack, aDouble) -> { + try { + jsonObject.add(ItemStackSerializer.serialize(itemStack), new JsonPrimitive(aDouble)); + } catch (IOException e) { + e.printStackTrace(); + } + }); + return jsonObject; + } +} diff --git a/LootTable/src/main/resources/plugin.yml b/LootTable/src/main/resources/plugin.yml new file mode 100644 index 0000000..c72766d --- /dev/null +++ b/LootTable/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedLootTables +main: net.crankedpvp.loottable.LootTablePlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - StorageUtil \ No newline at end of file diff --git a/Lootboxes/pom.xml b/Lootboxes/pom.xml new file mode 100644 index 0000000..f6b01ad --- /dev/null +++ b/Lootboxes/pom.xml @@ -0,0 +1,26 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Lootboxes + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + + \ No newline at end of file diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/CrankedLootboxes.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/CrankedLootboxes.java new file mode 100644 index 0000000..7eccf3d --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/CrankedLootboxes.java @@ -0,0 +1,71 @@ +package net.crankedpvp.lootboxes; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.lootboxes.commands.LootboxCommand; +import net.crankedpvp.lootboxes.language.FileHandler; +import net.crankedpvp.lootboxes.listeners.CombineListener; +import net.crankedpvp.lootboxes.listeners.OpenLootboxListener; +import net.crankedpvp.lootboxes.listeners.OpenSidePickerListener; +import net.crankedpvp.lootboxes.listeners.PreviewLootboxListener; +import net.crankedpvp.lootboxes.struct.LootboxManager; +import net.crankedpvp.lootboxes.struct.LootboxRegister; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class CrankedLootboxes extends JavaPlugin { + + @Getter + private static CrankedLootboxes instance; + + @Getter + private LootboxRegister lootboxRegister; + + @Getter + private LootboxManager lootboxManager; + + + @Getter + private CommandManager commandManager; + + @Getter + private FileHandler fileHandler; + + @Override + public void onEnable() { + + instance = this; + + + this.fileHandler = new FileHandler(this); + this.fileHandler.load(); + + this.lootboxRegister = new LootboxRegister(this); + this.lootboxManager = new LootboxManager(this); + + + this.lootboxRegister.clearLootboxMap(); + this.lootboxManager.createDefaultConfig("-example", 6); + this.lootboxManager.initializeAll(); + + this.registerListeners(); + + this.commandManager = new CommandManager(this); + this.registerCommandCompletion(); + this.commandManager.register(new LootboxCommand(this)); + + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new OpenLootboxListener(this), this); + pluginManager.registerEvents(new PreviewLootboxListener(this), this); + pluginManager.registerEvents(new CombineListener(this), this); + pluginManager.registerEvents(new OpenSidePickerListener(this), this); + } + + public void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#lootboxes", input -> this.lootboxRegister.getLootboxesAsIDs()); + } + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/commands/LootboxCommand.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/commands/LootboxCommand.java new file mode 100644 index 0000000..edc5429 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/commands/LootboxCommand.java @@ -0,0 +1,353 @@ +package net.crankedpvp.lootboxes.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.inventory.AdminLootboxInventory; +import net.crankedpvp.lootboxes.inventory.CurrentLootboxInventory; +import net.crankedpvp.lootboxes.language.Language; +import net.crankedpvp.lootboxes.struct.Lootbox; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +@Command("lootbox") +@Alias({"lootboxes", "lb", "crankedlootbox", "mc"}) +public class LootboxCommand extends CommandBase { + + private final CrankedLootboxes plugin; + public LootboxCommand(CrankedLootboxes plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + + if(player.hasPermission("cranked.admin")) { + sendAdminHelpMessage(player); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + return; + } + + CurrentLootboxInventory currentLootboxInventory = new CurrentLootboxInventory(player, plugin); + currentLootboxInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("help") + @Alias("support") + @WrongUsage("&eUsage: /lootbox help") + @Permission("cranked.admin") + public void helpCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + sendAdminHelpMessage(player); + } + + @SubCommand("create") + @Alias({"make", "new"}) + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox create [amount of rewards]") + public void createCommand(CommandSender commandSender, String lootbox, @Optional Integer amountOfRewards) { + Player player = (Player) commandSender; + if(amountOfRewards == null) amountOfRewards = 1; + if(plugin.getLootboxRegister().isLootbox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.ALREADY_LOOTBOX.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(player.getItemInHand() == null) { + plugin.getLootboxManager().createLootbox(lootbox, amountOfRewards); + } else { + plugin.getLootboxManager().createLootboxFromItemStack(player.getItemInHand(), lootbox, amountOfRewards); + } + player.sendMessage(Language.PREFIX.getMessage() + Language.CREATED_LOOTBOX.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + plugin.registerCommandCompletion(); + } + + @SubCommand("delete") + @Alias({"del"}) + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox delete ") + public void deleteCommand(CommandSender commandSender, @Completion("#lootboxes") String lootbox) { + Player player = (Player) commandSender; + if(!plugin.getLootboxRegister().isLootbox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + player.sendMessage(Language.PREFIX.getMessage() + Language.DELETED_LOOTBOX.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.LAVA_POP, 2.0F, 2.0F); + plugin.getLootboxManager().deleteConfig(lootbox); + plugin.getLootboxRegister().removeLootbox(lootbox); + } + + @SubCommand("disable") + @Alias("unload") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox disable ") + public void disableCommand(CommandSender commandSender, @Completion("#lootboxes") String lootbox) { + Player player = (Player) commandSender; + + if (!this.plugin.getLootboxRegister().isLootbox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + File file = new File(this.plugin.getDataFolder() + "/Lootboxes/" + lootbox + ".yml"); + if (file.renameTo(new File(this.plugin.getDataFolder() + "/Lootboxes/-" + lootbox + ".yml"))) { + this.plugin.getLootboxRegister().removeLootbox(lootbox); + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_DISABLED.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 2.0F); + } + } + + @SubCommand("enable") + @Alias("load") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox enable ") + public void enableCommand(CommandSender commandSender, @Completion("#lootboxes") String lootbox) { + Player player = (Player) commandSender; + + if (this.plugin.getLootboxRegister().isLootbox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.ALREADY_LOOTBOX.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + File file = new File(this.plugin.getDataFolder() + "/Lootboxes/-" + lootbox + ".yml"); + if (file.renameTo(new File(this.plugin.getDataFolder() + "/Lootboxes/" + lootbox + ".yml"))) { + this.plugin.getLootboxManager().initialize(lootbox); + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_ENABLED.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + } + + @SubCommand("reload") + @Alias("restart") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox reload [lootbox]") + public void reloadCommand(CommandSender commandSender, @Optional @Completion("#lootboxes") String lootbox) { + Player player = (Player) commandSender; + + if(lootbox == null) { + player.sendMessage(Language.PREFIX.getMessage() + Language.RELOADED_ALL.getMessage()); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + this.plugin.getLootboxRegister().clearLootboxMap(); + this.plugin.getLootboxManager().initializeAll(); + this.plugin.getFileHandler().load(); + return; + } + if (this.plugin.getLootboxRegister().getLootboxes().containsKey(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.RELOADED_SINGULAR.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + this.plugin.getLootboxRegister().removeLootbox(lootbox); + this.plugin.getLootboxManager().initialize(lootbox); + return; + } + player.sendMessage(Language.LOOTBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + + @SubCommand("list") + @Alias({"all", "view"}) + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox list") + public void listCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + + AdminLootboxInventory adminLootboxInventory = new AdminLootboxInventory(player, this.plugin, false); + adminLootboxInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("viewweekly") + @Alias({"weekly", "weeklylootbox"}) + @WrongUsage("&eUsage: /lootbox weekly") + public void viewWeeklyCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + CurrentLootboxInventory currentLootboxInventory = new CurrentLootboxInventory(player, plugin); + currentLootboxInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("setweekly") + @Alias({"setweekly", "setweeklylootbox"}) + @WrongUsage("&eUsage: /lootbox setweekly ") + @Permission("cranked.admin") + public void setWeeklyCommand(CommandSender commandSender, @Completion("#lootboxes") String lootbox) { + Player player = (Player) commandSender; + + if (!this.plugin.getLootboxRegister().isLootbox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + this.plugin.getLootboxRegister().setWeeklyLootbox(this.plugin.getLootboxRegister().getLootbox(lootbox)); + player.sendMessage(Language.PREFIX.getMessage() + CC.translate("&aSuccessfully set weekly lootbox to " + lootbox)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @SubCommand("give") + @Alias("send") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox give [amount]") + public void giveCommand(CommandSender commandSender, @Completion("#players")Player player, @Completion("#lootboxes") String lootbox, @Optional Integer amount) { + if(amount == null) amount = 1; + + if(!player.isOnline()) { + player.sendMessage(Language.PREFIX.getMessage() + CC.translate("&cThat player is not online")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(!this.plugin.getLootboxRegister().isLootbox(lootbox)) { + commandSender.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + //sender.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + this.plugin.getLootboxManager().giveLootbox(player, this.plugin.getLootboxRegister().getLootbox(lootbox), amount); + commandSender.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_GIVEN.getMessage().replace("%lootbox%", lootbox)); + //sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + //player.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_RECEIVED.getMessage().replace("%lootbox%", CC.translate(this.plugin.getLootboxRegister().getLootbox(lootbox).getDisplayName()))); + } + + @SubCommand("giveall") + @Alias("sendall") + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox giveall [amount]") + public void giveCommand(CommandSender commandSender, @Completion("#lootboxes") String lootbox, @Optional Integer amount) { + if(amount == null) amount = 1; + + if(!this.plugin.getLootboxRegister().isLootbox(lootbox)) { + commandSender.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + SoundUtils.tryPlayErrorSound(commandSender); + return; + } + + commandSender.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_GIVEN.getMessage().replace("%lootbox%", lootbox)); + SoundUtils.tryPlaySuccessSound(commandSender); + + final Map ipMap = new HashMap<>(); + for (final Player p : Bukkit.getOnlinePlayers()) { + if(commandSender instanceof Player) { + if(p.getUniqueId().toString().equals(((Player) commandSender).getUniqueId().toString())) { + continue; + } + } + final String ip = p.getAddress().getAddress().toString(); + if (ipMap.containsKey(ip) && ipMap.get(ip) > 0) { + continue; + } + + this.plugin.getLootboxManager().giveLootbox(p, this.plugin.getLootboxRegister().getLootbox(lootbox), amount); + p.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_RECEIVED.getMessage().replace("%lootbox%", CC.translate(this.plugin.getLootboxRegister().getLootbox(lootbox).getDisplayName()))); + + p.playSound(p.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + ipMap.put(ip, ipMap.getOrDefault(ip, 0) + 1); + } + } + + + @SubCommand("addreward") + @Alias({"additem", "addloot"}) + @Permission("cranked.admin") + @WrongUsage("&eUsage: /lootbox addreward [jackpot]") + public void addItemCommand(CommandSender commandSender, @Completion("#lootboxes") String lootbox, Double chance, @Optional Boolean jackpot) { + if (jackpot == null) + jackpot = false; + this.plugin.getLootboxManager().addItem((Player)commandSender, lootbox, chance, jackpot); + } + + @SubCommand("removereward") + @Alias({"removeitem", "removeloot"}) + @Permission("cranked.admin") + public void removeItemCommand(CommandSender commandSender, @Completion("#lootboxes") String lootbox) { + Player player = (Player)commandSender; + this.plugin.getLootboxManager().removeItemFromLootbox(player, player.getItemInHand(), lootbox); + } + + @SubCommand("clearrewardsinalllootboxes") + @Permission("*") + public void clear(CommandSender commandSender) { + if(commandSender instanceof Player) return; + this.plugin.getLootboxRegister().getLootboxes().forEach((lootboxName, lootbox) -> { + lootbox.getRewards().clear(); + + File file = new File(this.plugin.getDataFolder() + "/Lootboxes/" + lootboxName + ".yml"); + if (file.exists()) { + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file); + yamlConfiguration.set("rewards", null); + try { + yamlConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + commandSender.sendMessage(CC.translate("&aSuccessfully cleared all lootbox rewards")); + + } + + @SubCommand("half") + @Alias({"leftorright", "halfgen", "randomhalf"}) + @WrongUsage("/lb half [left/right]") + @Permission("cranked.admin") + public void giveHalf(final Player player, String lootbox, @Optional String half) { + + if(!this.plugin.getLootboxRegister().isLootbox(lootbox)) { + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_INVALID.getMessage().replace("%lootbox%", lootbox)); + SoundUtils.tryPlayErrorSound(player); + return; + } + + Lootbox lootboxObject = this.plugin.getLootboxRegister().getLootbox(lootbox); + + if(half == null) { + player.getInventory().addItem(lootboxObject.buildLeftOrRightHalf()); + return; + } + half = half.toLowerCase(Locale.ROOT).equals("left") ? "left" : "right"; + player.getInventory().addItem(lootboxObject.buildHalf(half)); + player.sendMessage(CC.translate("&aGiven " + half + " half for " + lootbox)); + } + + private void sendAdminHelpMessage(Player player) { + player.sendMessage(""); + player.sendMessage(CC.translate("&cCranked&fPvP &8| &cLootboxes")); + player.sendMessage(CC.translate("&c[] &8- &fOptional Argument")); + player.sendMessage(CC.translate("&4<> &8- &fRequired Argument")); + player.sendMessage(""); + player.sendMessage(CC.translate(" &c* &f/lootbox create [amount of rewards]")); + player.sendMessage(CC.translate(" &c* &f/lootbox delete ")); + player.sendMessage(CC.translate(" &c* &f/lootbox enable ")); + player.sendMessage(CC.translate(" &c* &f/lootbox disable ")); + player.sendMessage(CC.translate(" &c* &f/lootbox additem [jackpot]")); + player.sendMessage(CC.translate(" &c* &f/lootbox removeitem ")); + player.sendMessage(CC.translate(" &c* &f/lootbox reload [lootbox]")); + player.sendMessage(CC.translate(" &c* &f/lootbox list")); + player.sendMessage(CC.translate(" &c* &f/lootbox viewweekly")); + player.sendMessage(CC.translate(" &c* &f/lootbox setweekly ")); + player.sendMessage(CC.translate(" &c* &f/lootbox give [amount]")); + player.sendMessage(CC.translate(" &c* &f/lootbox giveall [amount]")); + player.sendMessage(""); + } +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/AdminLootboxInventory.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/AdminLootboxInventory.java new file mode 100644 index 0000000..bab9647 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/AdminLootboxInventory.java @@ -0,0 +1,80 @@ +package net.crankedpvp.lootboxes.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.language.Language; +import net.crankedpvp.lootboxes.struct.Lootbox; +import net.crankedpvp.lootboxes.struct.RewardType; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Map; +import java.util.Objects; +import java.util.function.Predicate; + +public class AdminLootboxInventory { + + private final PaginatedGui lootboxMenu; + + public PaginatedGui getUI() { + return this.lootboxMenu; + } + + + public AdminLootboxInventory(Player player, CrankedLootboxes plugin, boolean bundles) { + + Map lootboxObjectMap = plugin.getLootboxRegister().getSortedLootboxes(); + + this.lootboxMenu = new PaginatedGui(6, 28, "Cranked Lootboxes"); + this.lootboxMenu.setDefaultClickAction(event -> event.setCancelled(true)); + this.lootboxMenu.getFiller().fillBorder(new GuiItem(GuiUtil.createFillerItem())); + ItemStack info = new ItemBuilder(Material.BOOK_AND_QUILL, CC.translate("&cCranked&fPvP &cLootboxes")).build(); + this.lootboxMenu.setItem(1, 5, new GuiItem(info)); + + this.lootboxMenu.setItem(6, 1, new GuiItem(GuiUtil.createPreviousItem(), event -> { + this.lootboxMenu.previous(); + event.setCancelled(true); + })); + this.lootboxMenu.setItem(6, 9, new GuiItem(GuiUtil.createNextItem(), event -> { + this.lootboxMenu.next(); + event.setCancelled(true); + })); + + setupSwitchItem(player, plugin, bundles); + + lootboxObjectMap.entrySet().stream() + .filter(Objects::nonNull) + .filter(this.filterLootboxType(bundles)) + .forEach(lootbox -> { + ItemStack itemStack = lootbox.getValue().createLootbox(1); + this.lootboxMenu.addItem(new GuiItem(itemStack, event -> { + if(player.hasPermission("cranked.admin")) { + player.getInventory().addItem(itemStack); + player.sendMessage(CC.translate(Language.PREFIX.getMessage() + "&aYou have been given a " + lootbox.getKey() + " lootbox")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + })); + }); + } + + private Predicate> filterLootboxType(boolean bundles) { + if(bundles) return lootbox -> lootbox.getValue().getRewardType() == RewardType.BUNDLE; + return lootbox -> lootbox.getValue().getRewardType() != RewardType.BUNDLE; + } + + + private void setupSwitchItem(Player player, CrankedLootboxes plugin, boolean bundle) { + ItemBuilder itemBuilder = bundle ? new ItemBuilder(Material.STICK, "&f&lSwitch to &b&lLootboxes") : new ItemBuilder(Material.BLAZE_ROD, "&f&lSwitch to &c&lBundles"); + this.lootboxMenu.setItem(1, 9, new GuiItem(itemBuilder.colorize().build(), event -> { + player.closeInventory(); + AdminLootboxInventory adminLootboxInventory = new AdminLootboxInventory(player, plugin, !bundle); + adminLootboxInventory.getUI().open(player); + })); + } +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/CurrentLootboxInventory.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/CurrentLootboxInventory.java new file mode 100644 index 0000000..5cf85c4 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/CurrentLootboxInventory.java @@ -0,0 +1,39 @@ +package net.crankedpvp.lootboxes.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class CurrentLootboxInventory { + + private CrankedLootboxes plugin; + private final Gui currentLootboxInventory; + + public Gui getUI() { + return this.currentLootboxInventory; + } + + public CurrentLootboxInventory(Player player, CrankedLootboxes plugin) { + this.plugin = plugin; + this.currentLootboxInventory = new Gui(6, "Cranked Weekly Lootbox"); + this.currentLootboxInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.currentLootboxInventory.getFiller().fill(new GuiItem(createFillerItem())); + ItemStack lootbox = this.plugin.getLootboxRegister().getWeeklyLootbox() == null ? this.plugin.getLootboxRegister().select(this.plugin.getLootboxRegister().getLootboxObjects()).createLootbox(1) : this.plugin.getLootboxRegister().getWeeklyLootbox().createLootbox(1); + this.currentLootboxInventory.setItem(3, 5, new GuiItem(lootbox)); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("")); + item.setItemMeta(meta); + return item; + } + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/HypeboxAnimationInventory.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/HypeboxAnimationInventory.java new file mode 100644 index 0000000..12f0066 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/HypeboxAnimationInventory.java @@ -0,0 +1,143 @@ +package net.crankedpvp.lootboxes.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.struct.Lootbox; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitTask; + +public class HypeboxAnimationInventory { + + private BukkitTask fastAnimationTask; + private BukkitTask slowerAnimationTask; + private BukkitTask slowAnimationTask; + + private int amountOfSpins = 0; + + private ItemStack receivingItem; + + private final ItemStack[] itemStacks = new ItemStack[9]; + + private final Player player; + + + private final Gui hypeBoxAnimationInventory; + + public Gui getUI() { + return this.hypeBoxAnimationInventory; + } + + public HypeboxAnimationInventory(Player player, Lootbox lootbox) { + this.player = player; + this.amountOfSpins = 0; + this.receivingItem = lootbox.pickRandomReward(); + this.hypeBoxAnimationInventory = new Gui(3, CC.translate(lootbox.getDisplayName())); + this.hypeBoxAnimationInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.hypeBoxAnimationInventory.getFiller().fill(new GuiItem(createFillerItem())); + this.hypeBoxAnimationInventory.setItem(1, 5, new GuiItem(this.createWinningFillerItem())); + this.hypeBoxAnimationInventory.setItem(3, 5, new GuiItem(this.createWinningFillerItem())); + this.hypeBoxAnimationInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(this.fastAnimationTask != null) this.fastAnimationTask.cancel(); + if(this.slowerAnimationTask != null) this.slowerAnimationTask.cancel(); + if(this.slowAnimationTask != null) this.slowAnimationTask.cancel(); + player.getInventory().addItem(receivingItem); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate("&d&lHype Boxes &8" + Arrow.arrow() + " &f" + LuckpermUtils.getDisplayName(player) + " &fhas just opened a " + lootbox.getDisplayName() + "&r &fand received:")); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate(" &f• &l" + receivingItem.getAmount() + "x &r" + (receivingItem.hasItemMeta() ? receivingItem.getItemMeta().getDisplayName() : receivingItem.getType().name()))); + + }); + + for(int i = 0; i < 9; i++) { + ItemStack itemStack = lootbox.pickRandomReward(); + this.itemStacks[i] = itemStack; + this.hypeBoxAnimationInventory.setItem(2, i+1, new GuiItem(itemStack)); + } + + this.fastAnimationTask = Bukkit.getScheduler().runTaskTimer(CrankedLootboxes.getInstance(), () -> shiftAllItemsToTheLeftOnceAtHighSpeed(lootbox), 3L, 3L); + } + + public void shiftAllItemsToTheLeftOnceAtHighSpeed(Lootbox lootbox) { + this.amountOfSpins++; + ItemStack[] itemStacks = this.itemStacks.clone(); + for(int i = 0; i < 8; i++) { + this.itemStacks[i] = itemStacks[i+1]; + } + this.itemStacks[8] = lootbox.pickRandomReward(); + + for(int i = 0; i < 9; i++) { + this.hypeBoxAnimationInventory.updateItem(2, i+1, new GuiItem(this.itemStacks[i])); + } + this.player.updateInventory(); + this.player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 1.0f, 2.0f); + + if(this.amountOfSpins == 40) { + this.amountOfSpins = 0; + this.fastAnimationTask.cancel(); + this.slowerAnimationTask = Bukkit.getScheduler().runTaskTimer(CrankedLootboxes.getInstance(), () -> shiftAllItemsToTheLeftOnceAtSlowerSpeed(lootbox), 0L, 7L); + } + } + + public void shiftAllItemsToTheLeftOnceAtSlowerSpeed(Lootbox lootbox) { + this.amountOfSpins++; + ItemStack[] itemStacks = this.itemStacks.clone(); + for(int i = 0; i < 8; i++) { + this.itemStacks[i] = itemStacks[i+1]; + } + this.itemStacks[8] = lootbox.pickRandomReward(); + + for(int i = 0; i < 9; i++) { + this.hypeBoxAnimationInventory.updateItem(2, i+1, new GuiItem(this.itemStacks[i])); + } + this.player.updateInventory(); + this.player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 1.0f, 2.0f); + + if(this.amountOfSpins == 10) { + this.amountOfSpins = 0; + this.slowerAnimationTask.cancel(); + this.slowAnimationTask = Bukkit.getScheduler().runTaskTimer(CrankedLootboxes.getInstance(), () -> shiftAllItemsToTheLeftOnceAtSlowSpeed(lootbox), 0L, 12L); + } + } + + public void shiftAllItemsToTheLeftOnceAtSlowSpeed(Lootbox lootbox) { + this.amountOfSpins++; + ItemStack[] itemStacks = this.itemStacks.clone(); + for(int i = 0; i < 8; i++) { + this.itemStacks[i] = itemStacks[i+1]; + } + this.itemStacks[8] = lootbox.pickRandomReward(); + + for(int i = 0; i < 9; i++) { + this.hypeBoxAnimationInventory.updateItem(2, i+1, new GuiItem(this.itemStacks[i])); + } + this.player.updateInventory(); + this.player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 1.0f, 2.0f); + + if(this.amountOfSpins == 5) { + this.slowAnimationTask.cancel(); + this.receivingItem = this.itemStacks[4]; + } + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate(" ")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createWinningFillerItem() { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.BLACK.getData()).setName(" ").setGlowing().build(); + } + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/LuckyBlockAnimationInventory.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/LuckyBlockAnimationInventory.java new file mode 100644 index 0000000..cc326a9 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/LuckyBlockAnimationInventory.java @@ -0,0 +1,90 @@ +package net.crankedpvp.lootboxes.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.lootboxes.struct.Lootbox; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class LuckyBlockAnimationInventory { + + private boolean hasOpened; + + private final Gui luckyBlockInventory; + + public Gui getUI() { + return this.luckyBlockInventory; + } + + public LuckyBlockAnimationInventory(Player player, Lootbox lootbox) { + this.luckyBlockInventory = new Gui(3, "Choose One..."); + this.luckyBlockInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.luckyBlockInventory.getFiller().fill(new GuiItem(createFillerItem())); + this.luckyBlockInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(!this.hasOpened) { + ItemStack itemStack = lootbox.pickRandomReward(); + player.getInventory().addItem(itemStack); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate("&d&lLucky Blocks &8" + Arrow.arrow() + LuckpermUtils.getDisplayName(player) + " &fhas just opened a " + lootbox.getDisplayName() + "&r &fand received:")); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate(" &f• &l" + itemStack.getAmount() + "x &r" + (itemStack.hasItemMeta() ? itemStack.getItemMeta().getDisplayName() : itemStack.getType().name()))); + } + }); + + ItemStack one = lootbox.pickRandomReward(); + ItemStack two = lootbox.pickRandomReward(); + ItemStack three = lootbox.pickRandomReward(); + + this.luckyBlockInventory.updateItem(2, 3, new GuiItem(getLuckyBlock(lootbox.getSkullValue()), event -> { + this.setItems(one, two, three); + player.getInventory().addItem(one); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate("&d&lLucky Blocks &8" + Arrow.arrow() + " &f" + LuckpermUtils.getDisplayName(player) + " &fhas just opened a " + lootbox.getDisplayName() + "&r &fand received:")); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate(" &f• &l" + one.getAmount() + "x &r" + (one.hasItemMeta() ? one.getItemMeta().getDisplayName() : one.getType().name()))); + })); + + this.luckyBlockInventory.updateItem(2, 5, new GuiItem(getLuckyBlock(lootbox.getSkullValue()), event -> { + this.setItems(one, two, three); + player.getInventory().addItem(two); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate("&d&lLucky Blocks &8" + Arrow.arrow() + " &f" + LuckpermUtils.getDisplayName(player) + " &fhas just opened a " + lootbox.getDisplayName() + "&r &fand received:")); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate(" &f• &l" + two.getAmount() + "x &r" + (two.hasItemMeta() ? two.getItemMeta().getDisplayName() : two.getType().name()))); + })); + + this.luckyBlockInventory.updateItem(2, 7, new GuiItem(getLuckyBlock(lootbox.getSkullValue()), event -> { + this.setItems(one, two, three); + player.getInventory().addItem(three); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate("&d&lLucky Blocks &8" + Arrow.arrow() + " &f" + LuckpermUtils.getDisplayName(player) + " &fhas just opened a " + lootbox.getDisplayName() + "&r &fand received:")); + if(lootbox.doesBroadcast())Bukkit.broadcastMessage(CC.translate(" &f• &l" + three.getAmount() + "x &r" + (three.hasItemMeta() ? three.getItemMeta().getDisplayName() : three.getType().name()))); + })); + } + + private void setItems(ItemStack one, ItemStack two, ItemStack three) { + this.hasOpened = true; + this.luckyBlockInventory.updateItem(2, 3, new GuiItem(one)); + this.luckyBlockInventory.updateItem(2, 5, new GuiItem(two)); + this.luckyBlockInventory.updateItem(2, 7, new GuiItem(three)); + } + + private ItemStack getLuckyBlock(String skullURL) { + ItemBuilder itemBuilder = new ItemBuilder(SkullUtils.getSkullFromSkin(skullURL)); + itemBuilder.setName("&c&l???"); + itemBuilder.setLore("&7Click here to receive a", + "&7random lucky block reward"); + return itemBuilder.colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("")); + item.setItemMeta(meta); + return item; + } + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/PreviewLootboxInventory.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/PreviewLootboxInventory.java new file mode 100644 index 0000000..d0c8ce8 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/inventory/PreviewLootboxInventory.java @@ -0,0 +1,64 @@ +package net.crankedpvp.lootboxes.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.language.Language; +import net.crankedpvp.lootboxes.struct.Reward; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class PreviewLootboxInventory { + private final PaginatedGui previewInventory; + + public PaginatedGui getUI() { + return this.previewInventory; + } + + public PreviewLootboxInventory(Player player, String name, CrankedLootboxes plugin) { + this.previewInventory = new PaginatedGui(6, 28, "Cranked Preview Lootbox"); + this.previewInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.previewInventory.getFiller().fillBorder(new GuiItem(GuiUtil.createFillerItem())); + ItemBuilder info = new ItemBuilder(Material.BOOK_AND_QUILL, "&aPreview Loot"); + if (player.hasPermission("cranked.admin")) { + info.addLoreLine("&7Left-Click to add reward to your inventory"); + info.addLoreLine("&7Right-Click to remove a reward"); + } + this.previewInventory.setItem(1, 5, new GuiItem(info.colorize().build())); + this.previewInventory.setItem(1, 1, new GuiItem(GuiUtil.createExitItem(), event -> player.closeInventory())); + this.previewInventory.setItem(1, 9, new GuiItem(GuiUtil.createExitItem(), event -> player.closeInventory())); + this.previewInventory.setItem(6, 1, new GuiItem(GuiUtil.createPreviousItem(), event -> { + this.previewInventory.previous(); + event.setCancelled(true); + })); + this.previewInventory.setItem(6, 9, new GuiItem(GuiUtil.createNextItem(), event -> { + this.previewInventory.next(); + event.setCancelled(true); + })); + for (Reward reward : plugin.getLootboxRegister().getLootbox(name).getRewards()) { + ItemStack item = reward.getItemStack(); + this.previewInventory.addItem(new GuiItem(item, event -> { + if (player.hasPermission("cranked.admin")) { + if (event.isShiftClick() && event.isRightClick()) { + plugin.getLootboxManager().removeItemFromLootbox(player, item, name); + ItemStack itemStack = item.clone(); + itemStack.setType(Material.BARRIER); + this.previewInventory.updateItem(event.getSlot(), new GuiItem(itemStack)); + player.playSound(player.getLocation(), Sound.ANVIL_BREAK, 2.0F, 2.0F); + } + if (event.isLeftClick()) { + player.getInventory().addItem(item); + player.sendMessage(CC.translate(Language.PREFIX.getMessage() + "&a+ " + item.getItemMeta().getDisplayName())); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + } + })); + } + } + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/Config.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/Config.java new file mode 100644 index 0000000..0404260 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/Config.java @@ -0,0 +1,103 @@ +package net.crankedpvp.lootboxes.language; + + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Config { + LOOTBOX_HEADER(), + LOOTBOX_FOOTER(), + LOOTBOX_REWARD_TITLE(), + LOOTBOX_REWARD_LINE(), + LOOTBOX_JACKPOT_TITLE(), + LOOTBOX_JACKPOT_LINE(), + LOOTBOX_MATERIAL() + + ; + + + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/FileHandler.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/FileHandler.java new file mode 100644 index 0000000..f6673f3 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/FileHandler.java @@ -0,0 +1,137 @@ +package net.crankedpvp.lootboxes.language; + +import net.crankedpvp.lootboxes.CrankedLootboxes; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class FileHandler { + + private final File languageFile; + private final File configFile; + private final FileConfiguration languageFileConfiguration; + private final FileConfiguration configFileConfiguration; + private final String languagePath; + private final String configPath; + private final CrankedLootboxes plugin; + + public FileHandler(CrankedLootboxes plugin) { + this.plugin = plugin; + this.languagePath = "language.yml"; + languageFile = new File(plugin.getDataFolder(), languagePath); + languageFileConfiguration = new YamlConfiguration(); + + this.configPath = "config.yml"; + configFile = new File(plugin.getDataFolder(), configPath); + configFileConfiguration = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultLanguage(); + this.loadLanguageFromDisk(); + this.copyLanguageDefaults(); + this.saveLanguage(); + this.loadLanguageFromDisk(); + this.loadLanguageMessages(); + + this.saveDefaultConfig(); + this.loadConfigFromDisk(); + this.copyConfigDefaults(); + this.saveConfig(); + this.loadConfigFromDisk(); + this.loadConfigMessages(); + } + + private void loadLanguageMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (languageFileConfiguration.isList(path)) { + entry.setValue(languageFileConfiguration.getStringList(path)); + continue; + } + entry.setValue(languageFileConfiguration.getString(path)); + } + } + + private void loadConfigMessages() { + for (Config entry : Config.values()) { + String path = entry.getPath(); + if (configFileConfiguration.isList(path)) { + entry.setValue(configFileConfiguration.getStringList(path)); + continue; + } + entry.setValue(configFileConfiguration.getString(path)); + } + } + + + private void loadLanguageFromDisk() { + try { + languageFileConfiguration.load(languageFile); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + private void loadConfigFromDisk() { + try { + configFileConfiguration.load(configFile); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void saveLanguage() { + try { + languageFileConfiguration.save(languageFile); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + languageFile.getPath() + "!"); + e.printStackTrace(); + } + } + + public void saveConfig() { + try { + configFileConfiguration.save(configFile); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + configFile.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyLanguageDefaults() { + InputStream defConfig = plugin.getResource(this.languagePath); + if (defConfig != null) { + languageFileConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + languageFileConfiguration.options().copyDefaults(true); + } + + private void copyConfigDefaults() { + InputStream defConfig = plugin.getResource(this.configPath); + if (defConfig != null) { + configFileConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + configFileConfiguration.options().copyDefaults(true); + } + + private void saveDefaultLanguage() { + if (!languageFile.exists()) { + languageFile.getParentFile().mkdirs(); + plugin.saveResource(languageFile.getName(),false); + } + } + + private void saveDefaultConfig() { + if (!configFile.exists()) { + configFile.getParentFile().mkdirs(); + plugin.saveResource(configFile.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/Language.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/Language.java new file mode 100644 index 0000000..102d56c --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/language/Language.java @@ -0,0 +1,120 @@ +package net.crankedpvp.lootboxes.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + PREFIX, + FULL_INVENTORY, + + + ALREADY_LOOTBOX, + CREATED_LOOTBOX, + DELETED_LOOTBOX, + LOOTBOX_DISABLED, + LOOTBOX_ENABLED, + LOOTBOX_INVALID, + RELOADED_ALL, + RELOADED_SINGULAR, + + LOOTBOX_RECEIVED, + LOOTBOX_GIVEN, + + LOOTBOX_ADDITEM, + LOOTBOX_ITEM_ALREADY_IN, + + LOOTBOX_ITEM_NOT_FOUND, + LOOTBOX_REMOVE_ITEM, + + PREVIEW_LOOT, + LOOTBOX_OPENED, + + + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/CombineListener.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/CombineListener.java new file mode 100644 index 0000000..cf87922 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/CombineListener.java @@ -0,0 +1,58 @@ +package net.crankedpvp.lootboxes.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.struct.Lootbox; +import net.crankedpvp.lootboxes.struct.LootboxManager; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class CombineListener implements Listener { + + private final CrankedLootboxes plugin; + public CombineListener(CrankedLootboxes plugin) { + this.plugin = plugin; + } + + @EventHandler + public void combine(InventoryClickEvent event) { + if(event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR) return; + if(event.getCursor() == null || event.getCursor().getType() == Material.AIR) return; + + Player player = (Player) event.getWhoClicked(); + ItemStack clickedItem = event.getCurrentItem(); + ItemStack cursorItem = event.getCursor(); + + if(!LootboxManager.isLootboxHalf(clickedItem)) return; + if(!LootboxManager.isLootboxHalf(cursorItem)) return; + + if(clickedItem.getAmount() > 1 || cursorItem.getAmount() > 1) { + player.sendMessage(CC.translate("&cYou cannot merge stacked half lootboxes")); + SoundUtils.tryPlayErrorSound(player); + return; + } + + NBTItem nbtClickedItem = new NBTItem(clickedItem); + NBTItem nbtCursorItem = new NBTItem(cursorItem); + + String lootbox = nbtClickedItem.getString("halfLootbox"); + if(!nbtCursorItem.getString("halfLootbox").equals(lootbox)) return; + + Lootbox lootboxObject = CrankedLootboxes.getInstance().getLootboxRegister().getLootbox(lootbox); + String side = nbtClickedItem.getString("side"); + if(nbtCursorItem.getString("side").equals(side)) return; + + event.setCurrentItem(null); + event.setCursor(null); + player.getInventory().addItem(lootboxObject.createLootbox(1)); + player.playSound(player.getLocation(), Sound.ANVIL_USE, 2.0f, 2.0f); + + } +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/OpenLootboxListener.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/OpenLootboxListener.java new file mode 100644 index 0000000..ded10ee --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/OpenLootboxListener.java @@ -0,0 +1,98 @@ +package net.crankedpvp.lootboxes.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.inventory.HypeboxAnimationInventory; +import net.crankedpvp.lootboxes.inventory.LuckyBlockAnimationInventory; +import net.crankedpvp.lootboxes.language.Language; +import net.crankedpvp.lootboxes.struct.Lootbox; +import net.crankedpvp.lootboxes.struct.LootboxManager; +import net.crankedpvp.lootboxes.struct.RewardType; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public class OpenLootboxListener implements Listener { + private final CrankedLootboxes plugin; + public OpenLootboxListener(CrankedLootboxes plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if(event.getAction() == null) return; + if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { + ItemStack itemStack = event.getItem(); + if(!LootboxManager.isLootbox(itemStack)) return; + event.setCancelled(true); + final NBTItem nbtItem = new NBTItem(itemStack); + final Lootbox lootbox = plugin.getLootboxRegister().getLootbox(nbtItem.getOrCreateCompound("cosmicData").getString("lootboxID")); + if(lootbox == null) return; + if(lootbox.getRewards().isEmpty()) return; + + int looper = (lootbox.getRewardType().equals(RewardType.LOOTBOX) || lootbox.getRewardType().equals(RewardType.BUNDLE)) ? (event.getPlayer().isSneaking() ? itemStack.getAmount() : 1) : 1; + for (int i = 0; i < looper; i++) { + if(!InventoryUtils.hasAvaliableSlot(event.getPlayer(), lootbox.getAmountOfRewards())) { + event.getPlayer().sendMessage(Language.PREFIX.getMessage() + Language.FULL_INVENTORY.getMessage()); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.LAVA_POP, 1.0F, 1.0F); + return; + } + + final int amount = itemStack.getAmount(); + if (amount <= 1) { + event.getPlayer().setItemInHand(null); + } else { + itemStack.setAmount(amount - 1); + event.getPlayer().setItemInHand(itemStack); + } + + //event.getPlayer().sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_OPENED.getMessage().replace("%lootbox%", StringUtils.toNiceString(lootbox.getId()))); + if(i == 0) event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.SUCCESSFUL_HIT, 0.5F, 0.5F); + + if(lootbox.getRewardType() == RewardType.HYPEBOX) { + HypeboxAnimationInventory hypeboxAnimationInventory = new HypeboxAnimationInventory(event.getPlayer(), lootbox); + hypeboxAnimationInventory.getUI().open(event.getPlayer()); + return; + } + if(lootbox.getRewardType() == RewardType.LUCKY_BLOCK) { + LuckyBlockAnimationInventory luckyBlockAnimationInventory = new LuckyBlockAnimationInventory(event.getPlayer(), lootbox); + luckyBlockAnimationInventory.getUI().open(event.getPlayer()); + return; + } + if(lootbox.getRewardType() == RewardType.BUNDLE) { + if(lootbox.doesBroadcast()) Bukkit.broadcastMessage(CC.translate("&d&lBundles &8" + Arrow.arrow() + " &f" + LuckpermUtils.getDisplayName(event.getPlayer()) + " &fhas just opened a " + lootbox.getDisplayName() + "&r &fand received:")); + lootbox.getRewards().forEach(reward -> { + event.getPlayer().getInventory().addItem(reward.getItemStack()); + if(lootbox.doesBroadcast()) Bukkit.broadcastMessage(CC.translate(" &f• &l" + reward.getItemStack().getAmount() + "x &r" + (reward.getItemStack().hasItemMeta() ? reward.getItemStack().getItemMeta().getDisplayName() : reward.getItemStack().getType().name()))); + + }); + return; + } + if(lootbox.getRewardType() == RewardType.LOOTBOX) { + + if(lootbox.doesBroadcast()) Bukkit.broadcastMessage(CC.translate("&d&lLootboxes &8" + Arrow.arrow() + " &r" + LuckpermUtils.getDisplayName(event.getPlayer()) + " &fhas just opened a " + lootbox.getDisplayName() + "&r &fand received:")); + final Map rewards = new HashMap<>(); + lootbox.getRewards().stream() + .filter(Objects::nonNull) + .forEach(reward -> rewards.put(reward.getItemStack(), reward.getChance())); + for(int rewardNum = 0; rewardNum < lootbox.getAmountOfRewards(); rewardNum++) { + ItemStack reward = RandomUtils.getRandomItem(rewards); + event.getPlayer().getInventory().addItem(reward); + assert reward != null; + if(lootbox.doesBroadcast()) Bukkit.broadcastMessage(CC.translate(" &f• &l" + reward.getAmount() + "x &r" + (reward.hasItemMeta() ? reward.getItemMeta().getDisplayName() : reward.getType().name()))); + } + } + } + } + } +} \ No newline at end of file diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/OpenSidePickerListener.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/OpenSidePickerListener.java new file mode 100644 index 0000000..ff5335a --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/OpenSidePickerListener.java @@ -0,0 +1,55 @@ +package net.crankedpvp.lootboxes.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.language.Language; +import net.crankedpvp.lootboxes.struct.Lootbox; +import net.crankedpvp.lootboxes.struct.LootboxManager; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class OpenSidePickerListener implements Listener { + private final CrankedLootboxes plugin; + public OpenSidePickerListener(CrankedLootboxes plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if(event.getAction() == null) return; + if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { + ItemStack itemStack = event.getItem(); + if(!LootboxManager.isLootboxHalfGenerator(itemStack)) return; + event.setCancelled(true); + final NBTItem nbtItem = new NBTItem(itemStack); + final Lootbox lootbox = plugin.getLootboxRegister().getLootbox(nbtItem.getString("leftOrRightHalf")); + if(lootbox == null) return; + if(!InventoryUtils.hasAvaliableSlot(event.getPlayer(), lootbox.getAmountOfRewards())) { + event.getPlayer().sendMessage(Language.PREFIX.getMessage() + Language.FULL_INVENTORY.getMessage()); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.LAVA_POP, 1.0F, 1.0F); + return; + } + + final int amount = itemStack.getAmount(); + if (amount <= 1) { + event.getPlayer().setItemInHand(null); + } else { + itemStack.setAmount(amount - 1); + event.getPlayer().setItemInHand(itemStack); + } + + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.SUCCESSFUL_HIT, 0.5F, 0.5F); + + if(Math.random() > 0.55) { + event.getPlayer().getInventory().addItem(lootbox.buildHalf("left")); + return; + } + event.getPlayer().getInventory().addItem(lootbox.buildHalf("right")); + } + } +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/PreviewLootboxListener.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/PreviewLootboxListener.java new file mode 100644 index 0000000..a80bc78 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/listeners/PreviewLootboxListener.java @@ -0,0 +1,39 @@ +package net.crankedpvp.lootboxes.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.inventory.PreviewLootboxInventory; +import net.crankedpvp.lootboxes.language.Language; +import net.crankedpvp.lootboxes.struct.LootboxManager; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class PreviewLootboxListener implements Listener { + + private final CrankedLootboxes plugin; + public PreviewLootboxListener(CrankedLootboxes plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if(event.getPlayer() == null) return; + if(event.getItem() == null) return; + if(event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_AIR) { + if (LootboxManager.isLootbox(event.getItem())) { + event.setCancelled(true); + final NBTItem nbtItem = new NBTItem(event.getItem()); + final String name = nbtItem.getCompound("cosmicData").getString("lootboxID"); + PreviewLootboxInventory previewLootInventory = new PreviewLootboxInventory(event.getPlayer(), name, this.plugin); + previewLootInventory.getUI().open(event.getPlayer()); + event.getPlayer().sendMessage(Language.PREFIX.getMessage() + Language.PREVIEW_LOOT.getMessage().replace("%lootbox%", StringUtils.toNiceString(name))); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.CHEST_OPEN, 1.0F, 2.0F); + } + } + } + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/Lootbox.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/Lootbox.java new file mode 100644 index 0000000..5002a91 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/Lootbox.java @@ -0,0 +1,126 @@ +package net.crankedpvp.lootboxes.struct; + +import de.tr7zw.nbtapi.NBTItem; +import lombok.AllArgsConstructor; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.RandomUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +@Getter @AllArgsConstructor +public class Lootbox { + + private final String id; + private final String displayName; + private final List header; + private final List footer; + private final String rewardTitle; + private final String rewardLine; + private final String jackpotTitle; + private final String jackpotLine; + private final Material material; + private final boolean glowing; + private final boolean viewRewards; + private final boolean broadcastRewards; + private final int amountOfRewards; + private final RewardType rewardType; + private final String skullValue; + private final List rewards; + + public List getLore() { + List lore = new ArrayList<>(); + if(!header.isEmpty()) lore.addAll(header); + if(viewRewards) { + if(rewards.stream().anyMatch(rewardObject -> !rewardObject.isJackpot())) { + lore.add(rewardTitle.replace("%rewards%", String.valueOf(amountOfRewards))); + for(Reward reward : rewards) { + if(!reward.isJackpot()) { + if(reward.getSpecialName() == null || reward.getSpecialName().equals("null")) { + lore.add(rewardLine.replace("%amount%", String.valueOf(reward.getItemStack().getAmount())).replace("%name%", reward.getItemStack().getItemMeta().getDisplayName())); + } else { + lore.add(reward.getSpecialName()); + } + } + } + } + if(rewards.stream().anyMatch(Reward::isJackpot)) { + if(rewards.stream().anyMatch(rewardObject -> !rewardObject.isJackpot())) lore.add(""); + lore.add(jackpotTitle); + for(Reward reward : rewards) { + if(reward.isJackpot()) { + if(reward.getSpecialName() == null || reward.getSpecialName().equals("null")) { + lore.add(jackpotLine.replace("%amount%", String.valueOf(reward.getItemStack().getAmount())).replace("%name%", reward.getItemStack().getItemMeta().getDisplayName())); + } else { + lore.add(reward.getSpecialName()); + } + } + } + } + } + lore.addAll(footer); + return lore; + } + + public ItemStack createLootbox(int amount) { + ItemBuilder itemBuilder = this.skullValue.equals("???") ? new ItemBuilder(material) : new ItemBuilder(SkullUtils.getSkullFromSkin(this.skullValue)); + itemBuilder.setAmount(amount); + itemBuilder.setName(this.displayName); + itemBuilder.setLore(this.getLore()).colorize(); + if (glowing) itemBuilder.setGlowing(); + NBTItem nbtItem = new NBTItem(itemBuilder.build()); + nbtItem.setBoolean("broadcast", this.broadcastRewards); + nbtItem.getOrCreateCompound("cosmicData").setString("customItem", "lootbox"); + nbtItem.getCompound("cosmicData").setString("lootboxID", id); + ItemStack itemStack = nbtItem.getItem(); + if(!this.skullValue.equals("???")) { + return SkullUtils.getSkull(itemStack, this.skullValue); + } + return nbtItem.getItem(); + } + + public ItemStack buildHalf(String side) { + String string = side.equals("left") ? "&b&lLeft Half (" + this.getDisplayName() + "&b&l)" : "&d&lRight Half (" + this.getDisplayName() + "&d&l)"; + String opposite = side.equals("left") ? "right" : "left"; + ItemBuilder itemBuilder = new ItemBuilder(Material.PRISMARINE_CRYSTALS, string, "&7Combine with the " + opposite + " half to", + "&7create a full " + this.getDisplayName()); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().setGlowing().build()); + nbtItem.setString("halfLootbox", this.getId()); + nbtItem.setString("side", side); + return nbtItem.getItem(); + + } + + public ItemStack buildLeftOrRightHalf() { + ItemBuilder itemBuilder = new ItemBuilder(Material.PAPER, "&b&lLEFT &f&l&nOR&r &d&lRIGHT &f&lHalf " + Arrow.arrow() + " " + this.getDisplayName(), + "&7Right-Click this lootbox to receive", + "&7either the &bleft &7or &dright&7 half", + "&7of the " + this.getDisplayName() + "&r &7lootbox", + "", + "&4&l(!) &7Obtained from &cbuy.crankedpvp.org &7(/buy)", + "", + "&f&lRandom Loot &7(1 Item)", + "&f&l* 1x &b&lLeft Half (" + this.getDisplayName() + "&b&l)", + "&f&l* 1x &d&lRight Half (" + this.getDisplayName() + "&d&l)" + ); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().setGlowing().build()); + nbtItem.setString("leftOrRightHalf", this.getId()); + return nbtItem.getItem(); + } + + public ItemStack pickRandomReward() { + final Map rewards = new HashMap<>(); + this.getRewards().stream() + .filter(Objects::nonNull) + .forEach(reward -> rewards.put(reward.getItemStack(), reward.getChance())); + return RandomUtils.getRandomItem(rewards); + } + + public boolean doesBroadcast() { + return this.broadcastRewards; + } +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/LootboxManager.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/LootboxManager.java new file mode 100644 index 0000000..16e9d71 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/LootboxManager.java @@ -0,0 +1,287 @@ +package net.crankedpvp.lootboxes.struct; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.lootboxes.language.Config; +import net.crankedpvp.lootboxes.language.Language; +import net.crankedpvp.lootboxes.utils.ItemStackSerializer; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; + +public class LootboxManager { + + private final CrankedLootboxes plugin; + public LootboxManager(CrankedLootboxes plugin) { + this.plugin = plugin; + } + + public static boolean isLootbox(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.getOrCreateCompound("cosmicData").hasKey("customItem")) return false; + return nbtItem.getCompound("cosmicData").hasKey("lootboxID"); + } + + public static boolean isLootboxHalfGenerator(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return (nbtItem.hasKey("leftOrRightHalf")); + } + + public static boolean isLootboxHalf(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasKey("halfLootbox")) return false; + return nbtItem.hasKey("side"); + } + + public static boolean doesLootboxBroadcast(ItemStack itemStack) { + if(!isLootbox(itemStack)) return false; + if (itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getBoolean("broadcast"); + } + + public void createDefaultConfig(String name) { + createDefaultConfig(name, 3); + } + + public void createDefaultConfig(String name, int amountOfRewards) { + File file = new File(this.plugin.getDataFolder(), "Lootboxes/" + name + ".yml"); + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + String[] colors = new String[]{"&a", "&b", "&c", "&d", "&e", "&2", "&3", "&4", "&5", "&6", "&9"}; + String color = colors[ThreadLocalRandom.current().nextInt(1, 10)]; + yamlConfiguration.set("Item.Display.Name", "&f&ki&r " + color + "&l" + StringUtils.toNiceString(name) + " &f&ki&r &f&lLootbox"); + yamlConfiguration.set("Item.Display.Header", Config.LOOTBOX_HEADER.getValuesAsList()); + yamlConfiguration.set("Item.Display.Footer", Config.LOOTBOX_FOOTER.getValuesAsList()); + yamlConfiguration.set("Item.Reward.Title", "" + Config.LOOTBOX_REWARD_TITLE.getValue()); + yamlConfiguration.set("Item.Reward.Line", "" + Config.LOOTBOX_REWARD_LINE.getValue()); + yamlConfiguration.set("Item.Jackpot.Title", "" + Config.LOOTBOX_JACKPOT_TITLE.getValue()); + yamlConfiguration.set("Item.Jackpot.Line", "" + Config.LOOTBOX_JACKPOT_LINE.getValue()); + yamlConfiguration.set("Item.Material", "" + Config.LOOTBOX_MATERIAL.getValue()); + yamlConfiguration.set("Item.Glowing", true); + yamlConfiguration.set("Misc.Reward.Amount", amountOfRewards); + yamlConfiguration.set("Misc.Reward.Type", "LOOTBOX"); + yamlConfiguration.set("Misc.View.Rewards", true); + yamlConfiguration.set("Misc.Broadcast.Rewards", false); + try { + yamlConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void createDefaultConfigFromItemStack(ItemStack itemStack, String name, int amountOfRewards) { + File file = new File(this.plugin.getDataFolder(), "Lootboxes/" + name + ".yml"); + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + ItemMeta itemMeta = itemStack.getItemMeta(); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + yamlConfiguration.set("Item.Display.Name", itemMeta.getDisplayName()); + yamlConfiguration.set("Item.Display.Header", itemMeta.getLore()); + yamlConfiguration.set("Item.Display.Footer", new ArrayList<>()); + yamlConfiguration.set("Item.Reward.Title", "" + Config.LOOTBOX_REWARD_TITLE.getValue()); + yamlConfiguration.set("Item.Reward.Line", "" + Config.LOOTBOX_REWARD_LINE.getValue()); + yamlConfiguration.set("Item.Jackpot.Title", "" + Config.LOOTBOX_JACKPOT_TITLE.getValue()); + yamlConfiguration.set("Item.Jackpot.Line", "" + Config.LOOTBOX_JACKPOT_LINE.getValue()); + yamlConfiguration.set("Item.Material", "" + itemStack.getType().name()); + yamlConfiguration.set("Item.Glowing", itemMeta.hasEnchants()); + yamlConfiguration.set("Misc.Reward.Amount", amountOfRewards); + yamlConfiguration.set("Misc.Reward.Type", "LOOTBOX"); + yamlConfiguration.set("Misc.View.Rewards", true); + yamlConfiguration.set("Misc.Broadcast.Rewards", false); + try { + yamlConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void createLootbox(String lootbox, Integer amountOfRewards) { + createDefaultConfig(lootbox, amountOfRewards); + this.initialize(lootbox); + } + + public void createLootboxFromItemStack(ItemStack itemStack, String lootbox, Integer amountOfRewards) { + createDefaultConfigFromItemStack(itemStack, lootbox, amountOfRewards); + this.initialize(lootbox); + } + + + + public void deleteConfig(String name) { + File file = new File(this.plugin.getDataFolder(), "Lootboxes/" + name + ".yml"); + if (file.exists()) + file.delete(); + } + + public void reloadLootbox(String lootbox) { + if (this.plugin.getLootboxRegister().isLootbox(lootbox)) { + this.plugin.getLootboxRegister().removeLootbox(lootbox); + initialize(lootbox); + } else { + System.out.println("[-] Failure reloading lootbox, " + lootbox); + } + } + + public void initializeAll() { + File dataFolder = new File(this.plugin.getDataFolder(), "Lootboxes"); + Arrays.stream(Objects.requireNonNull(dataFolder.listFiles())) + .filter(file -> !file.isDirectory()) + .filter(file -> !file.getName().startsWith("-")) + .forEach(file -> { + try { + initialize(file.getName().replace(".yml", "")); + } catch (NullPointerException exception) { + System.out.println("[CrankedLootboxes] Failed to register lootbox: " + file.getName().replace(".yml", "")); + } + }); + } + + public void initialize(String fileName) { + File file = new File(this.plugin.getDataFolder(), "Lootboxes/" + fileName + ".yml"); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + String name = yamlConfiguration.getString("Item.Display.Name"); + List header = yamlConfiguration.getStringList("Item.Display.Header"); + List footer = yamlConfiguration.getStringList("Item.Display.Footer"); + String rewardTitle = yamlConfiguration.getString("Item.Reward.Title"); + String rewardLine = yamlConfiguration.getString("Item.Reward.Line"); + String jackpotTitle = yamlConfiguration.getString("Item.Jackpot.Title"); + String jackpotLine = yamlConfiguration.getString("Item.Jackpot.Line"); + String mater = yamlConfiguration.getString("Item.Material"); + Material material = mater.contains("SKULL") ? Material.SKULL_ITEM : Material.valueOf(mater.toUpperCase()); + String skullValue = mater.contains(":") ? mater.split(":")[1] : "???"; + boolean glowing = yamlConfiguration.getBoolean("Item.Glowing"); + int rewardAmount = yamlConfiguration.getInt("Misc.Reward.Amount"); + boolean viewRewards = yamlConfiguration.getBoolean("Misc.View.Rewards"); + boolean broadcastRewards = yamlConfiguration.contains("Misc.Broadcast.Rewards") && yamlConfiguration.getBoolean("Misc.Broadcast.Rewards"); + RewardType rewardType = RewardType.valueOf(yamlConfiguration.getString("Misc.Reward.Type").toUpperCase()); + List rewards = getRewards(yamlConfiguration); + if(rewardType == RewardType.BUNDLE) rewardAmount = rewards.size(); + if(rewardType == RewardType.LUCKY_BLOCK) rewardAmount = 1; + Lootbox lootbox = new Lootbox(file.getName().replace(".yml", ""), name, header, footer, rewardTitle, rewardLine, jackpotTitle, jackpotLine, material, glowing, viewRewards, broadcastRewards, rewardAmount, rewardType, skullValue, rewards); + this.plugin.getLootboxRegister().register(lootbox); + } + + private List getRewards(FileConfiguration fileConfiguration) { + List rewards = new ArrayList<>(); + if (fileConfiguration.getConfigurationSection("rewards") != null) + fileConfiguration.getConfigurationSection("rewards").getKeys(false).forEach(key -> { + ItemStack itemStack = null; + try { + itemStack = ItemStackSerializer.deserialize(fileConfiguration.getConfigurationSection("rewards." + key).getString("item").replace("\r\n", "")); + } catch (IOException|ClassNotFoundException e) { + e.printStackTrace(); + } + Reward reward = new Reward(itemStack, fileConfiguration.getConfigurationSection("rewards." + key).getDouble("chance"), fileConfiguration.getConfigurationSection("rewards." + key).getBoolean("jackpot"), fileConfiguration.getConfigurationSection("rewards." + key).getString("special-name")); + rewards.add(reward); + }); + return rewards; + } + + public void addItem(Player player, String lootbox, double chance, boolean jackpot) { + try { + File file = new File(this.plugin.getDataFolder() + "/Lootboxes/" + lootbox + ".yml"); + if(file.exists()) { + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file); + String itemName = ChatColor.stripColor(player.getItemInHand().getItemMeta().getDisplayName()); + String toBase64 = ItemStackSerializer.serialize(player.getItemInHand()); + if(!yamlConfiguration.contains("rewards") || !yamlConfiguration.getConfigurationSection("rewards").getKeys(true).contains(itemName + player.getItemInHand().getAmount())) { + String name = itemName + player.getItemInHand().getAmount(); + yamlConfiguration.set("rewards." + name + ".item", toBase64); + yamlConfiguration.set("rewards." + name + ".chance", chance); + yamlConfiguration.set("rewards." + name + ".jackpot", jackpot); + yamlConfiguration.set("rewards." + name + ".special-name", "&f&l* " + player.getItemInHand().getAmount() + "x " + player.getItemInHand().getItemMeta().getDisplayName()); + yamlConfiguration.save(file); + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_ADDITEM.getMessage().replace("%lootbox%", lootbox).replace("%item%", player.getItemInHand().getItemMeta().getDisplayName())); + player.playSound(player.getLocation(), Sound.LEVEL_UP, 2.0F, 2.0F); + reloadLootbox(lootbox); + } else { + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_ITEM_ALREADY_IN.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void removeItemFromLootbox(Player player, ItemStack itemStack, String lootbox) { + try { + File file = new File(this.plugin.getDataFolder() + "/Lootboxes/" + lootbox + ".yml"); + if (file.exists()) { + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file); + String itemName = ChatColor.stripColor(itemStack.getItemMeta().getDisplayName()); + if (!yamlConfiguration.contains("rewards")) { + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_ITEM_NOT_FOUND.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + if (yamlConfiguration.getConfigurationSection("rewards").getKeys(true).contains(itemName + itemStack.getAmount())) { + yamlConfiguration.set("rewards." + itemName + itemStack.getAmount(), null); + yamlConfiguration.save(file); + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_REMOVE_ITEM.getMessage().replace("%lootbox%", lootbox).replace("%item%", itemStack.getItemMeta().getDisplayName())); + player.playSound(player.getLocation(), Sound.CHICKEN_EGG_POP, 2.0F, 2.0F); + reloadLootbox(lootbox); + } else { + player.sendMessage(Language.PREFIX.getMessage() + Language.LOOTBOX_ITEM_NOT_FOUND.getMessage().replace("%lootbox%", lootbox)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void giveLootbox(Player player, Lootbox lootbox, int amount) { + InventoryUtils.giveItemToPlayer(player, lootbox.createLootbox(amount)); + } + + public void giveLootbox(Player player, Lootbox lootbox) { + giveLootbox(player, lootbox, 1); + } + + public ItemStack getLootbox(Lootbox lootbox) { + return getLootbox(lootbox, 1); + } + + public ItemStack getLootbox(Lootbox lootbox, int amount) { + return lootbox.createLootbox(amount); + } + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/LootboxRegister.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/LootboxRegister.java new file mode 100644 index 0000000..baeb579 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/LootboxRegister.java @@ -0,0 +1,92 @@ +package net.crankedpvp.lootboxes.struct; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Maps; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import org.apache.commons.lang.Validate; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +public class LootboxRegister { + private final CrankedLootboxes plugin; + + @Getter + private final Map lootboxes; + + public LootboxRegister(CrankedLootboxes plugin) { + this.lootboxes = Maps.newConcurrentMap(); + this.plugin = plugin; + } + + public Map getSortedLootboxes() { + return sort(this.lootboxes); + } + + + public Map sort(Map map) { + List> list = new ArrayList<>(map.entrySet()); + list.sort(Map.Entry.comparingByKey()); + Collections.reverse(list); + Map result = new LinkedHashMap<>(); + for (int i = list.size() - 1; i >= 0; i--) { + Map.Entry entry = list.get(i); + result.put(entry.getKey(), entry.getValue()); + } + return result; + } + + @Getter @Setter + private Lootbox weeklyLootbox; + + + public void register(Lootbox lootbox) { + try { + this.lootboxes.put(lootbox.getId(), lootbox); + this.plugin.getLogger().info("Successfully registered lootbox: " + lootbox.getId()); + } catch (Exception var3) { + System.err.println("&8(&c!&8) Failed to register lootbox, " + lootbox.getId()); + } + } + + public boolean isLootbox(String name) { + return (getLootbox(name) != null); + } + + public Lootbox getLootbox(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + return this.lootboxes.get(name); + } + + public void clearLootboxMap() { + this.lootboxes.clear(); + } + + public void removeLootbox(String lootbox) { + this.lootboxes.remove(lootbox); + } + + public Collection getLootboxObjects() { + return Collections.unmodifiableCollection(this.lootboxes.values()); + } + + public List getLootboxesAsList() { + return new ArrayList<>(this.lootboxes.values()); + } + + public List getLootboxesAsIDs() { + return getLootboxesAsList().stream() + .map(Lootbox::getId) + .collect(Collectors.toList()); + } + + public Lootbox select(Collection lootboxCollection) { + return (lootboxCollection.size() > 0) ? ImmutableList.copyOf(lootboxCollection).get(ThreadLocalRandom.current().nextInt(lootboxCollection.size())) : null; + } + + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/Reward.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/Reward.java new file mode 100644 index 0000000..22849fb --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/Reward.java @@ -0,0 +1,17 @@ +package net.crankedpvp.lootboxes.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.bukkit.inventory.ItemStack; + +@AllArgsConstructor +@Getter +public class Reward { + + private final ItemStack itemStack; + private final double chance; + @Getter + private final boolean jackpot; + private final String specialName; + +} \ No newline at end of file diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/RewardType.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/RewardType.java new file mode 100644 index 0000000..f75a589 --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/struct/RewardType.java @@ -0,0 +1,7 @@ +package net.crankedpvp.lootboxes.struct; + +public enum RewardType { + BUNDLE, LUCKY_BLOCK, LOOTBOX, HYPEBOX + ; + +} diff --git a/Lootboxes/src/main/java/net/crankedpvp/lootboxes/utils/ItemStackSerializer.java b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/utils/ItemStackSerializer.java new file mode 100644 index 0000000..f3459db --- /dev/null +++ b/Lootboxes/src/main/java/net/crankedpvp/lootboxes/utils/ItemStackSerializer.java @@ -0,0 +1,30 @@ +package net.crankedpvp.lootboxes.utils; + +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class ItemStackSerializer { + public static ItemStack deserialize(String base64) throws IOException, ClassNotFoundException { + byte[] data = Base64Coder.decodeLines(base64); + ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); + BukkitObjectInputStream in = new BukkitObjectInputStream(bytesIn); + ItemStack itemStack = (ItemStack) in.readObject(); + in.close(); + return itemStack; + } + + public static String serialize(ItemStack itemStack) throws IOException { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + BukkitObjectOutputStream out = new BukkitObjectOutputStream(bytesOut); + out.writeObject(itemStack); + out.flush(); + out.close(); + return Base64Coder.encodeLines(bytesOut.toByteArray()); + } +} diff --git a/Lootboxes/src/main/resources/config.yml b/Lootboxes/src/main/resources/config.yml new file mode 100644 index 0000000..3082aa1 --- /dev/null +++ b/Lootboxes/src/main/resources/config.yml @@ -0,0 +1,15 @@ +LOOTBOX_MATERIAL: CHEST +LOOTBOX_HEADER: + - "&7Right-Click to receive some" + - "&7the following rewards..." + - "" + - "&4&l(!) &7Obtained from &cbuy.crankedpvp.org &7(/buy)" + - "" +LOOTBOX_FOOTER: + - "" + - "&c&lNOTE: &fThis is a physical item" + - "&fIt will not be refunded if lost" +LOOTBOX_REWARD_TITLE: "&f&lRandom Loot (&7%rewards% Items&f&l)" +LOOTBOX_REWARD_LINE: "&f&l* %amount%x %name%" +LOOTBOX_JACKPOT_TITLE: "&f&lJackpot Loot" +LOOTBOX_JACKPOT_LINE: " &f&l* %amount%x %name%" \ No newline at end of file diff --git a/Lootboxes/src/main/resources/language.yml b/Lootboxes/src/main/resources/language.yml new file mode 100644 index 0000000..721593c --- /dev/null +++ b/Lootboxes/src/main/resources/language.yml @@ -0,0 +1,18 @@ +PREFIX: "&cCranked&fPvP &8| " +FULL_INVENTORY: "&cYour inventory does not have enough slots to complete this action" +ALREADY_LOOTBOX: "&cA lootbox named %lootbox% is already registered" +CREATED_LOOTBOX: "&aYou have created the lootbox %lootbox%" +DELETED_LOOTBOX: "&aYou have deleted the lootbox %lootbox%" +LOOTBOX_INVALID: "&cThe lootbox with named %lootbox% could not be found" +LOOTBOX_DISABLED: "&aThe lootbox named %lootbox% has been disabled" +LOOTBOX_ENABLED: "&aThe lootbox named %lootbox% has been enabled" +RELOADED_ALL: "&aYou have reloaded ALL lootboxes" +RELOADED_SINGULAR: "&aYou have reloaded the %lootbox% lootbox" +LOOTBOX_RECEIVED: "&aYou have received the %lootbox% lootbox" +LOOTBOX_GIVEN: "&aYou have given the %lootbox% lootbox to %player%" +LOOTBOX_ADDITEM: "&aAdded %item%&r&a to %lootbox% lootbox" +LOOTBOX_ITEM_ALREADY_IN: "&cThis item is already in the %lootbox% lootbox" +LOOTBOX_ITEM_NOT_FOUND: "&cThis item is not in the %lootbox% lootbox" +LOOTBOX_REMOVE_ITEM: "&cDeleted %item%&r&c from %lootbox% lootbox" +LOOTBOX_OPENED: "&aYou have opened the %lootbox% lootbox" +PREVIEW_LOOT: "&aYou are now previewing the loot of the %lootbox% lootbox" diff --git a/Lootboxes/src/main/resources/plugin.yml b/Lootboxes/src/main/resources/plugin.yml new file mode 100644 index 0000000..05d6d0f --- /dev/null +++ b/Lootboxes/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedLootboxes +main: net.crankedpvp.lootboxes.CrankedLootboxes +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/LunarAPI/pom.xml b/LunarAPI/pom.xml new file mode 100644 index 0000000..c551076 --- /dev/null +++ b/LunarAPI/pom.xml @@ -0,0 +1,19 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + LunarAPI + + + 8 + 8 + + + \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LCPacketWrapper.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LCPacketWrapper.java new file mode 100644 index 0000000..0ac0435 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LCPacketWrapper.java @@ -0,0 +1,41 @@ +package com.lunarclient.bukkitapi; + +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import org.bukkit.entity.Player; + + +public interface LCPacketWrapper { + + /** + * The packet that will be sent to the player + * that is formed in the wrapper implementation. + * + * @return A LCPacket to send to the Lunar Client player + */ + T getPacket(); + + /** + * Send the wrapped packet to the player. + * + * @param player The online Lunar Client user to receive the packet. + */ + default void send(Player player) { + send(player, getPacket()); + } + + /** + * Send any LCPacket to a Lunar Client user. This is used in `send` method above. + * + * NOTE: This is intended to send only the wrapped packet, but can be used to + * send other packets. Although it technically can be done, in most cases it would + * be better to use {@link LunarClientAPI} to send a packet. + * + * @param player An online Lunar client user to receive the packet. + * @param packet The packet to send to the user. + */ + default void send(Player player, LCPacket packet) { + LunarClientAPI.getInstance().sendPacket(player, packet); + } + + +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LunarClientAPI.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LunarClientAPI.java new file mode 100644 index 0000000..9aad7e8 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LunarClientAPI.java @@ -0,0 +1,369 @@ +package com.lunarclient.bukkitapi; + +import com.lunarclient.bukkitapi.event.LCPacketReceivedEvent; +import com.lunarclient.bukkitapi.event.LCPacketSentEvent; +import com.lunarclient.bukkitapi.event.LCPlayerUnregisterEvent; +import com.lunarclient.bukkitapi.listener.LunarClientLoginListener; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.client.*; +import com.lunarclient.bukkitapi.nethandler.server.LCNetHandlerServer; +import com.lunarclient.bukkitapi.nethandler.shared.LCPacketWaypointAdd; +import com.lunarclient.bukkitapi.nethandler.shared.LCPacketWaypointRemove; +import com.lunarclient.bukkitapi.object.LCWaypoint; +import com.lunarclient.bukkitapi.object.StaffModule; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.util.Vector; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.stream.Collectors; + +public final class LunarClientAPI extends JavaPlugin implements Listener { + + public static final String MESSAGE_CHANNEL = "lunarclient:pm"; + + @Getter private static LunarClientAPI instance; + + @Setter private LCNetHandlerServer netHandlerServer = new LunarClientDefaultNetHandler(); + private final Set playersRunningLunarClient = Collections.newSetFromMap(new ConcurrentHashMap<>()); + private final Set playersNotRegistered = new HashSet<>(); + private final Map> packetQueue = new HashMap<>(); + private final Map> worldIdentifiers = new HashMap<>(); + + @Override + public void onEnable() { + instance = this; + + registerPluginChannel(MESSAGE_CHANNEL); + getServer().getPluginManager().registerEvents(new LunarClientLoginListener(this), this); + } + + /** + * Registers the bukkit plugin channel based on configuration of allowed players + * + * @param bukkitChannel The incoming plugin channel based on Minecraft Version. + */ + private void registerPluginChannel(String bukkitChannel) { + Messenger messenger = getServer().getMessenger(); + messenger.registerOutgoingPluginChannel(this, bukkitChannel); + messenger.registerIncomingPluginChannel(this, bukkitChannel, (channel, player, bytes) -> { + LCPacket packet = LCPacket.handle(bytes, player); + Bukkit.getPluginManager().callEvent(new LCPacketReceivedEvent(player, packet)); + packet.process(netHandlerServer); + }); + } + + /** + * Called when the player has been online for 2 seconds without + * sending any sort of registration stating they're on lunar client. + * + * This will remove all queued packets that we've saved, and prevent further packets + * from being stored for this player. + * + * Used in {@link LunarClientLoginListener}. Do not use unless you are certain you need this. + * + * @param player The player that has been online for at least 2 seconds. + */ + public void failPlayerRegister(Player player) { + playersNotRegistered.add(player.getUniqueId()); + packetQueue.remove(player.getUniqueId()); + } + + /** + * Register the player as a Lunar Client player based off of their + * bukkit plugin channel registration. + * + * NOTE: Do NOT use this as an anticheat method as this can be spoofed, + * or changed. This is intended for cosmetic use only! + * + * @param player The player registering as a Lunar Client user. + */ + public void registerPlayer(Player player) { + playersNotRegistered.remove(player.getUniqueId()); + playersRunningLunarClient.add(player.getUniqueId()); + if (packetQueue.containsKey(player.getUniqueId())) { + packetQueue.get(player.getUniqueId()).forEach(p -> sendPacket(player, p)); + + packetQueue.remove(player.getUniqueId()); + } + } + + /** + * Unregisters a player as a LunarClient player. This can be done by the client + * or by quitting. Either way we remove the player from the set, if they did not + * quit we don't want to remove them from NotRegistered players as we would + * continue to hold packets for them. + * + * If they did not quit, we don't want to hold packets for them forever so we + * add them to the not registered players set. + * + * @param player The player who has unregistered themself from the plugin channel. + * @param quit A {@link Boolean} value of weather the player quit or simply unregistered from the channel. + */ + public void unregisterPlayer(Player player, boolean quit) { + playersRunningLunarClient.remove(player.getUniqueId()); + if (quit) { + playersNotRegistered.remove(player.getUniqueId()); + } else { + playersNotRegistered.add(player.getUniqueId()); + getServer().getPluginManager().callEvent(new LCPlayerUnregisterEvent(player)); + } + } + + /** + * Checks if the player is currently running lunar client. + * @param player {@link Player} suspect of using Lunar Client. + * @return The {@link Boolean} value of weather the online player is currently using Lunar Client. + */ + public boolean isRunningLunarClient(Player player) { + return isRunningLunarClient(player.getUniqueId()); + } + + /** + * Checks if a user is currently running LunarClient on the server. + * @param playerUuid The ID of the suspect LunarClient user. + * + * @return The {@link Boolean} value of weather the player is currently running Lunar Client. + */ + public boolean isRunningLunarClient(UUID playerUuid) { + return playersRunningLunarClient.contains(playerUuid); + } + + /** + * Gets an immutable set of all the bukkit {@link Player} currently running lunar client. + * + * NOTE: This would only be ideal for displaying an object of the player, for computation + * it would probably be better to use the raw UUID of the players. + * + * @return An unmodifiableSet of the players currentl running lunar client. + */ + public Set getPlayersRunningLunarClient() { + return Collections.unmodifiableSet(playersRunningLunarClient.stream().map(Bukkit::getPlayer).collect(Collectors.toSet())); + } + + /** + * Force set a specific {@link StaffModule} for a specific player. + * Useful for enabling only a few {@link StaffModule} + * + * @param player The player receiving the staff modules. + * @param module The staff module to set to a state. + * @param state The new state of the StaffModule. + */ + public void setStaffModuleState(Player player, StaffModule module, boolean state) { + sendPacket(player, new LCPacketStaffModState(module.name(), state)); + } + + /** + * Gives a player ALL staff modules. + * Not recommended, a better path would to explicitly give a player each module. + * + * @param player The player to receive the enabled staff modules. + */ + public void giveAllStaffModules(Player player) { + for (StaffModule module : StaffModule.values()) { + setStaffModuleState(player, module, true); + } + } + + /** + * Disables ALL staff modules for a specific player + * regardless of if they are enabled. + * + * @param player The player receiving the new staff module state. + */ + public void disableAllStaffModules(Player player) { + for (StaffModule module : StaffModule.values()) { + setStaffModuleState(player, module, false); + } + } + + /** + * Sends a validated teammate object to the player. + * Tells the player of all its known team mates, ensure they're both online and in the world. + * + * @param player The player to receive the team mates + * @param packet The teammates to send to the player. + */ + public void sendTeammates(Player player, LCPacketTeammates packet) { + validatePlayers(player, packet); + sendPacket(player, packet); + } + + /** + * Validate teammates for the player (sendingTo). + * Ensures the teammates are online and in the same world before sending the location. + * Used above in sendTeammates. + * + * @param sendingTo The player we're sending teammates to. + * @param packet The teammates packet to verify. + */ + private void validatePlayers(Player sendingTo, LCPacketTeammates packet) { + packet.getPlayers().entrySet().removeIf(entry -> Bukkit.getPlayer(entry.getKey()) != null && !Bukkit.getPlayer(entry.getKey()).getWorld().equals(sendingTo.getWorld())); + } + + /** + * Create a hologram for a player on the server. + * + * @param player The observer of the new hologram. + * @param id The randomly generated UUID for the hologram. This will need to be saved for other hologram actions. + * @param position The location (x, y, z) of where the hologram will be placed in the world. + * @param lines The lines of the hologram to be sent to the player. + */ + public void addHologram(Player player, UUID id, Vector position, String[] lines) { + sendPacket(player, new LCPacketHologram(id, position.getX(), position.getY(), position.getZ(), Arrays.asList(lines))); + } + + /** + * Update the lines of a previously added hologram for a specific player. + * + * @param player The observer of the new hologram lines. + * @param id The ID of the previously placed hologram. + * @param lines The new lines to show to the player. + */ + public void updateHologram(Player player, UUID id, String[] lines) { + sendPacket(player, new LCPacketHologramUpdate(id, Arrays.asList(lines))); + } + + /** + * Remove a previously set hologram for a specific player. + * + * @param player The player to remove the hologram for. + * @param id The ID of the previously created hologram. + */ + public void removeHologram(Player player, UUID id) { + sendPacket(player, new LCPacketHologramRemove(id)); + } + + /** + * Override the normal (bukkit) nametag with lunar client nametags. + * This supports multiple lines, so index 0 will be bottom of the nametags. + * + * @param target The player whos nametag will be affected for the viewer. + * @param nametag The list of nametags that will be sent to the viewer. Supports color codes. + * @param viewer The observer who will see the targets nametag as a lunar client nametag. + */ + public void overrideNametag(Player target, List nametag, Player viewer) { + sendPacket(viewer, new LCPacketNametagsOverride(target.getUniqueId(), nametag)); + } + + /** + * Reset anything done to the nametag. + * This will reset hideNametag or any + * other action done to the nametag. + * + * @param target The player's nametag that will be reset for the viewer. + * @param viewer The observer who will see the targets nametag as normal (bukkit). + */ + public void resetNametag(Player target, Player viewer) { + sendPacket(viewer, new LCPacketNametagsOverride(target.getUniqueId(), null)); + } + + /** + * Hide the target's username from the viewer. + * + * + * @param target This player's nametag will be hidden from the viewer. + * @param viewer The observer who will hide the targets nametag. + */ + public void hideNametag(Player target, Player viewer) { + sendPacket(viewer, new LCPacketNametagsOverride(target.getUniqueId(), Collections.emptyList())); + } + + /** + * Gets the world identifier weather that is custom or + * the worlds generated Id for sending waypoints to the client. + * + * @param world The world to get the identifier for + * @return {@link String} of the set name of the world, or default to the worlds unique id. + */ + public String getWorldIdentifier(World world) { + String worldIdentifier = world.getUID().toString(); + + if (worldIdentifiers.containsKey(world.getUID())) { + worldIdentifier = worldIdentifiers.get(world.getUID()).apply(world); + } + + return worldIdentifier; + } + + /** + * Registers a custom name for the world to be identified as on the client. + * + * Not required, if not set it will default to the unquie id of the world. + * + * @param world The bukkit object for the world. + * @param identifier The new function identifier. + */ + public void registerWorldIdentifier(World world, Function identifier) { + worldIdentifiers.put(world.getUID(), identifier); + } + + /** + * Send a waypoint to a lunarclient player. + * + * Note: You will likely need to persist this object in order to remove it later. + * + * @param player A player running lunar client. + * @param waypoint A new waypoint object to send to the player. + */ + public void sendWaypoint(Player player, LCWaypoint waypoint) { + sendPacket(player, new LCPacketWaypointAdd(waypoint.getName(), waypoint.getWorld(), waypoint.getColor(), waypoint.getX(), waypoint.getY(), waypoint.getZ(), waypoint.isForced(), waypoint.isVisible())); + } + + /** + * Remove a waypoint that the server sent from a player. + * + * @param player A player running lunar client. + * @param waypoint A waypoint object that the server has previously sent. + */ + public void removeWaypoint(Player player, LCWaypoint waypoint) { + sendPacket(player, new LCPacketWaypointRemove(waypoint.getName(), waypoint.getWorld())); + } + + /** + * The most basic component of the Lunar Client API used + * to send packets to the Lunar Client player. + * Implementation with direct method calls is not recommended, + * and will likely be very brittle in regards to functionality. + * + * sendPacket will either send the packet immediately to the Lunar Client player + * or if for some reason there is a delay in the connection, it will queue the packet for + * consumption at a later date, when the player registers. + * + * @param player The bukkit representation of the {@link Player} to receive the packet. + * @param packet The Lunar Client packet that should be sent to the Lunar Client player. + * @return {@link Boolean} value of weather the packet was sent. + */ + public boolean sendPacket(Player player, LCPacket packet) { + UUID playerId = player.getUniqueId(); + if (isRunningLunarClient(playerId)) { + String channel = MESSAGE_CHANNEL; + player.sendPluginMessage(this, channel, LCPacket.getPacketData(packet)); + Bukkit.getPluginManager().callEvent(new LCPacketSentEvent(player, packet)); + return true; + } + + // If the player hasn't been on for 2 seconds, but also + // hasn't registered we hold on to hope they are just lagging + // and so we save packets for them until they are proven not + // lunar client players. + // Either way, the packet failed to send (this time). + + if (!playersNotRegistered.contains(playerId)) { + if (!packetQueue.containsKey(playerId)) { + packetQueue.put(playerId, new ArrayList<>()); + } + packetQueue.get(playerId).add(packet); + } + return false; + } + +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LunarClientDefaultNetHandler.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LunarClientDefaultNetHandler.java new file mode 100644 index 0000000..468ab51 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/LunarClientDefaultNetHandler.java @@ -0,0 +1,93 @@ +package com.lunarclient.bukkitapi; + +import com.lunarclient.bukkitapi.nethandler.client.LCPacketClientVoice; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketVoiceMute; +import com.lunarclient.bukkitapi.nethandler.client.obj.ServerRule; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketVoiceChannelSwitch; +import com.lunarclient.bukkitapi.nethandler.server.LCNetHandlerServer; +import com.lunarclient.bukkitapi.nethandler.server.LCPacketStaffModStatus; +import com.lunarclient.bukkitapi.nethandler.shared.LCPacketEmoteBroadcast; +import com.lunarclient.bukkitapi.nethandler.shared.LCPacketWaypointAdd; +import com.lunarclient.bukkitapi.nethandler.shared.LCPacketWaypointRemove; + +/** + * An empty implementation of the server nethandler. + */ +public class LunarClientDefaultNetHandler implements LCNetHandlerServer { + + /** + * Called when a player changes their staff mode state. + * Not currently implemented. + * @param lcPacketStaffModStatus All the status of the players staff mode. + */ + @Override + public void handleStaffModStatus(LCPacketStaffModStatus lcPacketStaffModStatus) { + + } + + /** + * Called when the client adds or edits a waypoint when the server controls waypoints. + * A waypoint that is edited will call handleRemoveWaypoint before creating the new waypoint. + * See {@link ServerRule} for how to control waypoints. + * + * @param lcPacketWaypointAdd The waypoint added by the client. + */ + @Override + public void handleAddWaypoint(LCPacketWaypointAdd lcPacketWaypointAdd) { + + } + + /** + * Called when a player removes a waypoint. See above (handleAddWaypoint) for more detail. + * @param lcPacketWaypointRemove The waypoint name and world removed by the player. + */ + @Override + public void handleRemoveWaypoint(LCPacketWaypointRemove lcPacketWaypointRemove) { + + } + + // Do not implement these, they do nothing and will not work. + + + /** + * Deprecated entirely from a time when Emotes went through the server. + */ + @Override + @Deprecated + public void handleEmote(LCPacketEmoteBroadcast lcPacketEmoteBroadcast) { + // DO NOT ATTEMPT TO IMPLEMENT + } + + /** + * Deprecated entirely, may return once a solution for voice is found. + * + * Not currently a work in progress. + */ + @Override + @Deprecated + public void handleVoice(LCPacketClientVoice lcPacketClientVoice) { + // DO NOT ATTEMPT TO IMPLEMENT + } + + /** + * Deprecated entirely, may return once a solution for voice is found. + * + * Not currently a work in progress. + */ + @Override + @Deprecated + public void handleVoiceMute(LCPacketVoiceMute lcPacketVoiceMute) { + // DO NOT ATTEMPT TO IMPLEMENT + } + + /** + * Deprecated entirely, may return once a solution for voice is found. + * + * Not currently a work in progress. + */ + @Override + @Deprecated + public void handleVoiceChannelSwitch(LCPacketVoiceChannelSwitch lcPacketVoiceChannelSwitch) { + // DO NOT ATTEMPT TO IMPLEMENT + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/LCCooldown.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/LCCooldown.java new file mode 100644 index 0000000..d895e7a --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/LCCooldown.java @@ -0,0 +1,69 @@ +package com.lunarclient.bukkitapi.cooldown; + +import com.lunarclient.bukkitapi.nethandler.client.LCPacketCooldown; +import com.google.common.base.Preconditions; +import com.lunarclient.bukkitapi.LCPacketWrapper; +import lombok.Data; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +import java.util.concurrent.TimeUnit; + +@Data +public class LCCooldown implements LCPacketWrapper { + + private final String name; + private final long millis; + private final Material itemId; + // The packet that will be sent to the Lunar Client player + // Because of @Data, we don't need a getter. + private final LCPacketCooldown packet; + + /** + * Used to create a persisting cooldown that can be sent to many players. + * + * @param name A unique name that is not null + * @param millis The duration for the cooldown in milliseconds, that is greater (or equal to reset) to 0. + * @param itemId The icon that will be displayed in Lunar Client. + */ + public LCCooldown(String name, long millis, Material itemId) { + Preconditions.checkArgument(millis > 0, "Cooldown must have a valid time > 0."); + this.name = Preconditions.checkNotNull(name, "Cooldown Name cannot be null."); + this.millis = millis; + this.itemId = Preconditions.checkNotNull(itemId, "Cooldown Icon cannot be null."); + packet = new LCPacketCooldown(name, millis, itemId.getId()); + } + + /** + * Simply creates a LCCooldown with seconds instead of milliseconds. + * + * @param name A unique name that is not null + * @param seconds the duration for the cooldown in seconds, that is greater (or equal to reset) to 0. + * @param item The icon that will be displayed in Lunar Client. + */ + public LCCooldown(String name, int seconds, Material item) { + this(name, seconds * 1000L, item); + } + + /** + * Simply creates a LCCooldown with a variable amount of time + * + * @param name A unique name that is not null + * @param time A duration greater than 0 milliseconds. + * @param unit A unit of measurement to put the cooldown in + * @param item The icon that will be displayed in Lunar Client. + */ + public LCCooldown(String name, int time, TimeUnit unit, Material item) { + this(name, unit.toMillis(time), item); + } + + + /** + * Clear the cooldown from a player before it naturally expires. + * + * @param player The player to clear the cooldown for. + */ + public void clear(Player player) { + send(player, new LCPacketCooldown(name, 0, itemId.getId())); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/LunarClientAPICooldown.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/LunarClientAPICooldown.java new file mode 100644 index 0000000..2dd2291 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/LunarClientAPICooldown.java @@ -0,0 +1,56 @@ +package com.lunarclient.bukkitapi.cooldown; + +import lombok.experimental.UtilityClass; +import org.bukkit.entity.Player; + +import java.util.*; + +@UtilityClass +public class LunarClientAPICooldown { + + private final Map registeredCooldowns = new HashMap<>(); + + /** + * Used to register a persisting cooldown. + * Ideally 1 {@link LCCooldown} will be created for each task. + * Create the {@link LCCooldown} once, register it and then send it to each player. + * + * @param cooldown The cooldown to register + */ + public void registerCooldown(LCCooldown cooldown) { + registeredCooldowns.put(cooldown.getName().toLowerCase(), cooldown); + } + + /** + * Used to unregister a persisting cooldown. + * If a cooldown will no longer be used or in shutdown, unregistering is a good idea. + * + * @param cooldown The cooldown to register + */ + public void unregisterCooldown(LCCooldown cooldown) { + registeredCooldowns.remove(cooldown.getName().toLowerCase()); + } + + /** + * Sends a cooldown to a Lunar Client player that has previously been registered. + * This could be used instead of passing around a {@link LCCooldown} instance. + * + * @param player The player to send a cooldown to + * @param cooldownName The name of the {@link LCCooldown} that is sent. + */ + public void sendCooldown(Player player, String cooldownName) { + String cooldownId = cooldownName.toLowerCase(); + if (!registeredCooldowns.containsKey(cooldownId)) { + throw new IllegalStateException("Attempted to send a cooldown that isn't registered [" + cooldownName + "]"); + } + registeredCooldowns.get(cooldownId).send(player); + } + + public void clearCooldown(Player player, String cooldownName) { + String cooldownId = cooldownName.toLowerCase(); + if (!registeredCooldowns.containsKey(cooldownId)) { + throw new IllegalStateException("Attempted to send a cooldown that isn't registered [" + cooldownName + "]"); + } + registeredCooldowns.get(cooldownId).clear(player); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/README.md b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/README.md new file mode 100644 index 0000000..9979390 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/cooldown/README.md @@ -0,0 +1,89 @@ +# Lunar Client Cooldown API + +`The object with creating the cooldown API is to provide a really easy solution for creating cooldowns in Lunar Client.` + +`Below are a few examples of how this can be implemented and what each implementation works well for.` + +``Note that while the API provides an easy path for most use cases, if your use case requires something different you can always send the packet using LunarClientAPI.`` + +## Examples: + +--- +### Example 1 - Static Timers. +```java + /** + * Called when your plugin loads, used to register a static + * cooldown, where the time doesn't change. + * + * This will allow you to reuse the object without keeping track of it yourself. + */ + private void loadPlugin() { + LunarClientAPICooldown.registerCooldown(new LCCooldown("CombatTag", 30, Material.DIAMOND_SWORD)); + } + + /** + * Called when a player attacks another player in your code. + * This will apply our previously registered 30 second timer, with a diamond sword image. + * + * @param attacker One of the players to receive the 30 second timer. + * @param victim One of the players to receive the 30 second timer. + */ + private void attackPlayer(Player attacker, Player victim) { + LunarClientAPICooldown.sendCooldown(attacker.getPlayer(), "CombatTag"); + LunarClientAPICooldown.sendCooldown(victim.getPlayer(), "CombatTag"); + } + + /** + * Called when a player dies (or some other action) in your code. + * This will remove our previously applied 30 second timer if it exists. + * + * @param player The player to clear the timer for. + */ + public void playerDeath(Player player) { + LunarClientAPICooldown.clearCooldown(player, "CombatTag"); + } +``` + +--- + +### Example 2 - Dynamic Teleport Timers + +```java + /** + * This is the least performant option, but sometimes a good option. + * This will create a NON-TRACKED {@link LCCooldown} that will send to a player. + * + * This is best used if you need a one-off cooldown that has a dynamic time or icon, meaning + * that it will change everytime. In this example, we have a player teleporting with a variable + * amount of time with the EnderPearl icon. + * + * @param player The player to receive the timer. + * @param variableTime The variable amount of time that should be applied to the cooldown. + */ + private void teleportTimer(Player player, int variableTime) { + new LCCooldown("Teleport", variableTime, Material.ENDER_PEARL).send(player); + } +``` + +--- + +### Example 3 - Limited Objects with Dynamic Timers + + +```java + /** + * This is the most performant option, but will require you to keep the LCPacketCooldown object yourself. + * If you don't understand what is going on in this, or you do not know how to persist and pass the object + * properly, this probably isn't the best solution for you. + * + * This will create just a packet object, and send it to the player(s). This is best suited for extremely + * performant servers, or servers that have a need for dynamic timers or icons and don't want the overhead of + * 2 objects per cooldown. + * + * @param player The player to send the cooldown. + * @param variableTime The amount of time (in seconds) to send in the cooldown. + */ + private void teleportTimerLimitedObjects(Player player, int variableTime) { + LunarClientAPI.getInstance().sendPacket(player, new LCPacketCooldown("Teleport", variableTime * 1000L, Material.ENDER_PEARL.getId())); + } +``` diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPacketReceivedEvent.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPacketReceivedEvent.java new file mode 100644 index 0000000..124e612 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPacketReceivedEvent.java @@ -0,0 +1,32 @@ +package com.lunarclient.bukkitapi.event; + +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public final class LCPacketReceivedEvent extends PlayerEvent { + + @Getter private static HandlerList handlerList = new HandlerList(); + + @Getter private final LCPacket packet; + + /** + * Called when the player sends a {@link LCPacket} + * to the server from the client. + * + * @param player The LunarClient player sending the packet. + * @param packet The incoming packet from the client. + */ + public LCPacketReceivedEvent(Player player, LCPacket packet) { + super(player); + this.packet = packet; + } + + @Override + public HandlerList getHandlers() { + return handlerList; + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPacketSentEvent.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPacketSentEvent.java new file mode 100644 index 0000000..58b64f5 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPacketSentEvent.java @@ -0,0 +1,33 @@ +package com.lunarclient.bukkitapi.event; + +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public final class LCPacketSentEvent extends PlayerEvent { + + @Getter private static HandlerList handlerList = new HandlerList(); + + @Getter private final LCPacket packet; + + /** + * Called when the server sends a {@link LCPacket} to the Lunar Client user. + * There is a chance the player does not receive the packet even if this event is + * called. There is no way to be 100% certain the client has received and registered the packet. + * + * @param player The player receiving the incoming packet. + * @param packet The {@link LCPacket} the server has sent to the Lunar Client user. + */ + public LCPacketSentEvent(Player player, LCPacket packet) { + super(player); + this.packet = packet; + } + + @Override + public HandlerList getHandlers() { + return handlerList; + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPlayerRegisterEvent.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPlayerRegisterEvent.java new file mode 100644 index 0000000..cf9960b --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPlayerRegisterEvent.java @@ -0,0 +1,27 @@ +package com.lunarclient.bukkitapi.event; + +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + + +public final class LCPlayerRegisterEvent extends PlayerEvent { + + @Getter private static HandlerList handlerList = new HandlerList(); + + /** + * Called whenever a player registers the LC plugin channel + * + * @param player The player registering as a Lunar Client user. + */ + public LCPlayerRegisterEvent(Player player) { + super(player); + } + + @Override + public HandlerList getHandlers() { + return handlerList; + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPlayerUnregisterEvent.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPlayerUnregisterEvent.java new file mode 100644 index 0000000..f6fbb12 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/event/LCPlayerUnregisterEvent.java @@ -0,0 +1,26 @@ +package com.lunarclient.bukkitapi.event; + +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public final class LCPlayerUnregisterEvent extends PlayerEvent { + + @Getter private static HandlerList handlerList = new HandlerList(); + + /** + * Called whenever a player unregisters the LC plugin channel + * + * @param player The player who has unregistered from the plugin channel. + */ + public LCPlayerUnregisterEvent(Player player) { + super(player); + } + + @Override + public HandlerList getHandlers() { + return handlerList; + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/listener/LunarClientLoginListener.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/listener/LunarClientLoginListener.java new file mode 100644 index 0000000..bed0609 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/listener/LunarClientLoginListener.java @@ -0,0 +1,65 @@ +package com.lunarclient.bukkitapi.listener; + +import com.lunarclient.bukkitapi.nethandler.client.LCPacketUpdateWorld; +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.lunarclient.bukkitapi.event.LCPlayerRegisterEvent; +import lombok.RequiredArgsConstructor; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.*; + +@RequiredArgsConstructor +public class LunarClientLoginListener implements Listener { + + private final LunarClientAPI lunarClientAPI; + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + + Bukkit.getScheduler().runTaskLater(lunarClientAPI, () -> { + if (!lunarClientAPI.isRunningLunarClient(player)) { + lunarClientAPI.failPlayerRegister(player); + } + }, 2 * 20L); + } + + @EventHandler + public void onRegister(PlayerRegisterChannelEvent event) { + if (!event.getChannel().equalsIgnoreCase(LunarClientAPI.MESSAGE_CHANNEL)) { + return; + } + Player player = event.getPlayer(); + + lunarClientAPI.registerPlayer(player); + + lunarClientAPI.getServer().getPluginManager().callEvent(new LCPlayerRegisterEvent(event.getPlayer())); + updateWorld(event.getPlayer()); + } + + @EventHandler + public void onUnregister(PlayerUnregisterChannelEvent event) { + if (event.getChannel().equalsIgnoreCase(LunarClientAPI.MESSAGE_CHANNEL)) { + lunarClientAPI.unregisterPlayer(event.getPlayer(), false); + } + } + + @EventHandler + public void onUnregister(PlayerQuitEvent event) { + lunarClientAPI.unregisterPlayer(event.getPlayer(), true); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onWorldChange(PlayerChangedWorldEvent event) { + updateWorld(event.getPlayer()); + } + + private void updateWorld(Player player) { + String worldIdentifier = lunarClientAPI.getWorldIdentifier(player.getWorld()); + + lunarClientAPI.sendPacket(player, new LCPacketUpdateWorld(worldIdentifier)); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/ByteBufWrapper.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/ByteBufWrapper.java new file mode 100644 index 0000000..f0c6252 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/ByteBufWrapper.java @@ -0,0 +1,74 @@ +package com.lunarclient.bukkitapi.nethandler; + +import io.netty.buffer.ByteBuf; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +public final class ByteBufWrapper { + + private final ByteBuf buf; + + public ByteBufWrapper(ByteBuf buf) { + this.buf = buf; + } + + public void writeVarInt(int b) { + while ((b & -128) != 0) { + this.buf.writeByte(b & 127 | 128); + b >>>= 7; + } + + this.buf.writeByte(b); + } + + public int readVarInt() { + int i = 0; + int chunk = 0; + byte b; + + do { + b = this.buf.readByte(); + i |= (b & 127) << chunk++ * 7; + + if (chunk > 5) { + throw new RuntimeException("VarInt too big"); + } + } while ((b & 128) == 128); + + return i; + } + + public void writeString(String s) { + byte[] arr = s.getBytes(StandardCharsets.UTF_8); + + this.writeVarInt(arr.length); + this.buf.writeBytes(arr); + } + + public String readString() { + int len = readVarInt(); + + byte[] buffer = new byte[len]; + buf.readBytes(buffer); + + return new String(buffer, StandardCharsets.UTF_8); + } + + public void writeUUID(UUID uuid) { + this.buf.writeLong(uuid.getMostSignificantBits()); + this.buf.writeLong(uuid.getLeastSignificantBits()); + } + + public UUID readUUID() { + long mostSigBits = this.buf.readLong(); + long leastSigBits = this.buf.readLong(); + + return new UUID(mostSigBits, leastSigBits); + } + + public ByteBuf buf() { + return buf; + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/LCPacket.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/LCPacket.java new file mode 100644 index 0000000..65b7405 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/LCPacket.java @@ -0,0 +1,154 @@ +package com.lunarclient.bukkitapi.nethandler; + +import com.lunarclient.bukkitapi.nethandler.client.*; +import com.lunarclient.bukkitapi.nethandler.server.LCPacketVoice; +import com.lunarclient.bukkitapi.nethandler.server.LCPacketVoiceChannel; +import com.lunarclient.bukkitapi.nethandler.server.LCPacketVoiceChannelRemove; +import com.lunarclient.bukkitapi.nethandler.server.LCPacketVoiceChannelUpdate; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import com.lunarclient.bukkitapi.nethandler.shared.LCPacketEmoteBroadcast; +import com.lunarclient.bukkitapi.nethandler.shared.LCPacketWaypointAdd; +import com.lunarclient.bukkitapi.nethandler.shared.LCPacketWaypointRemove; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public abstract class LCPacket { + + private static final Map classToId = new HashMap<>(); + private static final Map idToClass = new HashMap<>(); + + static { + // server + addPacket(0, LCPacketClientVoice.class); + addPacket(16, LCPacketVoice.class); + addPacket(1, LCPacketVoiceChannelSwitch.class); + addPacket(2, LCPacketVoiceMute.class); + + addPacket(17, LCPacketVoiceChannel.class); + addPacket(18, LCPacketVoiceChannelRemove.class); + addPacket(19, LCPacketVoiceChannelUpdate.class); + + // client + addPacket(3, LCPacketCooldown.class); + addPacket(4, LCPacketHologram.class); + addPacket(6, LCPacketHologramRemove.class); + addPacket(5, LCPacketHologramUpdate.class); + addPacket(7, LCPacketNametagsOverride.class); + addPacket(8, LCPacketNametagsUpdate.class); + addPacket(9, LCPacketNotification.class); + addPacket(10, LCPacketServerRule.class); + addPacket(11, LCPacketServerUpdate.class); + addPacket(12, LCPacketStaffModState.class); + addPacket(13, LCPacketTeammates.class); + addPacket(14, LCPacketTitle.class); + addPacket(15, LCPacketUpdateWorld.class); + addPacket(20, LCPacketWorldBorder.class); + addPacket(21, LCPacketWorldBorderRemove.class); + addPacket(22, LCPacketWorldBorderUpdate.class); + addPacket(25, LCPacketGhost.class); + addPacket(28, LCPacketBossBar.class); + addPacket(29, LCPacketWorldBorderCreateNew.class); + addPacket(30, LCPacketWorldBorderUpdateNew.class); + addPacket(31, LCPacketModSettings.class); + + // shared + addPacket(26, LCPacketEmoteBroadcast.class); + addPacket(23, LCPacketWaypointAdd.class); + addPacket(24, LCPacketWaypointRemove.class); + } + + private Object attachment; + + public static LCPacket handle(byte[] data) { + return handle(data, null); + } + + public static LCPacket handle(byte[] data, Object attachment) { + ByteBufWrapper wrappedBuffer = new ByteBufWrapper(Unpooled.wrappedBuffer(data)); + + int packetId = wrappedBuffer.readVarInt(); + Class packetClass = idToClass.get(packetId); + + if (packetClass != null) { + try { + LCPacket packet = (LCPacket) packetClass.newInstance(); + + packet.attach(attachment); + packet.read(wrappedBuffer); + + return packet; + } catch (IOException | InstantiationException | IllegalAccessException ex) { + ex.printStackTrace(); + } + } + + return null; + } + + public static byte[] getPacketData(LCPacket packet) { + return getPacketBuf(packet).array(); + } + + public static ByteBuf getPacketBuf(LCPacket packet) { + ByteBufWrapper wrappedBuffer = new ByteBufWrapper(Unpooled.buffer()); + wrappedBuffer.writeVarInt(classToId.get(packet.getClass())); + + try { + packet.write(wrappedBuffer); + } catch (IOException ex) { + ex.printStackTrace(); + } + + return wrappedBuffer.buf(); + } + + private static void addPacket(int id, Class clazz) { + if (classToId.containsKey(clazz)) { + throw new IllegalArgumentException("Duplicate packet class (" + clazz.getSimpleName() + "), already used by " + classToId.get(clazz)); + } else if (idToClass.containsKey(id)) { + throw new IllegalArgumentException("Duplicate packet ID (" + id + "), already used by " + idToClass.get(id).getSimpleName()); + } + + classToId.put(clazz, id); + idToClass.put(id, clazz); + } + + public abstract void write(ByteBufWrapper buf) throws IOException; + + public abstract void read(ByteBufWrapper buf) throws IOException; + + public abstract void process(LCNetHandler handler); + + public void attach(T obj) { + this.attachment = obj; + } + + @SuppressWarnings("unchecked") + public T getAttachment() { + return (T) attachment; + } + + protected void writeBlob(ByteBufWrapper b, byte[] bytes) { + b.buf().writeShort(bytes.length); + b.buf().writeBytes(bytes); + } + + protected byte[] readBlob(ByteBufWrapper b) { + short key = b.buf().readShort(); + + if (key < 0) { + System.out.println("Key was smaller than nothing! Weird key!"); + } else { + byte[] blob = new byte[key]; + b.buf().readBytes(blob); + return blob; + } + + return null; + } + +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/ModSettingsAdapter.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/ModSettingsAdapter.java new file mode 100644 index 0000000..acbed6a --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/ModSettingsAdapter.java @@ -0,0 +1,84 @@ +package com.lunarclient.bukkitapi.nethandler; + +import com.lunarclient.bukkitapi.nethandler.client.obj.ModSettings; +import com.google.gson.*; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +public class ModSettingsAdapter implements JsonDeserializer, JsonSerializer { + @Override + public ModSettings deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + ModSettings settings = new ModSettings(); + if (!jsonElement.isJsonObject()) { + return settings; + } + + JsonObject object = jsonElement.getAsJsonObject(); + for (Map.Entry entry : object.entrySet()) { + if (!entry.getValue().isJsonObject()) { + continue; + } + JsonObject modSettingObject = entry.getValue().getAsJsonObject(); + + settings.getModSettings().put(entry.getKey(), deserializeModSetting(modSettingObject)); + } + return settings; + } + + @Override + public JsonElement serialize(ModSettings modSettings, Type type, JsonSerializationContext jsonSerializationContext) { + JsonObject object = new JsonObject(); + for (Map.Entry entry : modSettings.getModSettings().entrySet()) { + object.add(entry.getKey(), serializeModSetting(entry.getValue())); + } + return object; + } + + private JsonObject serializeModSetting(ModSettings.ModSetting setting) { + JsonObject object = new JsonObject(); + JsonObject properties = new JsonObject(); + object.addProperty("enabled", setting.isEnabled()); + for (Map.Entry entry : setting.getProperties().entrySet()) { + + JsonPrimitive primitive; + if (entry.getValue() instanceof Boolean) { + primitive = new JsonPrimitive((Boolean) entry.getValue()); + } else if (entry.getValue() instanceof String) { + primitive = new JsonPrimitive((String) entry.getValue()); + } else if (entry.getValue() instanceof Number) { + primitive = new JsonPrimitive((Number) entry.getValue()); + } else { + continue; + } + properties.add(entry.getKey(), primitive); + } + object.add("properties", properties); + return object; + } + + private ModSettings.ModSetting deserializeModSetting(JsonObject object) { + JsonObject propertiesObject = object.get("properties").getAsJsonObject(); + Map properties = new HashMap<>(); + for (Map.Entry entry : propertiesObject.entrySet()) { + if (!entry.getValue().isJsonPrimitive()) { + continue; + } + JsonPrimitive primitive = entry.getValue().getAsJsonPrimitive(); + Object toSet; + if (primitive.isString()) { + toSet = primitive.getAsString(); + } else if (primitive.isNumber()) { + toSet = primitive.getAsNumber(); + } else if (primitive.isBoolean()) { + toSet = primitive.getAsBoolean(); + } else { + continue; + } + properties.put(entry.getKey(), toSet); + } + return new ModSettings.ModSetting(object.get("enabled").getAsBoolean(), properties); + } + +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCNetHandlerClient.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCNetHandlerClient.java new file mode 100644 index 0000000..1058692 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCNetHandlerClient.java @@ -0,0 +1,36 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.server.LCPacketVoice; +import com.lunarclient.bukkitapi.nethandler.server.LCPacketVoiceChannel; +import com.lunarclient.bukkitapi.nethandler.server.LCPacketVoiceChannelRemove; +import com.lunarclient.bukkitapi.nethandler.server.LCPacketVoiceChannelUpdate; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; + +public interface LCNetHandlerClient extends LCNetHandler { + + void handleBossBar(LCPacketBossBar packet); + void handleCooldown(LCPacketCooldown packet); + void handleGhost(LCPacketGhost packet); + void handleAddHologram(LCPacketHologram packet); + void handleRemoveHologram(LCPacketHologramRemove packet); + void handleUpdateHologram(LCPacketHologramUpdate packet); + void handleOverrideNametags(LCPacketNametagsOverride packet); + void handleNametagsUpdate(LCPacketNametagsUpdate packet); + void handleNotification(LCPacketNotification packet); + void handleServerRule(LCPacketServerRule packet); + void handleServerUpdate(LCPacketServerUpdate packet); + void handleStaffModState(LCPacketStaffModState packet); + void handleTeammates(LCPacketTeammates packet); + void handleTitle(LCPacketTitle packet); + void handleUpdateWorld(LCPacketUpdateWorld packet); + void handleWorldBorder(LCPacketWorldBorder packet); + void handleWorldBorderCreateNew(LCPacketWorldBorderCreateNew packet); + void handleWorldBorderRemove(LCPacketWorldBorderRemove packet); + void handleWorldBorderUpdate(LCPacketWorldBorderUpdate packet); + void handleWorldBorderUpdateNew(LCPacketWorldBorderUpdateNew packet); + void handleVoice(LCPacketVoice packet); + void handleVoiceChannels(LCPacketVoiceChannel packet); + void handleVoiceChannelUpdate(LCPacketVoiceChannelUpdate packet); + void handleVoiceChannelDelete(LCPacketVoiceChannelRemove packet); + void handleModSettings(LCPacketModSettings packetModSettings); +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketBossBar.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketBossBar.java new file mode 100644 index 0000000..03dcc32 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketBossBar.java @@ -0,0 +1,49 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketBossBar extends LCPacket { + + @Getter private int action; + @Getter private String text; + @Getter private float health; + + public LCPacketBossBar() {} + + public LCPacketBossBar(int action, String text, float health) { + this.action = action; + this.text = text; + this.health = health; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeVarInt(action); + + if (action == 0) { + buf.writeString(text); + buf.buf().writeFloat(health); + } + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.action = buf.readVarInt(); + + if (action == 0) { + text = buf.readString(); + health = buf.buf().readFloat(); + } + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleBossBar(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketClientVoice.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketClientVoice.java new file mode 100644 index 0000000..00466e3 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketClientVoice.java @@ -0,0 +1,36 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.server.LCNetHandlerServer; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketClientVoice extends LCPacket { + + @Getter private byte[] data; + + public LCPacketClientVoice() { + } + + public LCPacketClientVoice(byte[] data) { + this.data = data; + } + + @Override + public void write(ByteBufWrapper b) throws IOException { + writeBlob(b, this.data); + } + + @Override + public void read(ByteBufWrapper b) throws IOException { + this.data = readBlob(b); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerServer) handler).handleVoice(this); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketCooldown.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketCooldown.java new file mode 100644 index 0000000..a12d419 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketCooldown.java @@ -0,0 +1,43 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketCooldown extends LCPacket { + + @Getter private String message; + @Getter private long durationMs; + @Getter private int iconId; + + public LCPacketCooldown() {} + + public LCPacketCooldown(String message, long durationMs, int iconId) { + this.message = message; + this.durationMs = durationMs; + this.iconId = iconId; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(message); + buf.buf().writeLong(durationMs); + buf.buf().writeInt(iconId); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + message = buf.readString(); + durationMs = buf.buf().readLong(); + iconId = buf.buf().readInt(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleCooldown(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketGhost.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketGhost.java new file mode 100644 index 0000000..1a1df27 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketGhost.java @@ -0,0 +1,62 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public final class LCPacketGhost extends LCPacket { + + @Getter private List addGhostList; + @Getter private List removeGhostList; + + public LCPacketGhost() {} + + public LCPacketGhost(List uuidList, List removeGhostList) { + this.addGhostList = uuidList; + this.removeGhostList = removeGhostList; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeVarInt(addGhostList.size()); + + for (UUID uuid : addGhostList) { + buf.writeUUID(uuid); + } + + buf.writeVarInt(removeGhostList.size()); + + for (UUID uuid : removeGhostList) { + buf.writeUUID(uuid); + } + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + int addListSize = buf.readVarInt(); + this.addGhostList = new ArrayList<>(addListSize); + + for (int i = 0; i < addListSize; i++) { + this.addGhostList.add(buf.readUUID()); + } + + int removeListSize = buf.readVarInt(); + this.removeGhostList = new ArrayList<>(removeListSize); + + for (int i = 0; i < removeListSize; i++) { + this.removeGhostList.add(buf.readUUID()); + } + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleGhost(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologram.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologram.java new file mode 100644 index 0000000..a5ab4b2 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologram.java @@ -0,0 +1,63 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public final class LCPacketHologram extends LCPacket { + + @Getter private UUID uuid; + @Getter private double x; + @Getter private double y; + @Getter private double z; + @Getter private List lines; + + public LCPacketHologram() {} + + public LCPacketHologram(UUID uuid, double x, double y, double z, List lines) { + this.uuid = uuid; + this.x = x; + this.y = y; + this.z = z; + this.lines = lines; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeUUID(uuid); + buf.buf().writeDouble(x); + buf.buf().writeDouble(y); + buf.buf().writeDouble(z); + buf.writeVarInt(lines.size()); + + for (String s : lines) { + buf.writeString(s); + } + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.uuid = buf.readUUID(); + this.x = buf.buf().readDouble(); + this.y = buf.buf().readDouble(); + this.z = buf.buf().readDouble(); + int linesSize = buf.readVarInt(); + this.lines = new ArrayList<>(linesSize); + + for (int i = 0; i < linesSize; i++) { + this.lines.add(buf.readString()); + } + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleAddHologram(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologramRemove.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologramRemove.java new file mode 100644 index 0000000..23698bd --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologramRemove.java @@ -0,0 +1,36 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.UUID; + +public final class LCPacketHologramRemove extends LCPacket { + + @Getter private UUID uuid; + + public LCPacketHologramRemove() {} + + public LCPacketHologramRemove(UUID uuid) { + this.uuid = uuid; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeUUID(uuid); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.uuid = buf.readUUID(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleRemoveHologram(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologramUpdate.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologramUpdate.java new file mode 100644 index 0000000..bac533b --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketHologramUpdate.java @@ -0,0 +1,51 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public final class LCPacketHologramUpdate extends LCPacket { + + @Getter private UUID uuid; + @Getter private List lines; + + public LCPacketHologramUpdate() {} + + public LCPacketHologramUpdate(UUID uuid, List lines) { + this.uuid = uuid; + this.lines = lines; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeUUID(uuid); + buf.writeVarInt(lines.size()); + + for (String s : lines) { + buf.writeString(s); + } + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.uuid = buf.readUUID(); + int linesSize = buf.readVarInt(); + this.lines = new ArrayList<>(linesSize); + + for (int i = 0; i < linesSize; i++) { + this.lines.add(buf.readString()); + } + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleUpdateHologram(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketModSettings.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketModSettings.java new file mode 100644 index 0000000..6f8e7c3 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketModSettings.java @@ -0,0 +1,39 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.client.obj.ModSettings; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; + +import java.io.IOException; + +public final class LCPacketModSettings extends LCPacket { + + private ModSettings settings; + + public LCPacketModSettings() {} + + public LCPacketModSettings(ModSettings modSettings) { + this.settings = modSettings; + } + + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(ModSettings.GSON.toJson(this.settings)); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.settings = ModSettings.GSON.fromJson(buf.readString(), ModSettings.class); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleModSettings(this); + } + + public ModSettings getSettings() { + return settings; + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNametagsOverride.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNametagsOverride.java new file mode 100644 index 0000000..a61d690 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNametagsOverride.java @@ -0,0 +1,58 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public final class LCPacketNametagsOverride extends LCPacket { + + @Getter private UUID player; + @Getter private List tags; + + public LCPacketNametagsOverride() {} + + public LCPacketNametagsOverride(UUID player, List tags) { + this.player = player; + this.tags = tags; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeUUID(this.player); + buf.buf().writeBoolean(this.tags != null); + + if (this.tags != null) { + buf.writeVarInt(tags.size()); + + for (String tag : tags) { + buf.writeString(tag); + } + } + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.player = buf.readUUID(); + + if (buf.buf().readBoolean()) { + int tagsSize = buf.readVarInt(); + this.tags = new ArrayList<>(tagsSize); + + for (int i = 0; i < tagsSize; i++) { + tags.add(buf.readString()); + } + } + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleOverrideNametags(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNametagsUpdate.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNametagsUpdate.java new file mode 100644 index 0000000..6496661 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNametagsUpdate.java @@ -0,0 +1,63 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.*; + +public final class LCPacketNametagsUpdate extends LCPacket { + + @Getter private Map> playersMap; + + public LCPacketNametagsUpdate() {} + + public LCPacketNametagsUpdate(Map> playersMap) { + this.playersMap = playersMap; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeVarInt(playersMap == null ? -1 : playersMap.size()); + + if (playersMap != null) { + playersMap.forEach((uuid, tags) -> { + buf.writeUUID(uuid); + buf.writeVarInt(tags.size()); + + for (String tag : tags) { + buf.writeString(tag); + } + }); + } + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + int playersMapSize = buf.readVarInt(); + + if (playersMapSize != -1) { + this.playersMap = new HashMap<>(); + + for (int i = 0; i < playersMapSize; i++) { + UUID uuid = buf.readUUID(); + int tagsSize = buf.readVarInt(); + List tags = new ArrayList<>(tagsSize); + + for (int j = 0; j < tagsSize; j++) { + tags.add(buf.readString()); + } + + this.playersMap.put(uuid, tags); + } + } + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleNametagsUpdate(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNotification.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNotification.java new file mode 100644 index 0000000..9160b84 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketNotification.java @@ -0,0 +1,43 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketNotification extends LCPacket { + + @Getter private String message; + @Getter private long durationMs; + @Getter private String level; + + public LCPacketNotification() {} + + public LCPacketNotification(String message, long durationMs, String level) { + this.message = message; + this.durationMs = durationMs; + this.level = level; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(message); + buf.buf().writeLong(durationMs); + buf.writeString(level); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.message = buf.readString(); + this.durationMs = buf.buf().readLong(); + this.level = buf.readString(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleNotification(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketServerRule.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketServerRule.java new file mode 100644 index 0000000..3691e22 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketServerRule.java @@ -0,0 +1,64 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.client.obj.ServerRule; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketServerRule extends LCPacket { + + @Getter private ServerRule rule; + @Getter private int intValue; + @Getter private float floatValue; + @Getter private boolean booleanValue; + @Getter private String stringValue = ""; + + public LCPacketServerRule() {} + + public LCPacketServerRule(ServerRule rule, float value) { + this.rule = rule; + this.floatValue = value; + } + + public LCPacketServerRule(ServerRule rule, boolean value) { + this.rule = rule; + this.booleanValue = value; + } + + public LCPacketServerRule(ServerRule rule, int value) { + this.rule = rule; + this.intValue = value; + } + + public LCPacketServerRule(ServerRule rule, String value) { + this.rule = rule; + this.stringValue = value; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(rule.getId()); + buf.buf().writeBoolean(booleanValue); + buf.buf().writeInt(intValue); + buf.buf().writeFloat(floatValue); + buf.writeString(stringValue); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.rule = ServerRule.getRule(buf.readString()); + this.booleanValue = buf.buf().readBoolean(); + this.intValue = buf.buf().readInt(); + this.floatValue = buf.buf().readFloat(); + this.stringValue = buf.readString(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleServerRule(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketServerUpdate.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketServerUpdate.java new file mode 100644 index 0000000..cb76e57 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketServerUpdate.java @@ -0,0 +1,35 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketServerUpdate extends LCPacket { + + @Getter private String server; + + public LCPacketServerUpdate() {} + + public LCPacketServerUpdate(String server) { + this.server = server; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(server); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.server = buf.readString(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleServerUpdate(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketStaffModState.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketStaffModState.java new file mode 100644 index 0000000..5d19d7b --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketStaffModState.java @@ -0,0 +1,39 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketStaffModState extends LCPacket { + + @Getter private String mod; + @Getter private boolean state; + + public LCPacketStaffModState() {} + + public LCPacketStaffModState(String mod, boolean state) { + this.mod = mod; + this.state = state; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(mod); + buf.buf().writeBoolean(state); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.mod = buf.readString(); + this.state = buf.buf().readBoolean(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleStaffModState(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketTeammates.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketTeammates.java new file mode 100644 index 0000000..5c859c4 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketTeammates.java @@ -0,0 +1,81 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public final class LCPacketTeammates extends LCPacket { + + @Getter private UUID leader; + @Getter private long lastMs; + @Getter private Map> players; + + public LCPacketTeammates() {} + + public LCPacketTeammates(UUID leader, long lastMs, Map> players) { + this.leader = leader; + this.lastMs = lastMs; + this.players = players; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.buf().writeBoolean(leader != null); + + if (leader != null) { + buf.writeUUID(leader); + } + + buf.buf().writeLong(lastMs); + buf.writeVarInt(this.players.size()); + + this.players.forEach((uuid, posMap) -> { + buf.writeUUID(uuid); + buf.writeVarInt(posMap.size()); + + posMap.forEach((key, val) -> { + buf.writeString(key); + buf.buf().writeDouble(val); + }); + }); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + if (buf.buf().readBoolean()) { + this.leader = buf.readUUID(); + } + + this.lastMs = buf.buf().readLong(); + + int playersSize = buf.readVarInt(); + this.players = new HashMap<>(); + + for (int i = 0; i < playersSize; i++) { + UUID uuid = buf.readUUID(); + int posMapSize = buf.readVarInt(); + Map posMap = new HashMap<>(); + + for (int j = 0; j < posMapSize; j++) { + String key = buf.readString(); + double val = buf.buf().readDouble(); + + posMap.put(key, val); + } + + this.players.put(uuid, posMap); + } + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleTeammates(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketTitle.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketTitle.java new file mode 100644 index 0000000..82cfd2c --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketTitle.java @@ -0,0 +1,59 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketTitle extends LCPacket { + + @Getter private String type; + @Getter private String message; + @Getter private float scale; + @Getter private long displayTimeMs; + @Getter private long fadeInTimeMs; + @Getter private long fadeOutTimeMs; + + public LCPacketTitle() {} + + public LCPacketTitle(String type, String message, long displayTimeMs, long fadeInTimeMs, long fadeOutTimeMs) { + this(type, message, 1F, displayTimeMs, fadeInTimeMs, fadeOutTimeMs); + } + + public LCPacketTitle(String type, String message, float scale, long displayTimeMs, long fadeInTimeMs, long fadeOutTimeMs) { + this.type = type; + this.message = message; + this.scale = scale; + this.displayTimeMs = displayTimeMs; + this.fadeInTimeMs = fadeInTimeMs; + this.fadeOutTimeMs = fadeOutTimeMs; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(type); + buf.writeString(message); + buf.buf().writeFloat(scale); + buf.buf().writeLong(displayTimeMs); + buf.buf().writeLong(fadeInTimeMs); + buf.buf().writeLong(fadeOutTimeMs); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.type = buf.readString(); + this.message = buf.readString(); + this.scale = buf.buf().readFloat(); + this.displayTimeMs = buf.buf().readLong(); + this.fadeInTimeMs = buf.buf().readLong(); + this.fadeOutTimeMs = buf.buf().readLong(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleTitle(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketUpdateWorld.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketUpdateWorld.java new file mode 100644 index 0000000..d4f72be --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketUpdateWorld.java @@ -0,0 +1,35 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketUpdateWorld extends LCPacket { + + @Getter private String world; + + public LCPacketUpdateWorld() {} + + public LCPacketUpdateWorld(String world) { + this.world = world; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(world); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.world = buf.readString(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleUpdateWorld(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketVoiceChannelSwitch.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketVoiceChannelSwitch.java new file mode 100644 index 0000000..b010284 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketVoiceChannelSwitch.java @@ -0,0 +1,37 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.server.LCNetHandlerServer; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.UUID; + +public final class LCPacketVoiceChannelSwitch extends LCPacket { + + @Getter private UUID switchingTo; + + public LCPacketVoiceChannelSwitch() { + } + + public LCPacketVoiceChannelSwitch(UUID switchingTo) { + this.switchingTo = switchingTo; + } + + @Override + public void write(ByteBufWrapper b) throws IOException { + b.writeUUID(switchingTo); + } + + @Override + public void read(ByteBufWrapper b) throws IOException { + this.switchingTo = b.readUUID(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerServer) handler).handleVoiceChannelSwitch(this); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketVoiceMute.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketVoiceMute.java new file mode 100644 index 0000000..bb2e2ac --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketVoiceMute.java @@ -0,0 +1,46 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.server.LCNetHandlerServer; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.UUID; + +public final class LCPacketVoiceMute extends LCPacket { + + @Getter private UUID muting; + + @Getter private int volume; + + public LCPacketVoiceMute() { + } + + public LCPacketVoiceMute(UUID muting) { + this(muting, 0); + } + + public LCPacketVoiceMute(UUID muting, int volume) { + this.muting = muting; + this.volume = volume; + } + + @Override + public void write(ByteBufWrapper b) throws IOException { + b.writeUUID(muting); + b.writeVarInt(volume); + } + + @Override + public void read(ByteBufWrapper b) throws IOException { + this.muting = b.readUUID(); + this.volume = b.readVarInt(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerServer) handler).handleVoiceMute(this); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorder.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorder.java new file mode 100644 index 0000000..2646e7c --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorder.java @@ -0,0 +1,75 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketWorldBorder extends LCPacket { + + @Getter private String id; + @Getter private String world; + @Getter private boolean cancelsExit; + @Getter private boolean canShrinkExpand; + @Getter private int color = 0xFF3333FF; + @Getter private double minX; + @Getter private double minZ; + @Getter private double maxX; + @Getter private double maxZ; + + public LCPacketWorldBorder() {} + + public LCPacketWorldBorder(String id, String world, boolean cancelsExit, boolean canShrinkExpand, int color, double minX, double minZ, double maxX, double maxZ) { + this.id = id; + this.world = world; + this.cancelsExit = cancelsExit; + this.canShrinkExpand = canShrinkExpand; + this.color = color; + this.minX = minX; + this.minZ = minZ; + this.maxX = maxX; + this.maxZ = maxZ; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.buf().writeBoolean(id != null); + + if (id != null) { + buf.writeString(id); + } + + buf.writeString(world); + buf.buf().writeBoolean(cancelsExit); + buf.buf().writeBoolean(canShrinkExpand); + buf.buf().writeInt(color); + buf.buf().writeDouble(minX); + buf.buf().writeDouble(minZ); + buf.buf().writeDouble(maxX); + buf.buf().writeDouble(maxZ); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + if (buf.buf().readBoolean()) { + this.id = buf.readString(); + } + + this.world = buf.readString(); + this.cancelsExit = buf.buf().readBoolean(); + this.canShrinkExpand = buf.buf().readBoolean(); + this.color = buf.buf().readInt(); + this.minX = buf.buf().readDouble(); + this.minZ = buf.buf().readDouble(); + this.maxX = buf.buf().readDouble(); + this.maxZ = buf.buf().readDouble(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleWorldBorder(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderCreateNew.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderCreateNew.java new file mode 100644 index 0000000..6130bf8 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderCreateNew.java @@ -0,0 +1,64 @@ +package com.lunarclient.bukkitapi.nethandler.client; +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.io.IOException; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class LCPacketWorldBorderCreateNew extends LCPacket { + + private String id; + + private String world; + + private boolean cancelsEntry, cancelsExit; + + private boolean canShrinkExpand; + + private int color = 0xFF3333FF; + + private double minX, minZ, maxX, maxZ; + + @Override + public void write(ByteBufWrapper b) throws IOException { + b.buf().writeBoolean(id != null); + if (id != null) b.writeString(id); + b.writeString(world); + b.buf().writeBoolean(cancelsEntry); + b.buf().writeBoolean(cancelsExit); + b.buf().writeBoolean(canShrinkExpand); + b.buf().writeInt(color); + b.buf().writeDouble(minX); + b.buf().writeDouble(minZ); + b.buf().writeDouble(maxX); + b.buf().writeDouble(maxZ); + } + + @Override + public void read(ByteBufWrapper b) throws IOException { + if (b.buf().readBoolean()) { + this.id = b.readString(); + } + + this.world = b.readString(); + this.cancelsEntry = b.buf().readBoolean(); + this.cancelsExit = b.buf().readBoolean(); + this.canShrinkExpand = b.buf().readBoolean(); + this.color = b.buf().readInt(); + this.minX = b.buf().readDouble(); + this.minZ = b.buf().readDouble(); + this.maxX = b.buf().readDouble(); + this.maxZ = b.buf().readDouble(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleWorldBorderCreateNew(this); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderRemove.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderRemove.java new file mode 100644 index 0000000..0f0815f --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderRemove.java @@ -0,0 +1,35 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketWorldBorderRemove extends LCPacket { + + @Getter private String id; + + public LCPacketWorldBorderRemove() {} + + public LCPacketWorldBorderRemove(String id) { + this.id = id; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(id); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.id = buf.readString(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleWorldBorderRemove(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderUpdate.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderUpdate.java new file mode 100644 index 0000000..4d4cb78 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderUpdate.java @@ -0,0 +1,55 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketWorldBorderUpdate extends LCPacket { + + @Getter private String id; + @Getter private double minX; + @Getter private double minZ; + @Getter private double maxX; + @Getter private double maxZ; + @Getter private int durationTicks; + + public LCPacketWorldBorderUpdate() {} + + public LCPacketWorldBorderUpdate(String id, double minX, double minZ, double maxX, double maxZ, int durationTicks) { + this.id = id; + this.minX = minX; + this.minZ = minZ; + this.maxX = maxX; + this.maxZ = maxZ; + this.durationTicks = durationTicks; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(id); + buf.buf().writeDouble(minX); + buf.buf().writeDouble(minZ); + buf.buf().writeDouble(maxX); + buf.buf().writeDouble(maxZ); + buf.buf().writeInt(durationTicks); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.id = buf.readString(); + this.minX = buf.buf().readDouble(); + this.minZ = buf.buf().readDouble(); + this.maxX = buf.buf().readDouble(); + this.maxZ = buf.buf().readDouble(); + this.durationTicks = buf.buf().readInt(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleWorldBorderUpdate(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderUpdateNew.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderUpdateNew.java new file mode 100644 index 0000000..8b7b0f3 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/LCPacketWorldBorderUpdateNew.java @@ -0,0 +1,55 @@ +package com.lunarclient.bukkitapi.nethandler.client; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.io.IOException; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class LCPacketWorldBorderUpdateNew extends LCPacket { + + private String id; + + private double minX, minZ, maxX, maxZ; + private int durationTicks; + + private boolean cancelsEntry, cancelsExit; + private int color; + + @Override + public void write(ByteBufWrapper b) throws IOException { + b.writeString(id); + b.buf().writeDouble(minX); + b.buf().writeDouble(minZ); + b.buf().writeDouble(maxX); + b.buf().writeDouble(maxZ); + b.buf().writeInt(durationTicks); + b.buf().writeBoolean(cancelsEntry); + b.buf().writeBoolean(cancelsExit); + b.buf().writeInt(color); + } + + @Override + public void read(ByteBufWrapper b) throws IOException { + this.id = b.readString(); + this.minX = b.buf().readDouble(); + this.minZ = b.buf().readDouble(); + this.maxX = b.buf().readDouble(); + this.maxZ = b.buf().readDouble(); + this.durationTicks = b.buf().readInt(); + this.cancelsEntry = b.buf().readBoolean(); + this.cancelsExit = b.buf().readBoolean(); + this.color = b.buf().readInt(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleWorldBorderUpdateNew(this); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/obj/ModSettings.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/obj/ModSettings.java new file mode 100644 index 0000000..2ba6af9 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/obj/ModSettings.java @@ -0,0 +1,72 @@ +package com.lunarclient.bukkitapi.nethandler.client.obj; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.lunarclient.bukkitapi.nethandler.ModSettingsAdapter; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public final class ModSettings { + + public static final Gson GSON = new GsonBuilder().registerTypeHierarchyAdapter(ModSettings.class, new ModSettingsAdapter()).create(); + + private Map modSettings = new HashMap<>(); + + public ModSettings addModSetting(String modId, ModSetting setting) { + modSettings.put(modId, setting); + return this; + } + + public ModSetting getModSetting(String modId) { + return this.modSettings.get(modId); + } + + public Map getModSettings() { + return modSettings; + } + + public static class ModSetting { + private boolean enabled; + private Map properties; + + public ModSetting() { } // for serialization + + public ModSetting(boolean enabled, Map properties) { + this.enabled = enabled; + this.properties = properties; + } + + public boolean isEnabled() { + return enabled; + } + + public Map getProperties() { + return properties; + } + + @Override + public String toString() { + return "ModSetting{" + + "enabled=" + enabled + + ", properties=" + properties + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ModSetting that = (ModSetting) o; + return enabled == that.enabled && + Objects.equals(properties, that.properties); + } + + @Override + public int hashCode() { + return Objects.hash(enabled, properties); + } + } + +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/obj/ServerRule.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/obj/ServerRule.java new file mode 100644 index 0000000..fb6187d --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/client/obj/ServerRule.java @@ -0,0 +1,62 @@ +package com.lunarclient.bukkitapi.nethandler.client.obj; + +import lombok.Getter; + +public enum ServerRule { + + /** + * Whether or not minimap is allowed + * Expected value: (String) NEUTRAL or FORCED_OFF + */ + MINIMAP_STATUS("minimapStatus", String.class), + + /** + * Whether or not the server will store waypoints, instead of the client + */ + SERVER_HANDLES_WAYPOINTS("serverHandlesWaypoints", Boolean.class), + + /** + * A warning message will be shown when attempting to disconnect if the current + * game is competitive. + */ + COMPETITIVE_GAME("competitiveGame", Boolean.class), + + /** + * If this server forces shaders to be disabled + */ + SHADERS_DISABLED("shadersDisabled", Boolean.class), + + /** + * If the server runs legacy enchanting (pre 1.8) + */ + LEGACY_ENCHANTING("legacyEnchanting", Boolean.class), + + /** + * If this server has enabled voice chat + */ + VOICE_ENABLED("voiceEnabled", Boolean.class), + + /** + * Whether to revert combat mechanics to 1.7 + */ + LEGACY_COMBAT("legacyCombat", Boolean.class); + + @Getter private String id; + @Getter private Class type; + + ServerRule(String id, Class type) { + this.id = id; + this.type = type; + } + + public static ServerRule getRule(String id) { + for (ServerRule existing : ServerRule.values()) { + if (existing.id.equals(id)) { + return existing; + } + } + + return null; + } + +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCNetHandlerServer.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCNetHandlerServer.java new file mode 100644 index 0000000..cbbfd39 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCNetHandlerServer.java @@ -0,0 +1,14 @@ +package com.lunarclient.bukkitapi.nethandler.server; + +import com.lunarclient.bukkitapi.nethandler.client.LCPacketClientVoice; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketVoiceMute; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketVoiceChannelSwitch; + +public interface LCNetHandlerServer extends LCNetHandler { + + void handleStaffModStatus(LCPacketStaffModStatus packet); + void handleVoice(LCPacketClientVoice packet); + void handleVoiceMute(LCPacketVoiceMute packet); + void handleVoiceChannelSwitch(LCPacketVoiceChannelSwitch packet); +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketStaffModStatus.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketStaffModStatus.java new file mode 100644 index 0000000..519f833 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketStaffModStatus.java @@ -0,0 +1,47 @@ +package com.lunarclient.bukkitapi.nethandler.server; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.Getter; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +public final class LCPacketStaffModStatus extends LCPacket { + + @Getter private Set enabled; + + public LCPacketStaffModStatus() { + this.enabled = new HashSet<>(); + } + + public LCPacketStaffModStatus(Set enabled) { + this.enabled = enabled; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeVarInt(enabled.size()); + + for (String mod : enabled) { + buf.writeString(mod); + } + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + int size = buf.readVarInt(); + + for (int i = 0; i < size; i++) { + enabled.add(buf.readString()); + } + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerServer) handler).handleStaffModStatus(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoice.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoice.java new file mode 100644 index 0000000..f80a862 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoice.java @@ -0,0 +1,60 @@ +package com.lunarclient.bukkitapi.nethandler.server; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.client.LCNetHandlerClient; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +@AllArgsConstructor +@NoArgsConstructor +public final class LCPacketVoice extends LCPacket { + /** + * The UUID of all the senders, since we're using multiplex + * we don't actually know the bytes per user + */ + @Getter private Set uuids; + + /** + * The "smashed" bytes of all the voice. + */ + @Getter private byte[] data; + + @Override + public void write(ByteBufWrapper b) { + b.writeVarInt(uuids.size()); + uuids.forEach(b::writeUUID); + writeBlob(b, this.data); + } + + @Override + public void read(ByteBufWrapper b) { + uuids = new HashSet<>(); + int size = b.readVarInt(); + for (int i = 0; i < size; i++) { + uuids.add(b.readUUID()); + } + this.data = readBlob(b); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleVoice(this); + } + + /** + * For comparability, will be removed. + * @return The 0 index of the sent players. + */ + @Deprecated + public UUID getUuid() { + return new ArrayList<>(uuids).get(0); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannel.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannel.java new file mode 100644 index 0000000..67f6add --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannel.java @@ -0,0 +1,70 @@ +package com.lunarclient.bukkitapi.nethandler.server; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.client.LCNetHandlerClient; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +@AllArgsConstructor +@NoArgsConstructor +public final class LCPacketVoiceChannel extends LCPacket { + + @Getter private UUID uuid; + + @Getter private String name; + + @Getter private Map players; + + @Getter private Map listening; + + @Override + public void write(ByteBufWrapper b) { + b.writeUUID(uuid); + b.writeString(name); + writeMap(b, players); + writeMap(b, listening); + } + + @Override + public void read(ByteBufWrapper b) { + this.uuid = b.readUUID(); + this.name = b.readString(); + this.players = readMap(b); + this.listening = readMap(b); + } + + private void writeMap(ByteBufWrapper b, Map players) { + b.writeVarInt(players.size()); + for (Map.Entry player : players.entrySet()) { + b.writeUUID(player.getKey()); + b.writeString(player.getValue()); + } + } + + private Map readMap(ByteBufWrapper b) { + int size = b.readVarInt(); + + Map players = new HashMap<>(); + + for (int i = 0; i < size; i++) { + UUID uuid = b.readUUID(); + String name = b.readString(); + + players.put(uuid, name); + } + + return players; + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleVoiceChannels(this); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannelRemove.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannelRemove.java new file mode 100644 index 0000000..3d93f77 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannelRemove.java @@ -0,0 +1,33 @@ +package com.lunarclient.bukkitapi.nethandler.server; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.client.LCNetHandlerClient; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.UUID; + +@AllArgsConstructor +@NoArgsConstructor +public final class LCPacketVoiceChannelRemove extends LCPacket { + + @Getter private UUID uuid; + + @Override + public void write(ByteBufWrapper b) { + b.writeUUID(uuid); + } + + @Override + public void read(ByteBufWrapper b) { + this.uuid = b.readUUID(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleVoiceChannelDelete(this); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannelUpdate.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannelUpdate.java new file mode 100644 index 0000000..d64aca3 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/server/LCPacketVoiceChannelUpdate.java @@ -0,0 +1,51 @@ +package com.lunarclient.bukkitapi.nethandler.server; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import com.lunarclient.bukkitapi.nethandler.client.LCNetHandlerClient; +import com.lunarclient.bukkitapi.nethandler.shared.LCNetHandler; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.UUID; + +@AllArgsConstructor +@NoArgsConstructor +public final class LCPacketVoiceChannelUpdate extends LCPacket { + + /** + * 0 for adding a player + * 1 for removing a player + * 2 for marking a player as listening + * 3 for marking a player as deafened + */ + @Getter public int status; + + @Getter private UUID channelUuid; + + @Getter private UUID uuid; + + @Getter private String name; + + @Override + public void write(ByteBufWrapper b) { + b.writeVarInt(status); + b.writeUUID(channelUuid); + b.writeUUID(uuid); + b.writeString(name); + } + + @Override + public void read(ByteBufWrapper b) { + this.status = b.readVarInt(); + this.channelUuid = b.readUUID(); + this.uuid = b.readUUID(); + this.name = b.readString(); + } + + @Override + public void process(LCNetHandler handler) { + ((LCNetHandlerClient) handler).handleVoiceChannelUpdate(this); + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCNetHandler.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCNetHandler.java new file mode 100644 index 0000000..e876170 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCNetHandler.java @@ -0,0 +1,9 @@ +package com.lunarclient.bukkitapi.nethandler.shared; + +public interface LCNetHandler { + + void handleAddWaypoint(LCPacketWaypointAdd packet); + void handleRemoveWaypoint(LCPacketWaypointRemove packet); + void handleEmote(LCPacketEmoteBroadcast packet); + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketEmoteBroadcast.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketEmoteBroadcast.java new file mode 100644 index 0000000..3efb0df --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketEmoteBroadcast.java @@ -0,0 +1,39 @@ +package com.lunarclient.bukkitapi.nethandler.shared; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import lombok.Getter; + +import java.io.IOException; +import java.util.UUID; + +public final class LCPacketEmoteBroadcast extends LCPacket { + + @Getter private UUID uuid; // User doing the emote + @Getter private int emoteId; + + public LCPacketEmoteBroadcast() {} + + public LCPacketEmoteBroadcast(UUID uuid, int emoteId) { + this.uuid = uuid; + this.emoteId = emoteId; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeUUID(uuid); + buf.buf().writeInt(emoteId); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.uuid = buf.readUUID(); + this.emoteId = buf.buf().readInt(); + } + + @Override + public void process(LCNetHandler handler) { + handler.handleEmote(this); + } + +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketWaypointAdd.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketWaypointAdd.java new file mode 100644 index 0000000..f74e729 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketWaypointAdd.java @@ -0,0 +1,62 @@ +package com.lunarclient.bukkitapi.nethandler.shared; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketWaypointAdd extends LCPacket { + + @Getter private String name; + @Getter private String world; + @Getter private int color; + @Getter private int x; + @Getter private int y; + @Getter private int z; + @Getter private boolean forced; + @Getter private boolean visible; + + public LCPacketWaypointAdd() {} + + public LCPacketWaypointAdd(String name, String world, int color, int x, int y, int z, boolean forced, boolean visible) { + this.name = name; + this.world = world; + this.color = color; + this.x = x; + this.y = y; + this.z = z; + this.forced = forced; + this.visible = visible; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(name); + buf.writeString(world); + buf.buf().writeInt(color); + buf.buf().writeInt(x); + buf.buf().writeInt(y); + buf.buf().writeInt(z); + buf.buf().writeBoolean(forced); + buf.buf().writeBoolean(visible); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.name = buf.readString(); + this.world = buf.readString(); + this.color = buf.buf().readInt(); + this.x = buf.buf().readInt(); + this.y = buf.buf().readInt(); + this.z = buf.buf().readInt(); + this.forced = buf.buf().readBoolean(); + this.visible = buf.buf().readBoolean(); + } + + @Override + public void process(LCNetHandler handler) { + handler.handleAddWaypoint(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketWaypointRemove.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketWaypointRemove.java new file mode 100644 index 0000000..682d8a7 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/nethandler/shared/LCPacketWaypointRemove.java @@ -0,0 +1,38 @@ +package com.lunarclient.bukkitapi.nethandler.shared; + +import com.lunarclient.bukkitapi.nethandler.ByteBufWrapper; +import com.lunarclient.bukkitapi.nethandler.LCPacket; +import lombok.Getter; + +import java.io.IOException; + +public final class LCPacketWaypointRemove extends LCPacket { + + @Getter private String name; + @Getter private String world; + + public LCPacketWaypointRemove() {} + + public LCPacketWaypointRemove(String name, String world) { + this.name = name; + this.world = world; + } + + @Override + public void write(ByteBufWrapper buf) throws IOException { + buf.writeString(name); + buf.writeString(world); + } + + @Override + public void read(ByteBufWrapper buf) throws IOException { + this.name = buf.readString(); + this.world = buf.readString(); + } + + @Override + public void process(LCNetHandler handler) { + handler.handleRemoveWaypoint(this); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/object/LCWaypoint.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/object/LCWaypoint.java new file mode 100644 index 0000000..221ab1f --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/object/LCWaypoint.java @@ -0,0 +1,54 @@ +package com.lunarclient.bukkitapi.object; + +import com.lunarclient.bukkitapi.LunarClientAPI; +import lombok.AllArgsConstructor; +import lombok.Data; +import org.bukkit.Location; + +@Data +@AllArgsConstructor +public final class LCWaypoint { + + private final String name; + private final int x; + private final int y; + private final int z; + private final String world; + private final int color; + private final boolean forced; + private final boolean visible; + + /** + * Create a waypoint with any visibility. + * + * NOTE: Just because a waypoint object is created, that doesn't mean + * it will be sent to users. To display the waypoint you must still send + * it to the Lunar Client user. + * + * @param name The name of the waypoint (this is important if you need to edit it later, save the name). + * @param location The bukkit {@link Location} to display the waypoint at. Whole blocks only, partial blocks aren't accounted for. + * @param color The HEX color to set as the color for the waypoint. + * @param forced If the client should be able to remove the waypoint, or if it is forced for gameplay reasons. + * @param visible Weather or not the waypoint should be visible. This will likely always be true. + */ + public LCWaypoint(String name, Location location, int color, boolean forced, boolean visible) { + this(name, location.getBlockX(), location.getBlockY(), location.getBlockZ(), LunarClientAPI.getInstance().getWorldIdentifier(location.getWorld()), color, forced, visible); + } + + /** + * Create a waypoint that is automatically visible when sent. + * + * NOTE: Just because a waypoint object is created, that doesn't mean + * it will be sent to users. To display the waypoint you must still send + * it to the Lunar Client user. + * + * @param name The name of the waypoint (this is important if you need to edit it later, save the name). + * @param location The bukkit {@link Location} to display the waypoint at. Whole blocks only, partial blocks aren't accounted for. + * @param color The HEX color to set as the color for the waypoint. + * @param forced If the client should be able to remove the waypoint, or if it is forced for gameplay reasons. + */ + public LCWaypoint(String name, Location location, int color, boolean forced) { + this(name, location, color, forced, true); + } + +} \ No newline at end of file diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/object/StaffModule.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/object/StaffModule.java new file mode 100644 index 0000000..a9e8f52 --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/object/StaffModule.java @@ -0,0 +1,25 @@ +package com.lunarclient.bukkitapi.object; + +/** + * Lunar client has hidden StaffModule that can be + * sent to a user at any given point. + * + * Currently only XRAY is implemented but there are + * future plans to expand this to possibly NAME_TAGS, + * and there is still discussion of whether BUNNY_HOP + * will make a return. + * + * NOTE: Lunar Client will NOT check if the user is + * actually staff, if the user is given any StaffModule + * by the server it is assumed that the server knows what + * it is doing and will not check permissions or other. + */ +public enum StaffModule { + + XRAY, + @Deprecated + NAME_TAGS, + @Deprecated + BUNNY_HOP + +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/serverrule/LunarClientAPIServerRule.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/serverrule/LunarClientAPIServerRule.java new file mode 100644 index 0000000..f64fa1f --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/serverrule/LunarClientAPIServerRule.java @@ -0,0 +1,52 @@ +package com.lunarclient.bukkitapi.serverrule; + +import com.lunarclient.bukkitapi.LunarClientAPI; +import com.lunarclient.bukkitapi.nethandler.client.LCPacketServerRule; +import com.lunarclient.bukkitapi.nethandler.client.obj.ServerRule; +import lombok.experimental.UtilityClass; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +@UtilityClass +public class LunarClientAPIServerRule { + + // The reason this is a Map is so that hopefully we will only have 1 server rule packet + // per ServerRule. It would be extremely weird behavior if multiple with the same type were sent. + private final Map CUSTOM_SERVER_RULES = new HashMap<>(); + + /** + * Set a server rule to a boolean value. + * All current server rules (02/02/2021) + * use a boolean value. + * + * @param rule The ServerRule with type of boolean. + * @param value The value of the ServerRule. + */ + public void setRule(ServerRule rule, Boolean value) { + CUSTOM_SERVER_RULES.put(rule, new LCPacketServerRule(rule, value)); + } + + /** + * Send all set server rules to player(s). + * This will likely work best to be sent on join. + * + * If a server rule is updated, the players will need to be updated. + * This is not an automatic process. The ideal usage would be to set + * all server rules when the plugin loads, then when each player joins + * send them all server rules. + * + * @param players The player(s) to get all the previously set server rules. + */ + public void sendServerRule(Player... players) { + if (CUSTOM_SERVER_RULES.isEmpty()) { + return; + } + for (Player player : players) { + for (LCPacketServerRule value : CUSTOM_SERVER_RULES.values()) { + LunarClientAPI.getInstance().sendPacket(player, value); + } + } + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/title/LCTitleBuilder.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/title/LCTitleBuilder.java new file mode 100644 index 0000000..fa9599a --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/title/LCTitleBuilder.java @@ -0,0 +1,157 @@ +package com.lunarclient.bukkitapi.title; + +import com.lunarclient.bukkitapi.nethandler.client.LCPacketTitle; +import com.lunarclient.bukkitapi.LunarClientAPI; +import org.bukkit.entity.Player; + +import java.time.Duration; + +public final class LCTitleBuilder { + + /** + * Create a LCTitle by type and message. + * The message is final, but the type can be changed + * until the packet is built. + * + * @param message The message that will be displayed. + * @param type The {@link TitleType} to send to the client + * @return A new title builder. + */ + public static LCTitleBuilder of(String message, TitleType type) { + return new LCTitleBuilder(message, type); + } + + /** + * Create a LCTitle with a message. + * The type defaults to a title. + * + * @param message The message to display to the user. + * @return The new title builder. + */ + public static LCTitleBuilder of(String message) { + return of(message, TitleType.TITLE); + } + + private final String message; + private TitleType type; + private float scale; + private Duration displayDuration; + private Duration fadeInDuration; + private Duration fadeOutDuration; + + /** + * Starts a new builder with default params. + * If nothing else is specified then it will + * default to a title with your message that lasts + * 1.5 seconds and fades in and out for .5 seconds. + * + * @param message The final message specified to start the builder. + * @param type The type to start the builder. + */ + private LCTitleBuilder(String message, TitleType type) { + this.message = message; + this.type = type; + this.scale = 1; + this.displayDuration = Duration.ofMillis(1500); + this.fadeInDuration = Duration.ofMillis(500); + this.fadeOutDuration = Duration.ofMillis(500); + } + + /** + * Specify the {@link TitleType} for the title to be displayed. + * @param type The type of type to display. + * @return This builder with the updated value. + */ + public LCTitleBuilder type(TitleType type) { + this.type = type; + return this; + } + + /** + * Scale up or down the title sent to the client. + * + * @param scale The new scale (greater than 0) that the message will be displayed on. + * @return This builder with the updated value. + */ + public LCTitleBuilder scale(float scale) { + this.scale = scale; + return this; + } + + /** + * Specify the display time for which this + * title will be displayed to the user. + * + * The title will display for fade in + DISPLAY TIME + fade out = total display time. + * + * @param duration The {@link Duration} of how long to display the title for. + * @return This builder with the updated value. + */ + public LCTitleBuilder displayFor(Duration duration) { + this.displayDuration = duration; + return this; + } + + /** + * Specify the amount of time it takes + * the title to fade in for the user. + * + * The title will display for FADE IN + duration + fade out = total display time. + * + * @param duration The {@link Duration} of how long to fade in the title for. + * @return This builder with the updated value. + */ + public LCTitleBuilder fadeInFor(Duration duration) { + this.fadeInDuration = duration; + return this; + } + + /** + * Specify the amount of time it takes + * the title to fade out for the user. + * + * The title will display for fade in + duration + FADE OUT = total display time. + * + * @param duration The {@link Duration} of how long to fade in the title for. + * @return This builder with the updated value. + */ + public LCTitleBuilder fadeOutFor(Duration duration) { + this.fadeOutDuration = duration; + return this; + } + + + /** + * Take all the inputs from the builder and convert + * it into a single LCPacketTitle you can use to + * save and send to players as needed. + * + * Ideally if possible you would build the title packet once + * and then send it to all the players that can see it. + * A good example of this would be a welcome title, where + * its entirely static but needs to be sent to all users. + * + * @return The {@link LCPacketTitle} to send to Lunar Client users as needed. + */ + public LCPacketTitle build() { + return new LCPacketTitle(type.name().toLowerCase(), message, scale, displayDuration.toMillis(), fadeInDuration.toMillis(), fadeOutDuration.toMillis()); + } + + /** + * Builds the current packet and sends it to all players required. + * + * A good use case for this would be if all players online need + * to see the same message, at the same time and it won't be sent again. + * Like an announcement for an objective in a mini-game. + * + * @param players All the {@link Player} that need to see the title. + * @return The {@link LCPacketTitle} generated that can be used later if needed. + */ + public LCPacketTitle sendAndBuild(Player... players) { + LCPacketTitle title = build(); + for (Player player : players) { + LunarClientAPI.getInstance().sendPacket(player, title); + } + return title; + } +} diff --git a/LunarAPI/src/main/java/com/lunarclient/bukkitapi/title/TitleType.java b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/title/TitleType.java new file mode 100644 index 0000000..e8df01d --- /dev/null +++ b/LunarAPI/src/main/java/com/lunarclient/bukkitapi/title/TitleType.java @@ -0,0 +1,6 @@ +package com.lunarclient.bukkitapi.title; + +public enum TitleType { + TITLE, + SUBTITLE, +} diff --git a/LunarAPI/src/main/resources/plugin.yml b/LunarAPI/src/main/resources/plugin.yml new file mode 100644 index 0000000..36d5b6e --- /dev/null +++ b/LunarAPI/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedLunarAPI +version: ${git.commit.id.abbrev} +description: A server interface for the Lunar Client +author: Moonsworth LLC Development Team +main: com.lunarclient.bukkitapi.LunarClientAPI +load: STARTUP +website: https://www.lunarclient.com/ diff --git a/Masks/README.md b/Masks/README.md new file mode 100644 index 0000000..13416cc --- /dev/null +++ b/Masks/README.md @@ -0,0 +1,28 @@ +Each registered mask has a config at `plugins/CrankedMasks/masks/.yml`. +Starting the plugin fills in missing settings with that mask's defaults and keeps +existing settings. For example, `masks/boss.yml` contains: + +```yaml +mask: + displayName: '&6&lBoss Mask' + texture: '' + perks: + - '&6Abilities:' + - '&8 ● &6+15% Outgoing damage to bosses' + - '&8 ● &6-20% Incoming damage to bosses' + lore: + - '&7A seasoned monster hunter, you pride' + - '&7yourself on your boss slaying record.' +``` + +Keep the generated texture or replace it with a valid base64 skin texture. Names, +lore, and perk descriptions support `&` color codes. `perks` controls the text +shown on the item; ability behavior remains defined in each mask's Java class. +The mask ID and filename remain stable when changing the display name. + +After editing, run `/cm reload` in game to apply the config to newly generated +items. Existing items keep their saved name and lore. Invalid values are logged +with their filename and setting; malformed YAML is left intact for correction. + +`/adminitems` includes a Masks entry opening the same menu as `/masks`. Players +with `cranked.admin` can click a mask in that menu to receive it. diff --git a/Masks/pom.xml b/Masks/pom.xml new file mode 100644 index 0000000..62808ca --- /dev/null +++ b/Masks/pom.xml @@ -0,0 +1,34 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Masks + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + net.crankedpvp + Armor + + + com.comphenix.protocol + ProtocolLib + + + + \ No newline at end of file diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/CrankedMasks.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/CrankedMasks.java new file mode 100644 index 0000000..4b9eab1 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/CrankedMasks.java @@ -0,0 +1,67 @@ +package net.crankedpvp.crankedmasks; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedmasks.commands.AdminMaskCommand; +import net.crankedpvp.crankedmasks.commands.MasksCommand; +import net.crankedpvp.crankedmasks.language.LanguageHandler; +import net.crankedpvp.crankedmasks.listeners.MaskListener; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedmasks.struct.MasksRegister; +import net.crankedpvp.crankedmasks.struct.config.MaskConfigManager; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.stream.Collectors; + +@Getter +public class CrankedMasks extends JavaPlugin { + @Getter + private static CrankedMasks instance; + + private MasksRegister masksRegister; + private LanguageHandler languageHandler; + private CommandManager commandManager; + private MaskConfigManager maskConfigManager; + + @Override + public void onEnable() { + instance = this; + + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + + this.masksRegister = new MasksRegister(); + this.masksRegister.initialize(); + + this.maskConfigManager = new MaskConfigManager(this); + this.maskConfigManager.setupFiles(); + + this.commandManager = new CommandManager(this); + this.registerCommandParameters(); + this.registerCommandCompletion(); + this.commandManager.register(new AdminMaskCommand(this)); + this.commandManager.register(new MasksCommand()); + + + + PluginUtils.registerListeners(this, new MaskListener()); + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(Mask.class, argument -> { + Mask mask = this.masksRegister.getMaskFromID(this.masksRegister.getMaskIDFromName(String.valueOf(argument))); + return new TypeResult(mask, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#masks", input -> this.masksRegister.getMasks().stream().map(Mask::getID).collect(Collectors.toList())); + } + + @Override + public void onDisable() { + instance = null; + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/CrankedMasksAPI.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/CrankedMasksAPI.java new file mode 100644 index 0000000..f8f33a3 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/CrankedMasksAPI.java @@ -0,0 +1,159 @@ +package net.crankedpvp.crankedmasks; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedmasks.struct.MasksRegister; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +public class CrankedMasksAPI { + + public static List getMaskFromItem(ItemStack item) { + if (!ItemUtils.isSkull(item)) return null; + + NBTItem wrapper = new NBTItem(item); + if(!wrapper.hasKey("cosmicType") || !wrapper.getString("cosmicType").equals("mask")) + return null; + NBTCompound compound = wrapper.getOrCreateCompound("cosmicData"); + if(!compound.hasKey("maskType")) + return null; + List masks = new ArrayList<>(); + for(String string : compound.getString("maskType").split(",")) { + masks.add(MasksRegister.getInstance().getMaskFromID(string)); + } + return masks; + } + + public static boolean hasMaskEquipped(Player player, Mask mask) { + if (player.getInventory().getHelmet() == null) return false; + ItemStack helmet = player.getInventory().getHelmet(); + if (!itemHasMaskEquipped(helmet)) return false; + return getMasksOnItem(helmet).contains(mask); + } + + public static boolean hasMaskEquipped(Player player, String maskID) { + if (player.getInventory().getHelmet() == null) return false; + ItemStack helmet = player.getInventory().getHelmet(); + if (!itemHasMaskEquipped(helmet)) return false; + return getMasksOnItem(helmet).contains(CrankedMasks.getInstance().getMasksRegister().getMaskFromID(maskID)); + } + + public static boolean itemHasMaskEquipped(ItemStack item) { + if(!ItemUtils.isHelmet(item)) return false; + + NBTItem compound = new NBTItem(item); + + if(compound.hasKey("cosmicType") && compound.getString("cosmicType").equals("mask")) return false; + + NBTCompound cosmicData = compound.getOrCreateCompound("cosmicData"); + return cosmicData.hasKey("maskType"); + } + + @Nullable + public static List getMasksOnItem(ItemStack item) { + if (!ItemUtils.isHelmet(item)) return null; + List masks = new ArrayList<>(); + NBTItem nbtItem = new NBTItem(item); + if(!nbtItem.hasNBTData()) return null; + NBTCompound nbtCompound = nbtItem.getCompound("cosmicData"); + if(nbtCompound == null) return null; + if(!nbtCompound.hasKey("maskType")) return null; + for(String string : nbtCompound.getString("maskType").split(",")) { + masks.add(MasksRegister.getInstance().getMaskFromID(string)); + } + return masks; + } + + public static boolean isMask(ItemStack item) { + if (!ItemUtils.isSkull(item)) return false; + + NBTItem nbtItem = new NBTItem(item); + if (!nbtItem.hasKey("cosmicType")) return false; + return nbtItem.getString("cosmicType").equals("mask"); + } + + public static boolean isFounderMask(ItemStack item) { + if (!isMask(item)) return false; + NBTItem nbtItem = new NBTItem(item); + return nbtItem.hasKey("founderMask"); + } + + public static ItemStack remove(ItemStack item) { + NBTItem nbt = new NBTItem(item); + if(nbt.hasKey("founderMask")) nbt.removeKey("founderMask"); + NBTCompound cosmicData = nbt.getOrCreateCompound("cosmicData"); + cosmicData.removeKey("maskType"); + item = nbt.getItem(); + List lore = item.getItemMeta().getLore(); + if(lore != null) { + lore.removeIf(string -> string.startsWith(CC.translate("&7&lATTACHED:"))); + item = new ItemBuilder(item).setLore(lore).build(); + } + + return item; + } + + + public static ItemStack buildFounderMask() { + ItemStack skull = SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTUwMjkyNTc0NjVjNWVhYmZkM2QxOTQwOTcxZTNmZDZlNzYxZWEzYjMxNDlmNmQ5MWM4YzY3NmYwYTVmODgzIn19fQ=="); + ItemBuilder itemBuilder = new ItemBuilder(skull).setName("&4&lFounder Mask"); + + itemBuilder.addLoreLine("&fThis mask holds the power of"); + itemBuilder.addLoreLine("&fall current, unvaulted masks"); + itemBuilder.addLoreLine(""); + itemBuilder.addLoreLine("&dAbilities:"); + Collection masks = MasksRegister.getInstance().getMasks(); + List names = masks.stream().map(mask -> mask.getDisplayName().replace("§l", "")).sorted().collect(Collectors.toList()); + for(String name : names) { + itemBuilder.addLoreLine("&f ● " + name + " Abilities"); + } + itemBuilder.addLoreLine(""); + + itemBuilder + .addLore("&7&oAttach this mask to any helmet") + .addLore("&7&oto give it a visual override!") + .addLore("") + .addLore("&7To attach, place this mask on a helmet.") + .addLore("&7To unattach, right-click helmet while attached."); + + itemBuilder.colorize().build(); + + NBTItem wrapper = new NBTItem(skull); + wrapper.setString("cosmicType", "mask"); + wrapper.setString("founderMask", "founderMask"); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + String maskIds = masks.stream().map(Mask::getID).collect(Collectors.joining(",")); + cosmicData.setString("maskType", maskIds); + return wrapper.getItem(); + } + + public static ItemStack applyFounderMask(ItemStack item) { + Collection masks = MasksRegister.getInstance().getMasks(); + item = new ItemBuilder(item).addLore("&7&lATTACHED: &4&lFounder Mask").colorize().build(); + NBTItem wrapper = new NBTItem(item); + wrapper.setString("founderMask", "founderMask"); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + cosmicData.setString("maskType", "founderMask"); + String maskIds = masks.stream().map(Mask::getID).collect(Collectors.joining(",")); + cosmicData.setString("maskType", maskIds); + return wrapper.getItem(); + } + + public static boolean hasFounderMask(ItemStack clicked) { + if(!ItemUtils.isHelmet(clicked)) return false; + NBTItem nbtItem = new NBTItem(clicked); + return nbtItem.hasKey("founderMask"); + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/commands/AdminMaskCommand.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/commands/AdminMaskCommand.java new file mode 100644 index 0000000..016f9f0 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/commands/AdminMaskCommand.java @@ -0,0 +1,83 @@ +package net.crankedpvp.crankedmasks.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedmasks.language.Language; +import net.crankedpvp.crankedmasks.language.LanguageHandler; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedmasks.struct.MasksRegister; +import net.crankedpvp.crankedmasks.struct.config.MaskConfigManager; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +@Command("cm") +public class AdminMaskCommand extends CommandBase { + + private final LanguageHandler languageHandler; + private final MaskConfigManager maskConfigManager; + + public AdminMaskCommand(CrankedMasks plugin) { + this.languageHandler = plugin.getLanguageHandler(); + this.maskConfigManager = plugin.getMaskConfigManager(); + } + + @Default + @Permission("cranked.admin") + public void mainCommand(CommandSender sender) { + Language.ADMIN_COMMAND_HELP.send(sender); + } + + @SubCommand("mask") + @WrongUsage("&cUsage: /cm mask ") + @Permission("cranked.admin") + public void maskCommand(CommandSender sender, @Completion("#players") Player player, @Completion("#masks") String[] masks) { + if (masks == null) { + Language.INVALID_MASK.send(sender); + return; + } + + Mask mask = MasksRegister.getInstance().getMaskFromID(masks[0]); + + if (masks.length == 1) { + assert mask != null; + player.getInventory().addItem(mask.getItem()); + return; + } + + List multiMasks = Arrays.stream(masks) + .map(id -> MasksRegister.getInstance().getMaskFromID(id)) + .distinct() + .collect(Collectors.toList()); + assert mask != null; + player.getInventory().addItem(mask.buildMultiMask(multiMasks)); + + } + + @SubCommand("founder") + @WrongUsage("&cUsage: /cm founder ") + @Permission("cranked.admin") + public void maskCommand(CommandSender sender, @Completion("#players") Player player) { + player.getInventory().addItem(CrankedMasksAPI.buildFounderMask()); + + } + + @SubCommand("reload") + @WrongUsage("&cUsage: /cm reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + this.languageHandler.load(); + this.maskConfigManager.reloadFiles(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/commands/MasksCommand.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/commands/MasksCommand.java new file mode 100644 index 0000000..8b612d7 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/commands/MasksCommand.java @@ -0,0 +1,25 @@ +package net.crankedpvp.crankedmasks.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedmasks.inventory.MasksInventory; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("mask") +@Alias({"masks", "maskss"}) +public class MasksCommand extends CommandBase { + + @Default + public void mainCommand(CommandSender sender) { + if(!(sender instanceof Player)) return; + Player player = (Player)sender; + MasksInventory masksInventory = new MasksInventory(); + masksInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/cooldown/MaskClickCooldown.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/cooldown/MaskClickCooldown.java new file mode 100644 index 0000000..b97e449 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/cooldown/MaskClickCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedmasks.cooldown; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class MaskClickCooldown extends CurrentCooldown { + public MaskClickCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} \ No newline at end of file diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/events/MaskedItemEquipEvent.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/events/MaskedItemEquipEvent.java new file mode 100644 index 0000000..5191471 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/events/MaskedItemEquipEvent.java @@ -0,0 +1,34 @@ +package net.crankedpvp.crankedmasks.events; + +import lombok.Getter; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.events.ArmorEquipEvent; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.List; + +@Getter +public class MaskedItemEquipEvent extends Event implements Cancellable { + + private boolean cancelled; + private final Player player; + private final List maskTypes; + private final ArmorEquipEvent armorEquipEvent; + private final HandlerList handlers; + + public MaskedItemEquipEvent(Player player, List types, ArmorEquipEvent event) { + this.player = player; + this.maskTypes = types; + this.armorEquipEvent = event; + this.cancelled = false; + this.handlers = new HandlerList(); + } + + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/inventory/MasksInventory.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/inventory/MasksInventory.java new file mode 100644 index 0000000..47f3943 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/inventory/MasksInventory.java @@ -0,0 +1,68 @@ +package net.crankedpvp.crankedmasks.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Collection; + +public class MasksInventory { + private final Gui masksInventory; + + public Gui getUI() { + return this.masksInventory; + } + + Collection masks = CrankedMasks.getInstance().getMasksRegister().getMasks(); + + public MasksInventory() { + this.masksInventory = new Gui(6, "Cranked Masks"); + this.masksInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.masksInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.masksInventory.updateItem(6, 5, new GuiItem(createExitItem(), event -> event.getWhoClicked().closeInventory())); + this.masksInventory.updateItem(1, 5, new GuiItem(createInformationItem())); + + for(Mask mask : masks) { + this.masksInventory.addItem(new GuiItem(mask.getItem(), event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) event.getWhoClicked().getInventory().addItem(mask.getItem()); + })); + } + } + + private ItemStack createExitItem() { + ItemStack item = new ItemStack(Material.BED); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cExit Masks menu")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createInformationItem() { + return new ItemBuilder(Material.BOOK, "&a&lCranked Masks", + "&7Masks are items which can be", + "&7equipped to your helmet to", + "&7give it special effects and a", + "&7cool visual override.", + "", + "&7Each mask has it's own abilities", + "&7and can stack with other masks in", + "&7multi-masks. Which are simply", + "&7multiple masks inside one item") + .colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/language/Language.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/language/Language.java new file mode 100644 index 0000000..a479ef9 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/language/Language.java @@ -0,0 +1,98 @@ +package net.crankedpvp.crankedmasks.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + ADMIN_COMMAND_HELP, + INVALID_MASK, + ADMIN_RELOADING, + ADMIN_RELOADED, + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return value != null ? value : this.name(); + } + + public String getValue(UnaryOperator function) { + return value != null ? function.apply(value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(getValue(function)); + } + +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/language/LanguageHandler.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/language/LanguageHandler.java new file mode 100644 index 0000000..c0731d1 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.crankedmasks.language; + +import net.crankedpvp.crankedmasks.CrankedMasks; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final CrankedMasks plugin; + + public LanguageHandler(CrankedMasks plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/listeners/MaskListener.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/listeners/MaskListener.java new file mode 100644 index 0000000..6e2a2bd --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/listeners/MaskListener.java @@ -0,0 +1,206 @@ +package net.crankedpvp.crankedmasks.listeners; + +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedmasks.cooldown.MaskClickCooldown; +import net.crankedpvp.crankedmasks.events.MaskedItemEquipEvent; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.events.ArmorEquipEvent; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.InventoryClickUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class MaskListener implements Listener { + + @EventHandler(priority = EventPriority.HIGH) + public void onJoinWhileWearingMask(PlayerJoinEvent event) { + Player player = event.getPlayer(); + ItemStack helmet = player.getInventory().getHelmet(); + + if (!CrankedMasksAPI.itemHasMaskEquipped(helmet)) return; + + List masks = CrankedMasksAPI.getMasksOnItem(helmet); + + if (masks == null) return; + + for(Mask mask : masks) { + mask.onEquip(player); + } + } + + @EventHandler + public void onQuitWhileWearingMask(PlayerQuitEvent event) { + Player player = event.getPlayer(); + ItemStack helmet = player.getInventory().getHelmet(); + + if (!CrankedMasksAPI.itemHasMaskEquipped(helmet)) return; + + List masks = CrankedMasksAPI.getMasksOnItem(helmet); + + if (masks == null) return; + + for(Mask mask : masks) mask.onUnequip(player); + } + + @EventHandler + public void onInteractWithMaskInHand(PlayerInteractEvent event) { + ItemStack itemStack = event.getItem(); + + if (ItemUtils.isAirOrNull(itemStack)) return; + if (itemStack.getType() != Material.SKULL_ITEM) return; + if (!CrankedMasksAPI.isMask(itemStack)) return; + + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onRemoveMask(InventoryClickEvent event) { + if (!ItemUtils.isHelmet(event.getCurrentItem())) return; + ItemStack clicked = event.getCurrentItem(); + //if(event.isCancelled()) return; + if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + if (event.getClick() != ClickType.RIGHT) return; + if (!ItemUtils.isAirOrNull(event.getCursor())) return; + if (CooldownUtils.isCooldownActive((Player) event.getWhoClicked(),"maskClickCooldown")) return; + CooldownUtils.registerCooldown((Player) event.getWhoClicked(), new MaskClickCooldown("maskClickCooldown", 1)); + if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + List masks = CrankedMasksAPI.getMasksOnItem(clicked); + + if (masks == null || masks.isEmpty()) return; + + Player player = ((Player) event.getWhoClicked()); + + event.setCancelled(true); + boolean isFounder = CrankedMasksAPI.hasFounderMask(clicked); + event.setCurrentItem(CrankedMasksAPI.remove(clicked)); + if(isFounder) { + event.setCursor(CrankedMasksAPI.buildFounderMask()); + } else if(masks.size() == 1) { + event.setCursor(masks.get(0).getItem()); + } else { + event.setCursor(masks.get(0).buildMultiMask(masks)); + } + + if (event.getSlotType() == InventoryType.SlotType.ARMOR && event.getRawSlot() == 5) + for(Mask mask : masks) mask.onUnequip(player); + } + + @EventHandler + public void onAttackWithMask(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getDamage() <= 0) return; + + if (!(event.getDamager() instanceof Player)) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + + LivingEntity victim = (LivingEntity) event.getEntity(); + Player attacker = (Player) event.getDamager(); + ItemStack helmet = attacker.getInventory().getHelmet(); + + if (!CrankedMasksAPI.itemHasMaskEquipped(helmet)) return; + + List masks = CrankedMasksAPI.getMasksOnItem(helmet); + + if (masks == null) return; + + for(Mask mask : masks) mask.onAttack(attacker, victim, event); + } + + @EventHandler + public void onAttackedWithMask(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getDamage() <= 0) return; + + if (!(event.getDamager() instanceof LivingEntity)) return; + if (!(event.getEntity() instanceof Player)) return; + + Player victim = (Player) event.getEntity(); + LivingEntity attacker = (LivingEntity) event.getDamager(); + ItemStack helmet = victim.getInventory().getHelmet(); + + if (!CrankedMasksAPI.itemHasMaskEquipped(helmet)) return; + + List masks = CrankedMasksAPI.getMasksOnItem(helmet); + + if (masks == null) return; + + for(Mask mask : masks) { + if (mask == null) continue; + mask.onAttacked(victim, attacker, event); + } + } + + @EventHandler + public void onMaskEquip(ArmorEquipEvent event) { + if (ItemUtils.isHelmet(event.getOldArmorPiece())) { + if (CrankedMasksAPI.itemHasMaskEquipped(event.getOldArmorPiece())) { + List masks = CrankedMasksAPI.getMasksOnItem(event.getOldArmorPiece()); + if (masks != null) + for(Mask mask : masks) mask.onUnequip(event.getPlayer()); + } + } + if (ItemUtils.isHelmet(event.getNewArmorPiece()) || ItemUtils.isSkull(event.getNewArmorPiece())) { + if (CrankedMasksAPI.itemHasMaskEquipped(event.getNewArmorPiece())) { + List masks = CrankedMasksAPI.getMasksOnItem(event.getNewArmorPiece()); + if (masks != null) { + MaskedItemEquipEvent maskedItemEquipEvent = new MaskedItemEquipEvent(event.getPlayer(), masks, event); + Bukkit.getPluginManager().callEvent(maskedItemEquipEvent); + if (!maskedItemEquipEvent.isCancelled()) for(Mask mask : masks) mask.onEquip(event.getPlayer()); + } + } + } + } + + @EventHandler + public void onMaskApply(InventoryClickEvent event) { + ItemStack cursor = event.getCursor(); + ItemStack clicked = event.getCurrentItem(); + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + + if (ItemUtils.isAirOrNull(cursor)) return; + if (!ItemUtils.isHelmet(clicked)) return; + if (CrankedMasksAPI.itemHasMaskEquipped(clicked)) return; + if (!CrankedMasksAPI.isMask(cursor)) return; + + List masks = CrankedMasksAPI.getMaskFromItem(cursor); + + if (masks == null) return; + + Player player = ((Player) event.getWhoClicked()); + + event.setCancelled(true); + boolean isFounder = CrankedMasksAPI.isFounderMask(cursor); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(event.getCursor())); + if(isFounder) { + event.setCurrentItem(CrankedMasksAPI.applyFounderMask(clicked)); + } else if(masks.size() == 1) { + event.setCurrentItem(masks.get(0).apply(clicked)); + } else { + event.setCurrentItem(masks.get(0).applyMulti(clicked, masks)); + } + player.updateInventory(); + + if (event.getSlotType() == InventoryType.SlotType.ARMOR && event.getRawSlot() == 5) + for(Mask mask : masks) mask.onEquip(player); + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/AntiSilenceMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/AntiSilenceMask.java new file mode 100644 index 0000000..657d824 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/AntiSilenceMask.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class AntiSilenceMask extends Mask { + @Override + public String getName() { + return "Anti Silence"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&f&lAnti Silence Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTdhNTljNGVmNmIxYjM3ZWIxMzFkMzU2MWQzZTg0MDJiYTM4YWQ4NGQ2NmQ0ZWIyN2Q1MDdlZGM4OGJiZjcifX19"; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&fAbilities:", + "&8 ● &f+10% Chance to block incoming silence", + "&8 ● &f-15% Incoming silence duration" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oFear a man who cannot be heard..", + "&7&oThey are waiting for their time", + "&7&oto strike, and it will be too late."); + } + + @Override + public void onEquip(Player player) { + } + + @Override + public void onUnequip(Player player) { + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/BossMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/BossMask.java new file mode 100644 index 0000000..128f09b --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/BossMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class BossMask extends Mask { + @Override + public String getName() { + return "Boss"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&6&lBoss Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDRiOTc4ZTM0YTAyN2VhYzE2Mzc2NDQ4YWY2NmY5MDVkYzAwN2NjOGZhYjFlM2E0MzM4ODVlOTJhZmUzOGY3NSJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&6Abilities:", + "&8 ● &6+15% Outgoing damage to bosses", + "&8 ● &6-20% Incoming damage to bosses" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7A seasoned monster hunter, you pride", + "&7yourself on your boss slaying record."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/BunnyMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/BunnyMask.java new file mode 100644 index 0000000..af4b7ff --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/BunnyMask.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class BunnyMask extends Mask { + @Override + public String getName() { + return "Bunny"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&d&lBunny Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTIxNjJkY2VmZmFjOTU3NDI5OGY5N2MyN2E3YWMyMzg2N2NjNTczYTlhMmYxNzg5ZDNkYjc2ZWE0ZDhlZDE1OSJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&dAbilities:", + "&8 ● &dPermanent Jump Boost III Effect" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oHippity Hoppity your set is", + "&7&onow my property.. thanks.", + " &7- &7&oBugs Bunny"); + } + + @Override + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.JUMP, 2, "BunnyMask"); + } + + @Override + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "BunnyMask"); + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/CoyoteMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/CoyoteMask.java new file mode 100644 index 0000000..618a0f0 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/CoyoteMask.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedmasks.masks; + + + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class CoyoteMask extends Mask { + @Override + public String getName() { + return "Coyote"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&6&lCoyote Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvY2Q4NTZhNWM0MGU4ZTcyMDY0ZmQ5YmVmOGVjOTBhODZlZTEzMGE0ZGE0YmVlYWJkYmRiNjM0YjcyMmJjYjBiYSJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&6Abilities:", + "&8 ● &6Immune to cactus" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oThe coyote hunts its prey in", + "&7&ostyle, a silent predator.."); + } + + @Override + public void onEquip(Player player) { + } + + @Override + public void onUnequip(Player player) { + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/DreamMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/DreamMask.java new file mode 100644 index 0000000..1402028 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/DreamMask.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class DreamMask extends Mask { + @Override + public String getName() { + return "Dream"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&d&lDream Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYzg0ODMwNzlkNzAyOWUzNDhlMWJjMmMwN2MzMjIyODBlMTNmM2FhMjlhM2ZhZmViZDdhNGExZmJmYzMwODczMSJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&dAbilities:", + "&8 ● &dImmune to (Nightmare) Headless Ability" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7The attraction of the future..", + "&7All men of action are dreamers."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/GhostMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/GhostMask.java new file mode 100644 index 0000000..0ae65d7 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/GhostMask.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class GhostMask extends Mask { + @Override + public String getName() { + return "Ghost"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&8&lGhost Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0aW1lc3RhbXAiOjE1NDAzNTY0MjgwMjAsInByb2ZpbGVJZCI6ImEzOWVmNTdhMzg3YzRjZDE5NzQwNTliNzMyZWJjN2E1IiwicHJvZmlsZU5hbWUiOiJNZXJjaGFudCIsInRleHR1cmVzIjp7IlNLSU4iOnsidXJsIjoiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS8xMDVjNDg3NjllY2MzMjg4YWJkYjcyMThlYmZmMzEyZGNhMmEyOGJjZmNkMjlkMGFjMjk5YWNjMjMyM2VhNzhjIn19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&8Abilities:", + "&8 ● &8Immune to /invsee", + "&8 ● &8Invisible on /near" + + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oNo one knows what or how", + "&7&ohe looks. Some call him the", + "&7&oghost of crankedpvp."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/LeviathanMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/LeviathanMask.java new file mode 100644 index 0000000..32dd162 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/LeviathanMask.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class LeviathanMask extends Mask { + @Override + public String getName() { + return "Leviathan"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&3&lLeviathan Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDIzOGYxYzM0OGQ4ZDNlOTJiYTk5YmM4NTUxNDVmOWZkODM3ZWVlN2E0NjA1OWYxYThjNjE1Mjk0Mjg5YzkzMiJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&3Abilities:", + "&8 ● &3Immune to enemy kraken pet" + + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oA primordial sea serpent", + "&7&othat harnesses the power of", + "&7&othe kraken so that it cannot", + "&7&obe used to destroy you"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/MonopolyMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/MonopolyMask.java new file mode 100644 index 0000000..111b23d --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/MonopolyMask.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class MonopolyMask extends Mask { + @Override + public String getName() { + return "Monopoly"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&b&lMonopoly Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTExOThkYTBhOTg4NWJjM2I1OGMyNzg2MGQ0Mjc0MTQwOTllOGI0OTViYTkyYTU5MjFlZDVkNGUyN2E4YzMwZCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&bAbilities:", + "&8 ● &b33% Holy White Scroll negation" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7The mask of a man who has it all,", + "&7a truly powerful entity to contest with"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/NewSantaMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/NewSantaMask.java new file mode 100644 index 0000000..2369317 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/NewSantaMask.java @@ -0,0 +1,46 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class NewSantaMask extends Mask { + @Override + public String getName() { + return "Santa"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&c&lSanta Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0aW1lc3RhbXAiOjE1Mzk2ODUyNDc4MjgsInByb2ZpbGVJZCI6ImM3ZmRkYjlhYWRmZDRiZTNiMzI2ZDcwMGRmMjUyZTg4IiwicHJvZmlsZU5hbWUiOiJTYW50YSIsInRleHR1cmVzIjp7IlNLSU4iOnsidXJsIjoiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS8zZjg2NjgyMWJmYmY1MWMwNWZmNzk4YWYxMDk1NzVhZmZhMThjNzc5MTUxODEwYjUyZTk5YzU0N2MzMzc5ZWI3In19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&cAbilities:", + "&8 ● &c2x Chance for Santas Beard star item to proc" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList("&7&oAn eerie mask imbued with", "&7&oChristmas Joy that knows", "&7&owho is naughty or nice."); + } + + @Override + public void onEquip(Player player) { + } + + @Override + public void onUnequip(Player player) { + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/PartyMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/PartyMask.java new file mode 100644 index 0000000..697ef82 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/PartyMask.java @@ -0,0 +1,69 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class PartyMask extends Mask { + @Override + public String getName() { + return "Party"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&d&lParty Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZTJmNTYzOGMyMTNlYTJhNWE5NGU2NTk4MTY2YmM0N2VlZWI0MGY1ZGY4NGRhNzBjZDkyMzNjMTgxMmRmMTEwIn19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&dAbilities:", + "&8 ● &d-5% Incoming Damage", + "&8 ● &d+2.5% Outgoing Damage" + + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oThere is always time for", + "&7&oa party but you should also", + "&7&ocreate time for more parties."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } + + @Override + public void onAttacked(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(5, event, "Party Mask"); + } + } + + @Override + public void onAttack(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + super.getDamageHandler().increaseDamage(2.5, event, "Party Mask"); + } + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/PurgeMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/PurgeMask.java new file mode 100644 index 0000000..885cd75 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/PurgeMask.java @@ -0,0 +1,61 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class PurgeMask extends Mask { + @Override + public String getName() { + return "Purge"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&c&lPurge Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGJlNTgwNWViN2M4MjVhZmQxZjMyOTI4ZDY4ODU1YTQzNTIyNjgzYTViMGMyYzhmN2M5M2M1ZDBiOTAzYjhmMSJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&cAbilities:", + "&8 ● &c+2.5% Outgoing Damage" + + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oYou're going to Camp Blood, ain't ya?", + "&7&oYou'll never come back again.", + "&7&oIt's got a death curse!"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } + + @Override + public void onAttack(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + super.getDamageHandler().increaseDamage(2.5, event, "Purge Mask"); + } + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/ReindeerMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/ReindeerMask.java new file mode 100644 index 0000000..48a12eb --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/ReindeerMask.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class ReindeerMask extends Mask { + @Override + public String getName() { + return "Reindeer"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&a&lReindeer Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZWJkNDZiMzhiMjFiMzQyY2FmOTE3YWQ5Y2E0MmFmYjY4Mzg4YTU1OTFiY2M5YWRlZDFlOGUzNDZlMTg4OTAifX19"; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&aAbilities:", + "&8 ● &aPermanent Speed IV Effect" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oThe forecast this Christmas", + "&7&ois cloudy with a chance", + "&7&oof reindeer buddies."); + } + + @Override + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "ReindeerMask"); + } + + @Override + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "ReindeerMask"); + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/SantaMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/SantaMask.java new file mode 100644 index 0000000..8c6264c --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/SantaMask.java @@ -0,0 +1,49 @@ +package net.crankedpvp.crankedmasks.masks; + + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class SantaMask extends Mask { + @Override + public String getName() { + return "Santa"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&c&lSanta Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0aW1lc3RhbXAiOjE1Mzk2ODUyNDc4MjgsInByb2ZpbGVJZCI6ImM3ZmRkYjlhYWRmZDRiZTNiMzI2ZDcwMGRmMjUyZTg4IiwicHJvZmlsZU5hbWUiOiJTYW50YSIsInRleHR1cmVzIjp7IlNLSU4iOnsidXJsIjoiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS8zZjg2NjgyMWJmYmY1MWMwNWZmNzk4YWYxMDk1NzVhZmZhMThjNzc5MTUxODEwYjUyZTk5YzU0N2MzMzc5ZWI3In19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&cAbilities:", + "&8 ● &c+2 Max Hearts" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList("&7&oAn eerie mask imbued with", "&7&oChristmas Joy that knows", "&7&owho is naughty or nice."); + } + + @Override + public void onEquip(Player player) { + //PotionEffectUtils.addExtraPotionEffect(player, PotionEffectType.HEALTH_BOOST, 1, "SantaMask"); + } + + @Override + public void onUnequip(Player player) { + //PotionEffectUtils.removePotionEffect(player, "SantaMask"); + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/TinkerMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/TinkerMask.java new file mode 100644 index 0000000..b597131 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/TinkerMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class TinkerMask extends Mask { + @Override + public String getName() { + return "Tinker"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&e&lTinker Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZmFhYjJmZDAzN2MzOTk3MTAxYmNmNWNkNDgzODQwNDk0ZmFlMjEzMmViYWY5MjM0MmQ5YmUxZTRiOGI2N2VjIn19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&eAbilities:", + "&8 ● &e1.5x EXP Multiplier" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oYou can't cheat the game, you can't", + "&7&ocheat the grind. You get out what you", + "&7&oput in at the end of the day."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/UnderworldMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/UnderworldMask.java new file mode 100644 index 0000000..f9075fd --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/UnderworldMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class UnderworldMask extends Mask { + @Override + public String getName() { + return "Underworld"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&4&lUnderworld Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTRkNDEyZDhhNmI5NmNkN2FhYTgzMjJlZjc1ZmY1ZjQ0Yzc4ODhjZjMyMjQwYWQ4YzkyM2E1OGNlYTc0MDdhNiJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&4Abilities:", + "&8 ● &4+10% Outgoing damage to underworld mobs", + "&8 ● &4-10% Incoming damage from underworld mobs" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7You aim to roam the lands of the underworld", + "&7without having to look over your shoulder.."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/VampireMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/VampireMask.java new file mode 100644 index 0000000..f28c835 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/VampireMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class VampireMask extends Mask { + @Override + public String getName() { + return "Vampire"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&4&lVampire Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGQ0NDc1NmUwYjRlY2U4ZDc0NjI5NmEzZDVlMjk3ZTE0MTVmNGJhMTc2NDdmZmUyMjgzODUzODNkMTYxYTkifX19"; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&4Abilities:", + "&8 ● &4Immune to Lifesteal" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oI have never met a vampire", + "&7&opersonally, but I don't know", + "&7&owhat might happen tomorrow"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/WitchMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/WitchMask.java new file mode 100644 index 0000000..2ea3fde --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/WitchMask.java @@ -0,0 +1,69 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class WitchMask extends Mask { + @Override + public String getName() { + return "Witch"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&d&lWitch Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjEwMDVlY2I2OGIzZGY3MThlNzQwYjk5NGE2M2I4ODM2NDk0YTQ5OTJkMzYzZWEzODAxYzM5YjZhZTM2N2M2OCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&dAbilities:", + "&8 ● &dChance to give enemies potion debuffs", + "&8 ● &dEnemy debuffs have a chance to heal you" + + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7Those who don't believe in magic,", + "&7will never find it.."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } + + @Override + public void onAttack(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + if(ThreadLocalRandom.current().nextInt(201) == 1) { + Player victimPlayer = (Player) victim; + PotionEffectUtils.addPotionEffect(victimPlayer, PotionEffectType.SLOW, 1, "Witch Mask", 5); + PotionEffectUtils.addPotionEffect(victimPlayer, PotionEffectType.SLOW_DIGGING, 1, "Witch Mask", 5); + PotionEffectUtils.addPotionEffect(victimPlayer, PotionEffectType.WITHER, 1, "Witch Mask", 5); + } + } + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/ZeusMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/ZeusMask.java new file mode 100644 index 0000000..e71a54d --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/ZeusMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class ZeusMask extends Mask { + @Override + public String getName() { + return "Zeus"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&b&lZeus Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZGNkOWRkZjRmYjllMjVlNjJkMmU5ODU5NWQ1MTY4ZGUyYjMzNjdiYTc4ZjM2OTdiZTFjNDc5ZjM1MTAyYWQ3NiJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&bAbilities:", + "&8 ● &bImmune to Nature Warth" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oLord Zeus, erm. Uncle, please", + "&7&oaccept this offering from me", + "&7&oand all my gratitude."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BandageMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BandageMask.java new file mode 100644 index 0000000..fd384bf --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BandageMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class BandageMask extends Mask { + @Override + public String getName() { + return "Bandage"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&6&lBandage Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTY0ZTRiODc0Y2RmN2IyNWFhMmIyODdlMmE3MDYzZDA4MmU2NGY5ZmYxNTEwYzEyMjY5MDUzNDhlMDA1YzNlIn19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&6Abilities:", + "&f ● Immune to Bleed effects." + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"That which does not kill us, makes us", + "&fstronger\"", + " &7- &oFriedrich Nietzsche"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BossMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BossMask.java new file mode 100644 index 0000000..79045da --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BossMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class BossMask extends Mask { + @Override + public String getName() { + return "Boss"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&6&lBoss Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDRiOTc4ZTM0YTAyN2VhYzE2Mzc2NDQ4YWY2NmY5MDVkYzAwN2NjOGZhYjFlM2E0MzM4ODVlOTJhZmUzOGY3NSJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&6Abilities:", + "&8 ● &6+15% Outgoing damage to bosses", + "&8 ● &6-20% Incoming damage to bosses" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7A seasoned monster hunter, you pride", + "&7yourself on your boss slaying record."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BunnyMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BunnyMask.java new file mode 100644 index 0000000..2c66ee3 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/BunnyMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class BunnyMask extends Mask { + @Override + public String getName() { + return "Bunny"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&d&lBunny Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTIxNjJkY2VmZmFjOTU3NDI5OGY5N2MyN2E3YWMyMzg2N2NjNTczYTlhMmYxNzg5ZDNkYjc2ZWE0ZDhlZDE1OSJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&dAbilities:", + "&f ● Gain a 1.25x Increased Spawner Rate within a chunk" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"Of course you realize, this means", + "&fwar\"", + " &7- &7&oBugs Bunny"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/CarverMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/CarverMask.java new file mode 100644 index 0000000..a63228a --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/CarverMask.java @@ -0,0 +1,50 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class CarverMask extends Mask { + @Override + public String getName() { + return "Carver"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&6&lCarver Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZTM0YTM2NzUyZmYxNjAzNTAwZDJiMDNhMDBlZjc4M2RmZTA5OGRkNGY3N2Q4MmI4MzcwODBiOWUxYzExM2IxZCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&6Abilities:", + "&f ● Immune to Halloweenify." + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"My body is different, I can take your soul\"", + " &7- &oSleepy Hallow"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/DavyJonesMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/DavyJonesMask.java new file mode 100644 index 0000000..b7fb73e --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/DavyJonesMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class DavyJonesMask extends Mask { + @Override + public String getName() { + return "Davy Jones"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&5&lDavy Jones Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTU2ZWM3MGYwNDQxYzdkMWYwM2ZjOTcwOWZkZjcwZTU1OGY3ZDJlYzE5MWQzNzMwYjhjMDYyMWJlZjg5OWVkZSJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&5Abilities:", + "&f ● 33% Chance to negate Holy White Scrolls" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"Are you prepared for what comes after", + "&fdeath?\"", + " &7- &oDavy Jones"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/FishermanMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/FishermanMask.java new file mode 100644 index 0000000..64a418a --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/FishermanMask.java @@ -0,0 +1,61 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class FishermanMask extends Mask { + @Override + public String getName() { + return "Fisherman"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&e&lFisherman Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDgwNGU0MmVjOWIwN2ZjZTFjZTAwNThiNzhkZjU3NjNmNmU0MTBkOWNlODJlZjFlYmI5NTk3YTE1MmI2ZDRjOCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&eAbilities:", + "&f ● Immune to being attacked by a fishing rod.", + "&f ● Enjoy a 5% damage reduction." + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"Not a scam. It's called fishing, not", + "&fphishing.\"", + " &7- &oFishing Businessman"); + } + + @Override + public void onAttacked(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(5, event, this.getName()); + } + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/GhostMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/GhostMask.java new file mode 100644 index 0000000..a27a251 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/GhostMask.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class GhostMask extends Mask { + @Override + public String getName() { + return "Ghost"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&9&lGhost Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTgxOTc3OTE4YTExODBlMGRlYzg3OWU2YmNkMWFhMzk0OTQ5NzdiYjkxM2JlMmFiMDFhZmYxZGIxZmE0In19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&9Abilities:", + "&f ● Immune to /invsee." + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"A lot of hard work is hidden behind", + "&fnice things.\"", + " &7- &7&oRalph Lauren"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/LeviathanMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/LeviathanMask.java new file mode 100644 index 0000000..9cdd389 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/LeviathanMask.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class LeviathanMask extends Mask { + @Override + public String getName() { + return "Leviathan"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&3&lLeviathan Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDIzOGYxYzM0OGQ4ZDNlOTJiYTk5YmM4NTUxNDVmOWZkODM3ZWVlN2E0NjA1OWYxYThjNjE1Mjk0Mjg5YzkzMiJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&3Abilities:", + "&8 ● &3Immune to enemy kraken pet" + + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&7&oA primordial sea serpent", + "&7&othat harnesses the power of", + "&7&othe kraken so that it cannot", + "&7&obe used to destroy you"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/MidasMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/MidasMask.java new file mode 100644 index 0000000..40cd31b --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/MidasMask.java @@ -0,0 +1,66 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class MidasMask extends Mask { + @Override + public String getName() { + return "Midas"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&6&lMidas Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODE4Mzg2YjBlZmE2ZjhjY2Q0OGZjZTg5ZTdkYzU2NGU2YTQ2OTc0YzNhZTU3MjdhYWRmODM3ZDNmZGE2NTk2NCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&6Abilities:", + "&f ● +5% outgoing damage to opponents using heroic weapons", + "&f ● Ignores Sharpness VI damage from oponents" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"Shall we turn the Earth to gold? The", + "&frivers, the mountains, the stars, the", + "&fmoon, the sky... a universe of gold! - ", + "&fKing Midas\"", + " &7- &7&oMidas"); + } + + @Override + public void onAttack(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + if(CrankedArmorAPI.isWeaponHeroic(((Player) victim).getItemInHand())) { + super.getDamageHandler().increaseDamage(5, event, this.getName()); + } + } + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/PantherMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/PantherMask.java new file mode 100644 index 0000000..eb6bc3c --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/PantherMask.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class PantherMask extends Mask { + @Override + public String getName() { + return "Panther"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&8&lPanther Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTdlMDJiNDI5YzhjZTRmZmZkZWQ4MTkxNjU1NGZkM2RmYmI5MmQxNTc1ZTVmMmU0MWJkNTE1M2I1OGUxOCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&8Abilities:", + "&f ● Immutable to Nitro's Tactical Nuke.", + "&f ● Absorb damage and release it in bursts periodically" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"In life, death is not the end. It's", + "&fmore of a stepping off point. You", + "&freach out with both hands you are", + "&fled into a green veld where you can", + "&frun forever.\"", + " &7- &7&oT'Challa"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/ParrotMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/ParrotMask.java new file mode 100644 index 0000000..3563af2 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/ParrotMask.java @@ -0,0 +1,55 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class ParrotMask extends Mask { + @Override + public String getName() { + return "Parrot"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&6&lParrot Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWRmNGIzNDAxYTRkMDZhZDY2YWM4YjVjNGQxODk2MThhZTYxN2Y5YzE0MzA3MWM4YWMzOWE1NjNjZjRlNDIwOCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&6Abilities:", + "&f ● Permanent Speed III effect", + "&f ● Rocket Escape III effect" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"The bird who dares to fall is the", + "&fbird who learns to fly\"", + " &7- &7&oA bird"); + } + + @Override + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 3, this.getName()); + } + + @Override + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, this.getName()); + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/PartyMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/PartyMask.java new file mode 100644 index 0000000..1784b21 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/PartyMask.java @@ -0,0 +1,69 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class PartyMask extends Mask { + @Override + public String getName() { + return "Party"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&d&lParty Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZTJmNTYzOGMyMTNlYTJhNWE5NGU2NTk4MTY2YmM0N2VlZWI0MGY1ZGY4NGRhNzBjZDkyMzNjMTgxMmRmMTEwIn19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&dAbilities:", + "&f ● Deal an extra 2.5% more damage", + "&f ● Enjoy a 5% damage reduction." + + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&fThere is always time for", + "&fa party but you should also", + "&fcreate time for more parties."); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } + + @Override + public void onAttacked(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(5, event, this.getName()); + } + } + + @Override + public void onAttack(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + super.getDamageHandler().increaseDamage(2.5, event, this.getName()); + } + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/SantaMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/SantaMask.java new file mode 100644 index 0000000..1703eaa --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/SantaMask.java @@ -0,0 +1,52 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class SantaMask extends Mask { + @Override + public String getName() { + return "Santa"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&c&lSanta Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0aW1lc3RhbXAiOjE1Mzk2ODUyNDc4MjgsInByb2ZpbGVJZCI6ImM3ZmRkYjlhYWRmZDRiZTNiMzI2ZDcwMGRmMjUyZTg4IiwicHJvZmlsZU5hbWUiOiJTYW50YSIsInRleHR1cmVzIjp7IlNLSU4iOnsidXJsIjoiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS8zZjg2NjgyMWJmYmY1MWMwNWZmNzk4YWYxMDk1NzVhZmZhMThjNzc5MTUxODEwYjUyZTk5YzU0N2MzMzc5ZWI3In19fQ=="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&cAbilities:", + "&f ● +2 Max Hearts" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"Better get your milk and cookies out!", + "&fHo ho ho!\"", + " &7- &7&oSanta Claus"); + } + + @Override + public void onEquip(Player player) { + //PotionEffectUtils.addExtraPotionEffect(player, PotionEffectType.HEALTH_BOOST, 1, "SantaMask"); + } + + @Override + public void onUnequip(Player player) { + //PotionEffectUtils.removePotionEffect(player, "SantaMask"); + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/SorcererMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/SorcererMask.java new file mode 100644 index 0000000..a99724b --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/SorcererMask.java @@ -0,0 +1,53 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class SorcererMask extends Mask { + @Override + public String getName() { + return "Sorcerer"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&3&lSorcerer Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjkzMTk1MjU4MjVmMWYzMDcyN2ViOTQwZDNhMDY0MjZiYzRjZWMwN2ZiZDgwYWY1Y2QxNDZlM2ViMzg3OWY2OCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&3Abilities:", + "&f ● Wither and poison damage has a chance to heal the wearer." + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"Healing is not a process enacted by", + "&fsorcery alone. The patient must fight", + "&fat least as hard as the physician, if", + "&fnot much harder.\"", + " &7- &7&oPaul Krueger"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/TinkerMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/TinkerMask.java new file mode 100644 index 0000000..15be614 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/TinkerMask.java @@ -0,0 +1,52 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class TinkerMask extends Mask { + @Override + public String getName() { + return "Tinker"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&e&lTinker Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTdlMDJiNDI5YzhjZTRmZmZkZWQ4MTkxNjU1NGZkM2RmYmI5MmQxNTc1ZTVmMmU0MWJkNTE1M2I1OGUxOCJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&eAbilities:", + "&f ● Receive up to a a 1.45x XP Multiplier." + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"You can't cheat the game. You can't", + "&fcheat the grind. You get out what you", + "&fput in at the end of the day\"", + " &7- &7&oDaBaby"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/VampireMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/VampireMask.java new file mode 100644 index 0000000..4b87da6 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/VampireMask.java @@ -0,0 +1,52 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class VampireMask extends Mask { + @Override + public String getName() { + return "Vampire"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&4&lVampire Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGQ0NDc1NmUwYjRlY2U4ZDc0NjI5NmEzZDVlMjk3ZTE0MTVmNGJhMTc2NDdmZmUyMjgzODUzODNkMTYxYTkifX19"; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&4Abilities:", + "&f ● Immune to Lifesteal", + "&f ● Increased Lifesteal Proc Chance" + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&f\"When them vamps outside, lil' b****,", + "&fyou better be ready. \"", + " &7- &7&oPlayboi Carti"); + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/ZoidMask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/ZoidMask.java new file mode 100644 index 0000000..3ac22cc --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/masks/cadia/ZoidMask.java @@ -0,0 +1,62 @@ +package net.crankedpvp.crankedmasks.masks.cadia; + +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class ZoidMask extends Mask { + @Override + public String getName() { + return "Zoid"; + } + + @Override + protected String getDefaultDisplayName() { + return CC.translate("&5&lZoid Mask"); + } + + @Override + protected String getDefaultTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZTU4MjZiYTUwMTVkNjE2NjM0YjYyYmQxZGM2MWZhOTJlMTIxZDQ1MzIyNmQ4ZDc4MGVlMjFhMTg0MWE2ZDdjMyJ9fX0="; + } + + @Override + protected List getDefaultPerks() { + return Arrays.asList( + "&5Abilities:", + "&f ● Immune to the Exotic Bone.", + "&f ● Enjoy a 2.5% damage reduction." + ); + } + + @Override + protected List getDefaultLore() { + return Arrays.asList( + "&fThis mask will make you a king against", + "&fthose who consider themselves hardcore.", + "&5&oViper Nest" + ); + } + + @Override + public void onAttacked(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(2.5, event, this.getName()); + } + } + + @Override + public void onEquip(Player player) { + + } + + @Override + public void onUnequip(Player player) { + + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/Mask.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/Mask.java new file mode 100644 index 0000000..add507c --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/Mask.java @@ -0,0 +1,161 @@ +package net.crankedpvp.crankedmasks.struct; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.ChatColor; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +public abstract class Mask implements Listener { + + @ConfigValue + private String displayName; + @ConfigValue + private String texture; + @ConfigValue + private List perks; + @ConfigValue + private List lore; + + @Getter + private final DamageHandler damageHandler; + @Getter + private final CrankedMasks crankedMasks; + + public Mask() { + this.damageHandler = CrankedUtils.instance.getDamageHandler(); + this.crankedMasks = CrankedMasks.getInstance(); + } + + public abstract String getName(); + + protected abstract String getDefaultDisplayName(); + + protected abstract String getDefaultTexture(); + + protected abstract List getDefaultPerks(); + + protected abstract List getDefaultLore(); + + public String getDisplayName() { + return displayName == null ? getDefaultDisplayName() : displayName; + } + + public String getTexture() { + return texture == null ? getDefaultTexture() : texture; + } + + public List getPerks() { + return perks == null ? getDefaultPerks() : perks; + } + + public List getLore() { + return lore == null ? getDefaultLore() : lore; + } + + public void initializeConfigDefaults() { + displayName = getDefaultDisplayName(); + texture = getDefaultTexture(); + perks = getDefaultPerks(); + lore = getDefaultLore(); + } + + public void onAttack(Player attacker, Entity victim, EntityDamageByEntityEvent event) {} + + public void onAttacked(Player victim, Entity attacker, EntityDamageByEntityEvent event) {} + + public void onEquip(Player player) {} + + public void onUnequip(Player player) {} + + public String getID() { + return this.getName().toLowerCase(Locale.ROOT).replace(" ", ""); + } + + public ItemStack apply(ItemStack item) { + item = new ItemBuilder(item).addLore("&7&lATTACHED: " + this.getDisplayName()).colorize().build(); + + NBTItem wrapper = new NBTItem(item); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + cosmicData.setString("maskType", this.getID()); + return wrapper.getItem(); + } + + public ItemStack applyMulti(ItemStack item, List masks) { + String multiMaskNames = masks.stream().map(Mask::getDisplayName).collect(Collectors.joining("&f&l, ")); + item = new ItemBuilder(item).addLore("&7&lATTACHED: " + multiMaskNames).colorize().build(); + + NBTItem wrapper = new NBTItem(item); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + String maskIds = masks.stream().map(Mask::getID).collect(Collectors.joining(",")); + cosmicData.setString("maskType", maskIds); + return wrapper.getItem(); + } + + public ItemStack getItem() { + ItemStack skull = SkullUtils.getSkull(this.getTexture()); + skull = new ItemBuilder(skull).setName(this.getDisplayName()) + .addLore(this.getLore()) + .addLore("") + .addLore(this.getPerks()) + .addLore("") + .addLore("&7&oAttach this mask to any helmet") + .addLore("&7&oto give it a visual override!") + .addLore("") + .addLore("&7To attach, place this mask on a helmet.") + .addLore("&7To unattach, right-click helmet while attached.") + .colorize() + .build(); + NBTItem wrapper = new NBTItem(skull); + wrapper.setString("cosmicType", "mask"); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + cosmicData.setString("maskType", this.getID()); + return wrapper.getItem(); + } + + public ItemStack buildMultiMask(List masks) { + ItemStack skull = SkullUtils.getSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNjM4YzUzZTY2ZjI4Y2YyYzdmYjE1MjNjOWU1ZGUxYWUwY2Y0ZDdhMWZhZjU1M2U3NTI0OTRhOGQ2ZDJlMzIifX19"); + String multiMaskNames = masks.stream().map(Mask::getDisplayName).collect(Collectors.joining("&f&l, ")); + ItemBuilder itemBuilder = new ItemBuilder(skull).setName("&f&lMulti-Mask (" + multiMaskNames + "&f&l)").setLore(""); + + masks.forEach(mask -> { + itemBuilder.addLoreLine(mask.getDisplayName()); + mask.getPerks().forEach(itemBuilder::addLoreLine); + itemBuilder.addLore(""); + }); + + + itemBuilder + .addLore("&7&oAttach this mask to any helmet") + .addLore("&7&oto give it a visual override!") + .addLore("") + .addLore("&7To attach, place this mask on a helmet.") + .addLore("&7To unattach, right-click helmet while attached."); + + List lore = itemBuilder.getLore(); + lore.removeIf(line -> line.contains(ChatColor.stripColor("Abilities:"))); + itemBuilder.setLore(lore); + itemBuilder.colorize().build(); + + NBTItem wrapper = new NBTItem(skull); + wrapper.setString("cosmicType", "mask"); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + String maskIds = masks.stream().map(Mask::getID).collect(Collectors.joining(",")); + cosmicData.setString("maskType", maskIds); + return wrapper.getItem(); + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/MasksRegister.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/MasksRegister.java new file mode 100644 index 0000000..cd8cc06 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/MasksRegister.java @@ -0,0 +1,78 @@ +package net.crankedpvp.crankedmasks.struct; + +import lombok.Getter; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.masks.*; +import org.bukkit.Bukkit; + +import javax.annotation.Nullable; +import java.util.*; + +public class MasksRegister { + + @Getter + private static MasksRegister instance; + private final Map masks; + + + public MasksRegister() { + instance = this; + this.masks = new HashMap<>(); + } + + public void initialize() { + this.registerAll( + new BossMask(), new DreamMask(), new GhostMask(), new LeviathanMask(), new MonopolyMask(), + new PartyMask(), new PurgeMask(), new ReindeerMask(), new TinkerMask(), + new VampireMask(), new WitchMask(), new ZeusMask(), new BunnyMask(), new AntiSilenceMask(), new CoyoteMask(), + new NewSantaMask() + ); + } + + public void registerAll(Mask... Masks) { + for (Mask set : Masks) { + this.register(set); + } + } + + public void register(Mask mask) { + try { + this.masks.put(mask.getID(), mask); + CrankedMasks.getInstance().getServer().getPluginManager().registerEvents(mask, CrankedMasks.getInstance()); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register mask " + mask.getID()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.masks.clear(); + } + + public void unregister(Mask mask) { + this.masks.remove(mask.getID()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isMask(String name) { + return (this.getMaskFromID(name) != null); + } + + @Nullable + public Mask getMaskFromID(String id) { + if (!this.masks.containsKey(id)) return null; + return this.masks.get(id.toLowerCase()); + } + + public String getMaskIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getMasks() { + return Collections.unmodifiableCollection(this.masks.values()); + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/annotations/ConfigValue.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/annotations/ConfigValue.java new file mode 100644 index 0000000..bb6f5a8 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/annotations/ConfigValue.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedmasks.struct.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * don't forget to not make the field final when using this annotation + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigValue { + + String path() default "mask."; + String name() default ""; + +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/config/MaskConfig.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/config/MaskConfig.java new file mode 100644 index 0000000..3e0b0e5 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/config/MaskConfig.java @@ -0,0 +1,129 @@ +package net.crankedpvp.crankedmasks.struct.config; + +import lombok.AccessLevel; +import lombok.Getter; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedmasks.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +@Getter +public class MaskConfig { + + @Getter(value = AccessLevel.PRIVATE) + private final CrankedMasks plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + private final Mask mask; + + public MaskConfig(CrankedMasks plugin, String path, Mask mask) { + this.plugin = plugin; + this.path = path; + this.mask = mask; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public void setupConfigFile() { + this.createDefaultFile(); + this.reloadConfig(); + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path); + e.printStackTrace(); + } + return false; + } + + public void createDefaultFile() { + if (!configFile.exists()) { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path); + e.printStackTrace(); + } + } + } + + public void reloadConfig() { + if (this.loadConfigFromDisk()) { + this.loadVariables(); + } + } + + public boolean loadConfigFromDisk() { + try { + FileConfiguration loadedConfig = new YamlConfiguration(); + loadedConfig.load(configFile); + config = loadedConfig; + return true; + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path); + e.printStackTrace(); + } + return false; + } + + public void loadVariables() { + boolean needSave = false; + this.mask.initializeConfigDefaults(); + for (Class type = mask.getClass(); type != null; type = type.getSuperclass()) { + for (Field field : type.getDeclaredFields()) { + if (!field.isAnnotationPresent(ConfigValue.class)) continue; + ConfigValue annotationValue = field.getAnnotation(ConfigValue.class); + String name = annotationValue.name().isEmpty() ? field.getName() : annotationValue.name(); + String prefix = annotationValue.path(); + String valuePath = prefix.isEmpty() || prefix.endsWith(".") ? prefix + name : prefix + "." + name; + try { + field.setAccessible(true); + if (!this.config.contains(valuePath)) { + Object defaultValue = field.get(this.mask); + if (defaultValue instanceof String) { + defaultValue = ((String) defaultValue).replace('\u00a7', '&'); + } + this.config.set(valuePath, defaultValue); + needSave = true; + } + Object fieldValue = this.config.get(valuePath); + if (fieldValue instanceof String) { + fieldValue = CC.translate((String) fieldValue); + } else if (List.class.isAssignableFrom(field.getType())) { + if (!(fieldValue instanceof List)) { + throw new IllegalArgumentException("Expected a list of strings"); + } + List translated = new ArrayList<>(); + for (Object line : (List) fieldValue) { + if (!(line instanceof String)) { + throw new IllegalArgumentException("Expected a list of strings"); + } + translated.add(CC.translate((String) line)); + } + fieldValue = translated; + } + field.set(this.mask, fieldValue); + } catch (IllegalAccessException | IllegalArgumentException e) { + plugin.getLogger().warning("Invalid config value for " + path + " at " + valuePath + ": " + e.getMessage()); + } + } + } + if (needSave) { + saveConfig(); + } + } +} diff --git a/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/config/MaskConfigManager.java b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/config/MaskConfigManager.java new file mode 100644 index 0000000..cce8198 --- /dev/null +++ b/Masks/src/main/java/net/crankedpvp/crankedmasks/struct/config/MaskConfigManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedmasks.struct.config; + +import lombok.Getter; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.struct.Mask; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class MaskConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public MaskConfigManager(CrankedMasks plugin) { + for (Mask mask : plugin.getMasksRegister().getMasks()) { + MaskConfig maskConfig = new MaskConfig(plugin, "masks/" + mask.getID() + ".yml", mask); + configs.put(mask, maskConfig); + } + } + + public void setupFiles() { + configs.values().forEach(MaskConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(MaskConfig::reloadConfig); + } + + public MaskConfig getAbstractConfig(Mask mask) { + return configs.get(mask); + } + + public FileConfiguration getConfig(Mask mask) { + return getAbstractConfig(mask).getConfig(); + } +} diff --git a/Masks/src/main/resources/language.yml b/Masks/src/main/resources/language.yml new file mode 100644 index 0000000..3c6bd0f --- /dev/null +++ b/Masks/src/main/resources/language.yml @@ -0,0 +1,9 @@ +INVALID_MASK: "&c&l(!)&c Invalid mask name." + +ADMIN_COMMAND_HELP: + - "&8--- &3Cranked &fMasks &8---" + - "&3/cm &fmask &7 [player]" + + +ADMIN_RELOADING: "&3&l(!) &7Reloading configs now..." +ADMIN_RELOADED: "&3&l(!) &7Reloaded configs and other cool stuff. Took &3%took%ms&7." diff --git a/Masks/src/main/resources/plugin.yml b/Masks/src/main/resources/plugin.yml new file mode 100644 index 0000000..7d0320a --- /dev/null +++ b/Masks/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedMasks +main: net.crankedpvp.crankedmasks.CrankedMasks +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - ProtocolLib \ No newline at end of file diff --git a/MonthlyCrates/pom.xml b/MonthlyCrates/pom.xml new file mode 100644 index 0000000..bef96c7 --- /dev/null +++ b/MonthlyCrates/pom.xml @@ -0,0 +1,26 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + MonthlyCrates + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + + \ No newline at end of file diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/MonthlyCratesPlugin.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/MonthlyCratesPlugin.java new file mode 100644 index 0000000..421a5cd --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/MonthlyCratesPlugin.java @@ -0,0 +1,73 @@ +package net.crankedpvp.monthlycrates; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.monthlycrates.commands.MonthlyCrateCommand; +import net.crankedpvp.monthlycrates.commands.ViewCrateOpenCommand; +import net.crankedpvp.monthlycrates.listeners.MonthlyCrateListener; +import net.crankedpvp.monthlycrates.managers.MonthlyCrateManager; +import net.crankedpvp.monthlycrates.struct.LootType; +import net.crankedpvp.monthlycrates.struct.MonthlyCrate; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.stream.Collectors; + +public class MonthlyCratesPlugin extends JavaPlugin { + + @Getter + private static MonthlyCratesPlugin instance; + + @Getter + private MonthlyCrateManager monthlyCrateManager; + + @Getter + private CommandManager commandManager; + + @Override + public void onEnable() { + + instance = this; + this.monthlyCrateManager = new MonthlyCrateManager(this); + this.monthlyCrateManager.createDefaultConfig("-example"); + this.monthlyCrateManager.initializeAll(); + + this.commandManager = new CommandManager(this); + this.registerCommandParameters(); + this.registerCommandCompletion(); + this.commandManager.register(new MonthlyCrateCommand(this)); + this.commandManager.register(new ViewCrateOpenCommand(this)); + this.registerListeners(); + + + + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new MonthlyCrateListener(this), this); + } + + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(LootType.class, argument -> { + LootType lootType = LootType.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(lootType, argument); + }); + } + + public void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#monthlycrates", input -> this.monthlyCrateManager.getMonthlyCrates().values() + .stream().map(MonthlyCrate::getId).collect(Collectors.toList())); + } + + @Override + public void onDisable() { + instance = null; + this.monthlyCrateManager = null; + this.commandManager = null; + } + + +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/commands/MonthlyCrateCommand.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/commands/MonthlyCrateCommand.java new file mode 100644 index 0000000..66cbab6 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/commands/MonthlyCrateCommand.java @@ -0,0 +1,231 @@ +package net.crankedpvp.monthlycrates.commands; + +import lombok.SneakyThrows; +import net.crankedpvp.monthlycrates.MonthlyCratesPlugin; +import net.crankedpvp.monthlycrates.inventory.AdminInventory; +import net.crankedpvp.monthlycrates.managers.MonthlyCrateManager; +import net.crankedpvp.monthlycrates.struct.LootType; +import net.crankedpvp.monthlycrates.utils.Base64; +import net.crankedpvp.monthlycrates.utils.Utils; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.File; +import java.io.IOException; + +@Command("monthlycrate") +@Alias({"monthlycrates", "crankedcrate", "cc"}) +public class MonthlyCrateCommand extends CommandBase { + + private final MonthlyCratesPlugin plugin; + private final MonthlyCrateManager monthlyCrateManager; + public MonthlyCrateCommand(MonthlyCratesPlugin plugin) { + this.plugin = plugin; + this.monthlyCrateManager = plugin.getMonthlyCrateManager(); + } + + @Default + @Permission("cranked.admin") + public void defaultCommand(CommandSender commandSender) { + Player player = (Player)commandSender; + AdminInventory adminInventory = new AdminInventory(player); + adminInventory.getUI().open(player); + } + + @SubCommand("list") + @Permission("cranked.admin") + public void listCommand(CommandSender commandSender) { + Player player = (Player)commandSender; + commandSender.sendMessage(""); + commandSender.sendMessage(Utils.fixColor("&bMonthly Crates")); + this.monthlyCrateManager.getMonthlyCrateObjects().forEach(monthlyCrate -> commandSender.sendMessage(Utils.fixColor(" &b* &f" + monthlyCrate.getId()))); + player.playSound(player.getLocation(), Sound.FIREWORK_LAUNCH, 2.0F, 2.0F); + } + + @SubCommand("reload") + @Permission("cranked.admin") + public void reloadCommand(CommandSender commandSender, @Optional @Completion("#monthlycrates") String monthlycrate) { + Player sender = (Player) commandSender; + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + if (monthlycrate == null) { + this.monthlyCrateManager.clearMonthlyCrateMap(); + this.monthlyCrateManager.initializeAll(); + sender.sendMessage(Utils.fixColor("&aYou have successfully reloaded all monthlycrates")); + return; + } + + this.monthlyCrateManager.reloadMonthlyCrate(monthlycrate); + sender.sendMessage(Utils.fixColor("&aYou have successfully reloaded the " + monthlycrate + " monthlycrate")); + + } + + @SubCommand("create") + @Permission("cranked.admin") + public void createCommand(CommandSender commandSender, String name) { + Player sender = (Player)commandSender; + if (this.monthlyCrateManager.isMonthlyCrate(name)) { + sender.sendMessage(Utils.fixColor("&cThis is already a registered monthly crate")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + this.monthlyCrateManager.createDefaultConfig(name); + this.monthlyCrateManager.initialize(name); + sender.sendMessage(Utils.fixColor("&aSuccessfully created the monthlycrate of name: " + name)); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @SubCommand("delete") + @Permission("cranked.admin") + public void deleteCommand(CommandSender commandSender, @Completion("#monthlycrates") String name) { + Player player = (Player)commandSender; + if (this.monthlyCrateManager.isMonthlyCrate(name)) { + this.monthlyCrateManager.removeMonthlyCrate(name); + this.monthlyCrateManager.deleteConfig(name); + player.sendMessage(Utils.fixColor("&cYou have deleted the monthlycrate of name: " + name)); + player.playSound(player.getLocation(), Sound.ANVIL_BREAK, 2.0F, 2.0F); + } else { + player.sendMessage(Utils.fixColor("&cThat is not a valid monthlycrate")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + } + + @SubCommand("addreward") + @Alias({"additem", "addloot"}) + @Permission("cranked.admin") + @WrongUsage("/monthlycrate additem [monthlycrate] [chance] [loot-type]") + public void addItemCommand(CommandSender commandSender, @Completion("#monthlycrates") final String name, final Double chance, @Completion("#enum") final LootType lootType) throws IOException { + + Player player = (Player)commandSender; + File file = new File(this.plugin.getDataFolder() + "/MonthlyCrates/" + name + ".yml"); + if(file.exists()) { + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file); + String itemName = ChatColor.stripColor(player.getItemInHand().getItemMeta().getDisplayName()).replace(".", "").replace(" ", ""); + String toBase64 = Base64.serialize(player.getItemInHand()); + if(!yamlConfiguration.contains("rewards") || !yamlConfiguration.getConfigurationSection("rewards").getKeys(true).contains(itemName + player.getItemInHand().getAmount())) { + yamlConfiguration.set("rewards." + itemName + player.getItemInHand().getAmount() + ".item", toBase64); + yamlConfiguration.set("rewards." + itemName + player.getItemInHand().getAmount() + ".chance", chance); + yamlConfiguration.set("rewards." + itemName + player.getItemInHand().getAmount() + ".loot-type", lootType.name()); + yamlConfiguration.set("rewards." + itemName + player.getItemInHand().getAmount() + ".special-name", player.getItemInHand().getItemMeta().getDisplayName()); + yamlConfiguration.save(file); + player.sendMessage(Utils.fixColor("&aAdded Item to monthlycrate: " + name)); + player.playSound(player.getLocation(), Sound.LEVEL_UP, 2.0F, 2.0F); + this.monthlyCrateManager.reloadMonthlyCrate(name); + } else { + player.sendMessage(Utils.fixColor("&cThis item is already in the monhtlycrate")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + } + } + + @SneakyThrows + @SubCommand("removereward") + @Alias({"removeitem", "removeloot"}) + @Permission("cranked.admin") + @WrongUsage("/monthlycrate removeitem [monthlycrate]") + public void removeItemCommand(CommandSender commandSender, @Completion("#monthlycrates") String name) { + Player player = (Player)commandSender; + ItemStack itemStack = player.getItemInHand(); + File file = new File(this.plugin.getDataFolder() + "/MonthlyCrates/" + name + ".yml"); + if (file.exists()) { + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(file); + String itemName = ChatColor.stripColor(itemStack.getItemMeta().getDisplayName()).replace(".", "").replace(" ", ""); + if (!yamlConfiguration.contains("rewards")) { + player.sendMessage(Utils.fixColor("&cThis monthlycrate does not have this reward in")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + if (yamlConfiguration.getConfigurationSection("rewards").getKeys(true).contains(itemName + itemStack.getAmount())) { + yamlConfiguration.set("rewards." + itemName + itemStack.getAmount(), null); + yamlConfiguration.save(file); + player.sendMessage(Utils.fixColor("&aSuccessfully removed item from monthlycrate")); + player.playSound(player.getLocation(), Sound.CHICKEN_EGG_POP, 2.0F, 2.0F); + this.monthlyCrateManager.reloadMonthlyCrate(name); + } else { + player.sendMessage(Utils.fixColor("&cThis monthlycrate does not have this reward in")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + } + } + } + + + @SubCommand("give") + @Permission("cranked.admin") + public void giveCommand(CommandSender commandSender, @Completion("#players") final Player player, @Completion("#monthlycrates") final String name, Integer amount) { + if (!player.isOnline()) { + commandSender.sendMessage(Utils.fixColor("&cThat player is not online")); + if(commandSender instanceof Player) + ((Player)commandSender).playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + if (!this.monthlyCrateManager.isMonthlyCrate(name)) { + commandSender.sendMessage(Utils.fixColor("&cThe crate by name " + name + " is not a valid crate")); + if(commandSender instanceof Player) + ((Player)commandSender).playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + amount = (amount <= 0) ? 1 : amount; + player.getInventory().addItem(this.monthlyCrateManager.getMonthlyCrate(name).createMonthlyCrate(amount, player)); + commandSender.sendMessage(Utils.fixColor("&cGiven monthlycrate to " + player.getName())); + player.sendMessage(Utils.fixColor("&cReceived the " + name + " monthlycrate")); + player.playSound(player.getLocation(), Sound.ITEM_PICKUP, 2.0F, 2.0F); + } + + @SubCommand("disable") + @Permission("cranked.admin") + public void disableCommand(CommandSender commandSender, @Completion("#monthlycrates") String name) { + if (!this.monthlyCrateManager.isMonthlyCrate(name)) + return; + File file = new File(this.plugin.getDataFolder() + "/MonthlyCrates/" + name + ".yml"); + if (file.renameTo(new File(this.plugin.getDataFolder() + "/MonthlyCrates/-" + name + ".yml"))) { + this.monthlyCrateManager.removeMonthlyCrate(name); + commandSender.sendMessage(Utils.fixColor("&cDisabled monthlycrate: " + name)); + Player player = (Player)commandSender; + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 2.0F); + } + } + + @SubCommand("enable") + @Permission("cranked.admin") + public void enableCommand(CommandSender commandSender, String name) { + if (this.monthlyCrateManager.isMonthlyCrate(name)) + return; + File file = new File(this.plugin.getDataFolder() + "/MonthlyCrates/-" + name + ".yml"); + if (file.renameTo(new File(this.plugin.getDataFolder() + "/MonthlyCrates/" + name + ".yml"))) { + this.monthlyCrateManager.initialize(name); + commandSender.sendMessage(Utils.fixColor("&aEnabled monthlycrate: " + name)); + Player player = (Player)commandSender; + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + } + + @SubCommand("help") + @Permission("cranked.admin") + public void helpMessage(CommandSender commandSender) { + commandSender.sendMessage(Utils.fixColor("&a-------[ &2MonthlyCrates &a]-------")); + commandSender.sendMessage(Utils.fixColor("&a[] &8- &7Optional argument")); + commandSender.sendMessage(Utils.fixColor("&2<> &8- &7Required argument")); + commandSender.sendMessage(""); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc create ")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc delete ")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc enable ")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc disable ")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc additem ")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc removeitem ")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc reload [monthlycrate]")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc list")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/mc give ")); + commandSender.sendMessage(Utils.fixColor("&a-------[ &2MonthlyCrates &a]-------")); + if(commandSender instanceof Player) { + Player player = (Player) commandSender; + player.playSound(player.getLocation(), Sound.LEVEL_UP, 2.0F, 2.0F); + } + } + +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/commands/ViewCrateOpenCommand.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/commands/ViewCrateOpenCommand.java new file mode 100644 index 0000000..2e49299 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/commands/ViewCrateOpenCommand.java @@ -0,0 +1,37 @@ +package net.crankedpvp.monthlycrates.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.monthlycrates.MonthlyCratesPlugin; +import net.crankedpvp.monthlycrates.inventory.MonthlyCrateInventory; +import net.crankedpvp.monthlycrates.managers.MonthlyCrateManager; +import org.bukkit.entity.Player; + +import java.util.UUID; + +@Command("viewcrateopen") +public class ViewCrateOpenCommand extends CommandBase { + + private final MonthlyCratesPlugin plugin; + public ViewCrateOpenCommand(MonthlyCratesPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player, String crateID) { + MonthlyCrateManager monthlyCrateManager = this.plugin.getMonthlyCrateManager(); + if(!monthlyCrateManager.getMonthlyCrateBeingOpened().containsKey(UUID.fromString(crateID))) return; + + MonthlyCrateInventory monthlyCrateInventory = monthlyCrateManager.getMonthlyCrateBeingOpened().get(UUID.fromString(crateID)); + if(!monthlyCrateInventory.isActive()) { + player.sendMessage(CC.translate("&d&lMonthly Crates &8" + Arrow.arrow() + " &eThat monthly crate has finished opened")); + SoundUtils.tryPlayErrorSound(player); + return; + } + monthlyCrateManager.getMonthlyCrateBeingOpened().get(UUID.fromString(crateID)).getUI().open(player); + } +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/inventory/AdminInventory.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/inventory/AdminInventory.java new file mode 100644 index 0000000..e80af13 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/inventory/AdminInventory.java @@ -0,0 +1,55 @@ +package net.crankedpvp.monthlycrates.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.monthlycrates.MonthlyCratesPlugin; +import net.crankedpvp.monthlycrates.struct.MonthlyCrate; +import net.crankedpvp.monthlycrates.utils.ItemBuilder; +import net.crankedpvp.monthlycrates.utils.Utils; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Map; + +public class AdminInventory { + private final PaginatedGui adminInventory; + + public PaginatedGui getUI() { + return this.adminInventory; + } + + Map monthlyCrateMap = MonthlyCratesPlugin.getInstance().getMonthlyCrateManager().getMonthlyCrates(); + + public AdminInventory(Player player) { + this.adminInventory = new PaginatedGui(6, 36, "Cranked Monthly Crates"); + this.adminInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.adminInventory.getFiller().fillBottom(new GuiItem(createFillerItem())); + ItemStack prevPage = new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.").colorize().build(); + ItemStack nextPage = new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.").colorize().build(); + this.adminInventory.setItem(6, 1, new GuiItem(prevPage, event -> { + this.adminInventory.previous(); + event.setCancelled(true); + })); + this.adminInventory.setItem(6, 9, new GuiItem(nextPage, event -> { + this.adminInventory.next(); + event.setCancelled(true); + })); + for (MonthlyCrate monthlyCrate : this.monthlyCrateMap.values()) { + ItemStack item = monthlyCrate.createMonthlyCrate(1, player); + this.adminInventory.addItem(new GuiItem(item, event -> { + if(player.hasPermission("cranked.admin")) player.getInventory().addItem(item); + })); + } + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(Utils.fixColor("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/inventory/MonthlyCrateInventory.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/inventory/MonthlyCrateInventory.java new file mode 100644 index 0000000..92d17f1 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/inventory/MonthlyCrateInventory.java @@ -0,0 +1,162 @@ +package net.crankedpvp.monthlycrates.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.monthlycrates.MonthlyCratesPlugin; +import net.crankedpvp.monthlycrates.struct.LootType; +import net.crankedpvp.monthlycrates.struct.MonthlyCrate; +import net.crankedpvp.monthlycrates.utils.Utils; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +public class MonthlyCrateInventory { + + private final int amountOfRewards; + + @Getter + private boolean active = true; + + private final MonthlyCratesPlugin plugin = MonthlyCratesPlugin.getInstance(); + + private final Gui adminInventory; + + public Gui getUI() { + return this.adminInventory; + } + + @Getter + private final Map taskBySlot = new HashMap<>(); + + private int spinningItems = 0; + private int spunItems = 0; + + private boolean openedMystery = false; + + private final ItemStack[] preDefinedRewards; + private final ItemStack preDefinedBonusReward; + + public MonthlyCrateInventory(Player player, MonthlyCrate monthlyCrate) { + this.amountOfRewards = monthlyCrate.getAmountOfRewards(); + this.preDefinedRewards = new ItemStack[monthlyCrate.getAmountOfRewards()]; + for(int i = 0; i < this.amountOfRewards; i++) + this.preDefinedRewards[i] = (monthlyCrate.getRandomItemWithBlacklist(Collections.singletonList(LootType.BONUS))); + this.preDefinedBonusReward = monthlyCrate.getRandomItemWithWhitelist(Collections.singletonList(LootType.BONUS)); + this.adminInventory = new Gui(6, "Monthly Crate: " + monthlyCrate.getId()); + this.adminInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.adminInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(inventoryCloseEvent.getPlayer() != player) return; + this.active = false; + player.getInventory().addItem(preDefinedBonusReward); + Arrays.stream(preDefinedRewards).forEach(reward -> player.getInventory().addItem(reward)); + + for(HumanEntity viewer : this.adminInventory.getInventory().getViewers()) { + this.adminInventory.close(viewer); + } + }); + this.adminInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.adminInventory.getFiller().fillBetweenPoints(5, 1, 5, 9, new GuiItem(createFillerItem())); + this.adminInventory.getFiller().fill(new GuiItem(createMysteryItem(), event -> { + if(event.getWhoClicked() != player) return; + if(spinningItems >= this.amountOfRewards) return; + updateItemTask(event.getSlot(), monthlyCrate, spinningItems, player); + spinningItems++; + })); + + for(int i = 48; i < 51; i++) { + this.adminInventory.updateItem(i, new GuiItem(createBlockedItem())); + } + } + + private void allowOpeningOfBonusItems(MonthlyCrate monthlyCrate, Player player) { + for(int i = 48; i < 51; i++) { + int finalI = i; + this.adminInventory.updateItem(i, new GuiItem(createMysteryBonusItem(), event -> { + if(event.getWhoClicked() != player) return; + if(!openedMystery) { + this.adminInventory.updateItem(finalI, new GuiItem(this.preDefinedBonusReward)); + player.playSound(player.getLocation(), Sound.FIREWORK_LARGE_BLAST, 2.0F, 2.0F); + plugin.getServer().getScheduler().runTaskLater(plugin, () -> { + for(int j = 48; j < 51; j++) { + if(j != finalI) + this.adminInventory.updateItem(j, new GuiItem(monthlyCrate.getRandomItemWithWhitelist(Collections.singletonList(LootType.BONUS)))); + } + }, 20L); + plugin.getServer().getScheduler().runTaskLater(plugin, () -> { + player.playSound(player.getLocation(), Sound.CHEST_CLOSE, 2.0F, 2.0F); + player.closeInventory(); + }, 40L); + } + openedMystery = true; + this.active = false; + })); + } + } + + private ItemStack createMysteryBonusItem() { + ItemStack item = new ItemStack(Material.ENDER_CHEST); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(Utils.fixColor("&d&l???")); + item.setItemMeta(meta); + return item; + } + + private void updateItemTask(int slot, MonthlyCrate monthlyCrate, int index, Player player) { + AtomicInteger counter = new AtomicInteger(); + this.taskBySlot.put(slot, plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, () -> { + if(!player.getOpenInventory().getTopInventory().getTitle().contains("Monthly Crate")) plugin.getServer().getScheduler().cancelTask(this.taskBySlot.get(slot));; + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 1.0F, 1.0F); + this.adminInventory.updateItem(slot, new GuiItem(monthlyCrate.getRandomItemWithBlacklist(Collections.singletonList(LootType.BONUS)))); + counter.getAndIncrement(); + if(counter.get() == 35) { + plugin.getServer().getScheduler().cancelTask(this.taskBySlot.get(slot)); + this.plugin.getServer().getScheduler().runTaskLater(plugin, () -> this.adminInventory.updateItem(slot, new GuiItem(this.preDefinedRewards[index])), 5L); + spunItems++; + if(spunItems == this.amountOfRewards) { + player.playSound(player.getLocation(), Sound.FIREWORK_LAUNCH, 2.0F, 2.0F); + this.plugin.getServer().getScheduler().runTaskLater(plugin, () -> { + allowOpeningOfBonusItems(monthlyCrate, player); + player.playSound(player.getLocation(), Sound.CLICK, 1.0F, 1.0F); + }, 20L); + } + } + }, 0L, 3L)); + } + + private ItemStack createBlockedItem() { + ItemStack item = new ItemStack(Material.BARRIER); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(Utils.fixColor("&c&lWAIT")); + meta.setLore(Collections.singletonList(Utils.fixColor("&7Open " + (this.amountOfRewards-spinningItems) + " mystery items first"))); + item.setItemMeta(meta); + return item; + } + + private ItemStack createMysteryItem() { + ItemStack item = new ItemStack(Material.ENDER_CHEST); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(Utils.fixColor("&f&l???")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(Utils.fixColor("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/listeners/MonthlyCrateListener.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/listeners/MonthlyCrateListener.java new file mode 100644 index 0000000..89cd10d --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/listeners/MonthlyCrateListener.java @@ -0,0 +1,74 @@ +package net.crankedpvp.monthlycrates.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.Clickable; +import net.crankedpvp.monthlycrates.MonthlyCratesPlugin; +import net.crankedpvp.monthlycrates.inventory.MonthlyCrateInventory; +import net.crankedpvp.monthlycrates.managers.MonthlyCrateManager; +import net.crankedpvp.monthlycrates.struct.MonthlyCrate; +import net.crankedpvp.monthlycrates.utils.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +public class MonthlyCrateListener implements Listener { + + private final MonthlyCratesPlugin plugin; + public MonthlyCrateListener(MonthlyCratesPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onPlayerInteract(PlayerInteractEvent event) { + if(event.getAction() == null) return; + if(event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_AIR) return; + if(event.getItem() == null) return; + + ItemStack itemStack = event.getItem(); + if(!MonthlyCrateManager.isMonthlyCrate(itemStack)) return; + + event.setCancelled(true); + NBTItem nbtItem = new NBTItem(itemStack); + MonthlyCrate monthlyCrate = this.plugin.getMonthlyCrateManager().getMonthlyCrate(nbtItem.getString("monthlyCrateType")); + + if(!Utils.hasAvaliableSlot(event.getPlayer(), 10)) { + event.getPlayer().sendMessage(Utils.fixColor("&cYour inventory does not have enough open slots to open this")); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.LAVA_POP, 1.0F, 1.0F); + return; + } + + int amount = itemStack.getAmount(); + if (amount <= 1) { + event.getPlayer().setItemInHand(null); + } else { + itemStack.setAmount(amount - 1); + event.getPlayer().setItemInHand(itemStack); + } + + MonthlyCrateInventory monthlyCrateInventory = new MonthlyCrateInventory(event.getPlayer(), monthlyCrate); + monthlyCrateInventory.getUI().open(event.getPlayer()); + + UUID uuid = UUID.randomUUID(); + this.plugin.getMonthlyCrateManager().getMonthlyCrateBeingOpened().put(uuid, monthlyCrateInventory); + + Clickable clickable = new Clickable("&f✧ &eClick to watch &6" + event.getPlayer().getName() + " &eopen a " + monthlyCrate.getDisplayName(), "&eClick to view &6" + event.getPlayer().getName() + "'s &emonthlycrate &f✧", "/viewcrateopen " + uuid); + clickable.add(CC.translate("&eYou can purchase this monthlycrate at &fbuy.crankedpvp.org&e!")); + for(Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.sendMessage(""); + clickable.sendToPlayer(onlinePlayer); + onlinePlayer.sendMessage(""); + } + } + + + + +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/managers/MonthlyCrateManager.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/managers/MonthlyCrateManager.java new file mode 100644 index 0000000..358f0bf --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/managers/MonthlyCrateManager.java @@ -0,0 +1,184 @@ +package net.crankedpvp.monthlycrates.managers; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Maps; +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.monthlycrates.MonthlyCratesPlugin; +import net.crankedpvp.monthlycrates.inventory.MonthlyCrateInventory; +import net.crankedpvp.monthlycrates.struct.LootType; +import net.crankedpvp.monthlycrates.struct.MonthlyCrate; +import net.crankedpvp.monthlycrates.struct.Reward; +import net.crankedpvp.monthlycrates.utils.Base64; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemStack; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +public class MonthlyCrateManager { + + private final MonthlyCratesPlugin plugin; + public MonthlyCrateManager(MonthlyCratesPlugin plugin) { + this.plugin = plugin; + this.monthlyCrates = Maps.newConcurrentMap(); + this.monthlyCrateBeingOpened = Maps.newConcurrentMap(); + } + + @Getter + private final Map monthlyCrates; + + @Getter + private final Map monthlyCrateBeingOpened; + + public void initializeAll() { + File[] files = (new File(this.plugin.getDataFolder(), "MonthlyCrates")).listFiles(); + assert files != null; + Arrays.stream(files) + .filter(file -> !file.getName().startsWith("-")) + .filter(file -> file.getName().endsWith(".yml")) + .forEach(file -> { + try { + initialize(file.getName().replace(".yml", "")); + } catch (NullPointerException exception) { + System.out.println("[MonthlyCrates] Failed to register monthlycrate: " + file.getName().replace(".yml", "")); + } + }); + } + + public void initialize(String name) { + File file = new File(this.plugin.getDataFolder(), "MonthlyCrates/" + name + ".yml"); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + try { + yamlConfiguration.load(file); + } catch (IOException |org.bukkit.configuration.InvalidConfigurationException e) { + e.printStackTrace(); + } + String displayName = yamlConfiguration.getString("Item.Display.Name"); + List displayLore = yamlConfiguration.getStringList("Item.Display.Lore"); + Material material = Material.valueOf(yamlConfiguration.getString("Item.Material").toUpperCase()); + boolean glowing = yamlConfiguration.getBoolean("Item.Glowing"); + List rewards = getRewards(yamlConfiguration); + int amountOfRewards = yamlConfiguration.contains("Reward.Amount") ? yamlConfiguration.getInt("Reward.Amount") : 0; + MonthlyCrate monthlyCrate = new MonthlyCrate(name, displayName, displayLore, material, glowing, amountOfRewards, rewards); + this.register(monthlyCrate); + System.out.println("[MonthlyCrates] Registered monthlycrate: " + name); + } + + private List getRewards(FileConfiguration fileConfiguration) { + List rewards = new ArrayList<>(); + if (fileConfiguration.getConfigurationSection("rewards") == null) return rewards; + fileConfiguration.getConfigurationSection("rewards").getKeys(false).forEach(key -> { + ItemStack itemStack = null; + try { + itemStack = Base64.deserialize(fileConfiguration.getConfigurationSection("rewards." + key).getString("item").replace("\r\n", "")); + } catch (IOException|ClassNotFoundException e) { + e.printStackTrace(); + } + Reward reward = new Reward(itemStack, fileConfiguration.getConfigurationSection("rewards." + key).getDouble("chance"), LootType.valueOf(fileConfiguration.getConfigurationSection("rewards." + key).getString("loot-type").toUpperCase()), fileConfiguration.getConfigurationSection("rewards."+key).getString("special-name")); + rewards.add(reward); + }); + return rewards; + } + + public void createDefaultConfig(String name) { + File file = new File(this.plugin.getDataFolder(), "MonthlyCrates/" + name + ".yml"); + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + yamlConfiguration.set("Item.Display.Name", "&f&ki&r&5✧&f&ki&r &f&lCRANKED CRATE: &6&lExample &f&ki&r&5✧&f&ki&r"); + yamlConfiguration.set("Item.Display.Lore", Arrays.asList("&7&oUnlocked by %player% from &f&nbuy.crankedpvp.org", + "", + "&f&lADMIN ITEMS", + "%admin-rewards% %color-&f&l%", + "", + "&e&lCOSMETIC ITEMS", + "%cosmetic-rewards% %color-&e&l%", + "", + "&6&lTREASURE ITEMS", + "%treasure-rewards% %color-&6&l%", + "", + "&d&lBONUS ITEMS", + "%bonus-rewards% %color-&d&l%")); + yamlConfiguration.set("Item.Material", Material.ENDER_CHEST.name()); + yamlConfiguration.set("Item.Glowing", true); + yamlConfiguration.set("Reward.Amount", 9); + try { + yamlConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void reloadMonthlyCrate(String monthlycrate) { + if (isMonthlyCrate(monthlycrate)) { + removeMonthlyCrate(monthlycrate); + initialize(monthlycrate); + } else { + System.out.println("[-] Failure reloading monthlycrate, " + monthlycrate); + } + } + + public void register(MonthlyCrate monthlyCrate) { + try { + this.monthlyCrates.put(monthlyCrate.getId(), monthlyCrate); + this.plugin.getLogger().info("Successfully registered monthlyCrate: " + monthlyCrate.getId()); + } catch (Exception var3) { + System.err.println("&8(&c!&8) Failed to register monthlyCrate, " + monthlyCrate.getId()); + } + } + + public boolean isMonthlyCrate(String name) { + return (getMonthlyCrate(name) != null); + } + + public MonthlyCrate getMonthlyCrate(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + return this.monthlyCrates.get(name); + } + + public void clearMonthlyCrateMap() { + this.monthlyCrates.clear(); + } + + public void removeMonthlyCrate(String monthlycrate) { + this.monthlyCrates.remove(monthlycrate); + } + + public Collection getMonthlyCrateObjects() { + return Collections.unmodifiableCollection(this.monthlyCrates.values()); + } + + public MonthlyCrate select(Collection monthlyCrateCollection) { + return (monthlyCrateCollection.size() > 0) ? ImmutableList.copyOf(monthlyCrateCollection).get(ThreadLocalRandom.current().nextInt(monthlyCrateCollection.size())) : null; + } + + public static boolean isMonthlyCrate(ItemStack itemStack) { + if (itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if (nbtItem.hasNBTData()) { + if (nbtItem.hasKey("crankedCustomItem")) { + return nbtItem.getString("crankedCustomItem").equalsIgnoreCase("monthlyCrate"); + } + } + return false; + } + + public void deleteConfig(String name) { + File file = new File(this.plugin.getDataFolder(), "MonthlyCrates/" + name + ".yml"); + if (file.exists()) + file.delete(); + } +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/LootType.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/LootType.java new file mode 100644 index 0000000..ae9069f --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/LootType.java @@ -0,0 +1,12 @@ +package net.crankedpvp.monthlycrates.struct; + +public enum LootType { + + ADMIN, + COSMETIC, + TREASURE, + BONUS, + RARE, + LEGENDARY + +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/MonthlyCrate.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/MonthlyCrate.java new file mode 100644 index 0000000..36ac163 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/MonthlyCrate.java @@ -0,0 +1,111 @@ +package net.crankedpvp.monthlycrates.struct; + +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.RandomUtils; +import net.crankedpvp.monthlycrates.utils.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +@Getter +public class MonthlyCrate { + + private final String id; + private final String displayName; + private final List lore; + private final Material material; + private final boolean glowing; + + private final int amountOfRewards; + + private final List rewards; + + public MonthlyCrate(String id, String displayName, List lore, Material material, boolean glowing, int amountOfRewards, List rewards) { + this.id = id; + this.displayName = displayName; + this.lore = lore; + this.material = material; + this.glowing = glowing; + this.amountOfRewards = amountOfRewards; + this.rewards = rewards; + } + + public MonthlyCrate(String id, String displayName, List lore, Material material, boolean glowing, List rewards) { + this.id = id; + this.displayName = displayName; + this.lore = lore; + this.material = material; + this.glowing = glowing; + this.amountOfRewards = 9; + this.rewards = rewards; + } + + + public List getLore(String playerName) { + List newLore = new ArrayList<>(); + for(String line : lore) { + if(line.contains("rewards%")) { + LootType lootType = LootType.valueOf(line.split("-")[0].toUpperCase().replace("%", "")); + Stream rewardStream = this.rewards.stream().filter(reward -> reward.getLootType() == lootType); + rewardStream.forEach(reward -> { + ItemStack itemStack = reward.getItemStack(); + //String amount = itemStack.getAmount() <= 1 ? "&f&l* " : "&f&l* " + itemStack.getAmount() + "x &r"; + String amount = "&f&l* " + itemStack.getAmount() + "x &r"; + amount = CC.translate(amount); + if(reward.getGetSpecialName() == null || reward.getGetSpecialName().equals("null")) { + newLore.add(amount + reward.getItemStack().getItemMeta().getDisplayName()); + } else { + newLore.add(amount + reward.getGetSpecialName()); + } + }); + } else { + newLore.add(line.replace("%player%", playerName).replace("%amount%", String.valueOf(this.amountOfRewards))); + } + } + return newLore; + } + + + public ItemStack createMonthlyCrate(int amount, Player player) { + String playerName = (player == null) ? "Console" : player.getName(); + ItemBuilder itemBuilder = new ItemBuilder(material, amount, (short)0, displayName).setLore(getLore(playerName)); + if(glowing) itemBuilder.setGlowing(); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "monthlyCrate"); + nbtItem.setString("monthlyCrateType", getId()); + return nbtItem.getItem(); + } + + public ItemStack createMonthlyCrate(int amount) { + return createMonthlyCrate(amount, null); + } + + public ItemStack createMonthlyCrate() { + return createMonthlyCrate(1); + } + + public ItemStack getRandomItemWithBlacklist(List blacklistedLootTypes) { + Map rewards = new HashMap<>(); + this.rewards.stream() + .filter(reward -> !blacklistedLootTypes.contains(reward.getLootType())) + .forEach(reward -> rewards.put(reward.getItemStack(), reward.getChance())); + return RandomUtils.getRandomItem(rewards); + } + + public ItemStack getRandomItemWithWhitelist(List whitelistedLootTypes) { + Map rewards = new HashMap<>(); + this.rewards.stream() + .filter(reward -> whitelistedLootTypes.contains(reward.getLootType())) + .forEach(reward -> rewards.put(reward.getItemStack(), reward.getChance())); + return RandomUtils.getRandomItem(rewards); + + } +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/Reward.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/Reward.java new file mode 100644 index 0000000..5f80a95 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/struct/Reward.java @@ -0,0 +1,16 @@ +package net.crankedpvp.monthlycrates.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.bukkit.inventory.ItemStack; + +@AllArgsConstructor +@Getter +public class Reward { + + private final ItemStack itemStack; + private final double chance; + private final LootType lootType; + private final String getSpecialName; + +} \ No newline at end of file diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/Base64.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/Base64.java new file mode 100644 index 0000000..e7d7d59 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/Base64.java @@ -0,0 +1,30 @@ +package net.crankedpvp.monthlycrates.utils; + +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class Base64 { + public static ItemStack deserialize(String base64) throws IOException, ClassNotFoundException { + byte[] data = Base64Coder.decodeLines(base64); + ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); + BukkitObjectInputStream in = new BukkitObjectInputStream(bytesIn); + ItemStack itemStack = (ItemStack) in.readObject(); + in.close(); + return itemStack; + } + + public static String serialize(ItemStack itemStack) throws IOException { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + BukkitObjectOutputStream out = new BukkitObjectOutputStream(bytesOut); + out.writeObject(itemStack); + out.flush(); + out.close(); + return Base64Coder.encodeLines(bytesOut.toByteArray()); + } +} \ No newline at end of file diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/ItemBuilder.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/ItemBuilder.java new file mode 100644 index 0000000..48fdbb7 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/ItemBuilder.java @@ -0,0 +1,250 @@ +package net.crankedpvp.monthlycrates.utils; + + + +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +public class ItemBuilder { + + private ItemMeta itemMeta; + private final ItemStack itemStack; + + public ItemBuilder(String material) { + this(Material.valueOf(material)); + } + + public ItemBuilder(Material material) { + this(material,1); + } + + public ItemBuilder(Material material, int amount) { + this(new ItemStack(material, amount)); + } + + public ItemBuilder(Material material, String name, String... lore) { + this(material, 1, (short) 0, name, lore); + } + + public ItemBuilder(Material material, int amount, short durability) { + this(new ItemStack(material, amount, durability)); + } + + public ItemBuilder(Material material, int amount, short durability, String name, String... lore) { + this(new ItemStack(material, amount, durability)); + setName(name); + setLore(lore); + } + + public ItemBuilder(ItemBuilder itemBuilder) { + this.itemStack = itemBuilder.itemStack; + this.itemMeta = itemBuilder.itemMeta; + } + + public ItemBuilder(ConfigurationSection section) { + this(new ItemBuilder(section.getString("name")) + .setLore(section.getStringList("lore")) + .setDurability((short) section.getInt("damage")) + .setUnbreakable(section.getBoolean("unbreakable")) + ); + } + + public ItemBuilder(ItemStack itemStack) { + this.itemStack = itemStack; + this.itemMeta = itemStack.getItemMeta(); + } + + public ItemBuilder clone() { + return new ItemBuilder(itemStack); + } + + public ItemBuilder setMaterial(String material) { + itemStack.setType(Material.valueOf(material)); + return this; + } + + public ItemBuilder setMaterial(Material material) { + itemStack.setType(material); + return this; + } + + public ItemBuilder setDurability(short durability) { + itemStack.setDurability(durability); + return this; + } + + public ItemBuilder setName(String name) { + itemMeta.setDisplayName(name); + return this; + } + + public ItemBuilder addUnsafeEnchantment(Enchantment enchantment, int level) { + itemStack.addUnsafeEnchantment(enchantment, level); + return this; + } + + public ItemBuilder removeEnchantment(Enchantment enchantment) { + itemStack.removeEnchantment(enchantment); + return this; + } + + public ItemBuilder addEnchantment(Enchantment enchantment, int level) { + itemMeta.addEnchant(enchantment, level,true); + return this; + } + + public ItemBuilder addEnchantments(Map enchantments) { + itemStack.addEnchantments(enchantments); + return this; + } + + public ItemBuilder setGlowing() { + if (itemMeta.hasEnchants()) return this; + itemMeta.addEnchant(Enchantment.DURABILITY,1,true); + return addItemFlag(ItemFlag.HIDE_ENCHANTS); + } + + public ItemBuilder colorize() { + colorizeName(); + return colorizeLore(); + } + + public ItemBuilder colorizeLore() { + if (itemMeta.hasLore()) { + List lore = getItemMeta().getLore(); + lore.replaceAll(Utils::fixColor); + return setLore(lore); + } + return this; + } + + public ItemBuilder colorizeName() { + if (itemMeta.hasDisplayName()) setName(Utils.fixColor(getItemMeta().getDisplayName())); + return this; + } + + public ItemBuilder setUnbreakable(boolean unbreakable) { + itemMeta.spigot().setUnbreakable(unbreakable); + return this; + } + + public List getLore() { + return itemMeta.getLore(); + } + + public ItemBuilder setLore(String... lore) { + return setLore(Arrays.asList(lore)); + } + + public ItemBuilder setLore(List lore) { + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder removeLoreLine(String line) { + List lore = new ArrayList<>(itemMeta.getLore()); + lore.remove(line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder removeLoreLine(int index) { + if (index < 0) return this; + List lore = new ArrayList<>(itemMeta.getLore()); + if (index > lore.size()) return this; + lore.remove(index); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addLoreLine(String line) { + List lore = new ArrayList<>(); + if(itemMeta.hasLore()) lore = new ArrayList<>(itemMeta.getLore()); + lore.add(line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addLoreLine(String line, int pos) { + List lore = new ArrayList<>(itemMeta.getLore()); + if (pos >= lore.size()) return this; + lore.set(pos, line); + itemMeta.setLore(lore); + return this; + } + + public ItemBuilder addItemFlags(List itemFlags) { + for (String itemFlagStr : itemFlags) { + try { + ItemFlag itemFlag = ItemFlag.valueOf(itemFlagStr); + addItemFlag(itemFlag); + } catch (IllegalArgumentException ignored) {} + } + return this; + } + + public ItemBuilder setItemFlags(List itemFlags) { + itemMeta.addItemFlags(itemFlags.toArray(new ItemFlag[0])); + return this; + } + + public ItemBuilder addItemFlag(ItemFlag itemFlag) { + itemMeta.addItemFlags(itemFlag); + return this; + } + + @SuppressWarnings("deprecation") + public ItemBuilder setColor(DyeColor color) { + itemStack.setDurability(color.getData()); + return this; + } + + public ItemBuilder setLeatherArmorColor(Color color) { + LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; + if (Bukkit.getItemFactory().isApplicable(leatherArmorMeta, itemStack)) { + leatherArmorMeta.setColor(color); + itemMeta = leatherArmorMeta; + } + return this; + } + + public ItemBuilder setSkullOwner(String owner) { + SkullMeta skullMeta = (SkullMeta) itemMeta; + if (Bukkit.getItemFactory().isApplicable(skullMeta, itemStack)) { + skullMeta.setOwner(owner); + itemMeta = skullMeta; + } + return this; + } + + public ItemMeta getItemMeta() { + return itemMeta; + } + + public ItemStack build() { + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + public ItemStack addNbt(String key, String string) { + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString(key, string); + return nbtItem.getItem(); + } + +} diff --git a/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/Utils.java b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/Utils.java new file mode 100644 index 0000000..befe239 --- /dev/null +++ b/MonthlyCrates/src/main/java/net/crankedpvp/monthlycrates/utils/Utils.java @@ -0,0 +1,24 @@ +package net.crankedpvp.monthlycrates.utils; + +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public class Utils { + public static String fixColor(String string) { + return ChatColor.translateAlternateColorCodes('&', string); + } + + public static boolean hasAvaliableSlot(Player player, int amount){ + int amountOpen = 0; + Inventory inv = player.getInventory(); + for (ItemStack item : inv.getContents()) { + if(item == null) { + amountOpen += 1; + } + } + return amountOpen >= amount; + } + +} diff --git a/MonthlyCrates/src/main/resources/plugin.yml b/MonthlyCrates/src/main/resources/plugin.yml new file mode 100644 index 0000000..156ec11 --- /dev/null +++ b/MonthlyCrates/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedMonthlyCrates +main: net.crankedpvp.monthlycrates.MonthlyCratesPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/Pets/pom.xml b/Pets/pom.xml new file mode 100644 index 0000000..1a86e67 --- /dev/null +++ b/Pets/pom.xml @@ -0,0 +1,68 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Pets + + + 8 + 8 + + + + + + net.crankedpvp + Utils + + + com.massivecraft + Factions + + + net.crankedpvp + CagePvP + + + net.crankedpvp + Masks + + + net.crankedpvp + Arcade + + + net.crankedpvp + StarItems + + + net.crankedpvp + Armor + + + net.crankedpvp + Leaderboards + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + com.golfing.wineSpigot + winespigot + 1.0 + system + ${project.basedir}/../.lib/WineSpigot-V1.4.4.3.jar + + + \ No newline at end of file diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/CollarAPI.java b/Pets/src/main/java/net/crankedpvp/crankedpets/CollarAPI.java new file mode 100644 index 0000000..83e58d2 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/CollarAPI.java @@ -0,0 +1,67 @@ +package net.crankedpvp.crankedpets; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class CollarAPI { + + public static ItemStack buildCollar(int amount) { + ItemBuilder itemBuilder = new ItemBuilder(Material.LEASH, amount, (short)0, "&6&lPet Collar", + "&7Drag n' Drop this collar onto", + "&7any inventory pet to ensure", + "&7it stays by your side after death"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "petCollar"); + return nbtItem.getItem(); + } + + public static ItemStack buildCollar() { + return buildCollar(1); + } + + public static ItemStack buildLeash() { + return buildCollar(1); + } + + public static boolean isPetCollar(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return false; + if(itemStack.getType() != Material.LEASH) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData() || !nbtItem.hasKey("crankedCustomItem")) return false; + return nbtItem.getString("crankedCustomItem").equals("petCollar"); + } + + public static boolean hasPetCollar(ItemStack itemStack) { + if(itemStack == null) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + if(!nbtItem.hasKey("collarEquipped")) return false; + return nbtItem.getBoolean("collarEquipped"); + } + + public static ItemStack addCollarToPet(ItemStack itemStack) { + if(itemStack == null) return null; + ItemBuilder itemBuilder = new ItemBuilder(itemStack); + itemBuilder.addLore("&6&l*COLLAR*"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setBoolean("collarEquipped", true); + return nbtItem.getItem(); + } + + public static ItemStack removePetCollarFromItem(ItemStack itemStack) { + if(itemStack == null) return null; + ItemBuilder itemBuilder = new ItemBuilder(itemStack); + List lore = itemBuilder.getLore(); + lore.removeIf(line -> line.equals(CC.translate("&6&l*COLLAR*"))); + itemBuilder.setLore(lore); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setBoolean("holyWhiteScrollEquipped", false); + return nbtItem.getItem(); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/CrankedPets.java b/Pets/src/main/java/net/crankedpvp/crankedpets/CrankedPets.java new file mode 100644 index 0000000..3235bc1 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/CrankedPets.java @@ -0,0 +1,74 @@ +package net.crankedpvp.crankedpets; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedpets.commands.AdminPetCommand; +import net.crankedpvp.crankedpets.commands.PetsCommand; +import net.crankedpvp.crankedpets.language.LanguageHandler; +import net.crankedpvp.crankedpets.listeners.ApplyPetCollarListener; +import net.crankedpvp.crankedpets.listeners.PetListeners; +import net.crankedpvp.crankedpets.listeners.PlayerDeathListener; +import net.crankedpvp.crankedpets.managers.PassivePetManager; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetsRegister; +import net.crankedpvp.crankedpets.struct.config.PetConfigManager; +import net.crankedpvp.crankedpets.tasks.PassivePetTask; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.stream.Collectors; + +@Getter +public class CrankedPets extends JavaPlugin { + + @Getter + public static CrankedPets instance; + public LanguageHandler languageHandler; + private PetsRegister petRegister; + private CommandManager commandManager; + private PetConfigManager petConfigManager; + private PassivePetManager passivePetManager; + + @Override + public void onEnable() { + instance = this; + + this.languageHandler = new LanguageHandler(this); + this.languageHandler.load(); + + this.petRegister = new PetsRegister(); + this.petRegister.initialize(); + + this.petConfigManager = new PetConfigManager(this); + this.petConfigManager.setupFiles(); + + this.commandManager = new CommandManager(this); + this.registerCommandParameters(); + this.registerCommandCompletion(); + this.commandManager.register(new AdminPetCommand(this)); + this.commandManager.register(new PetsCommand()); + + this.passivePetManager = new PassivePetManager(); + PluginUtils.registerListeners(this, new PetListeners(), new ApplyPetCollarListener(this), new PlayerDeathListener(this)); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new PassivePetTask(), 60L, 20L); + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(Pet.class, argument -> { + Pet pet = this.petRegister.getPetFromID(this.petRegister.getPetIDFromName(String.valueOf(argument))); + return new TypeResult(pet, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#pets", input -> this.petRegister.getPets().stream().map(Pet::getID).collect(Collectors.toList())); + } + + @Override + public void onDisable() { + instance = null; + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/CrankedPetsAPI.java b/Pets/src/main/java/net/crankedpvp/crankedpets/CrankedPetsAPI.java new file mode 100644 index 0000000..49495f9 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/CrankedPetsAPI.java @@ -0,0 +1,73 @@ +package net.crankedpvp.crankedpets; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetsRegister; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class CrankedPetsAPI { + + public static boolean isPet(ItemStack itemStack) { + if (!ItemUtils.isSkull(itemStack)) return false; + + NBTItem nbtItem = new NBTItem(itemStack); + + if (!nbtItem.hasKey("cosmicType")) return false; + return nbtItem.getString("cosmicType").equals("pet"); + } + + public static Pet getPetFromItem(ItemStack itemStack) { + NBTItem nbtItem = new NBTItem(itemStack); + + NBTCompound compound = nbtItem.getCompound("cosmicData"); + String petId = compound.getString("petType"); + + return PetsRegister.getInstance().getPetFromID(petId); + } + + public static boolean hasPetInInventory(Player player, Pet pet) { + for (ItemStack item : player.getInventory().getContents()) { + if (isPet(item)) { + Pet foundPet = getPetFromItem(item); + if (foundPet.getID().equals(pet.getID())) { + return true; + } + } + } + return false; + } + + +/* public static boolean isPetOnCooldown(ItemStack item) { + Pet pet = getPetFromItem(item); + NBTItem nbtItem = new NBTItem(item); + + NBTCompound compound = nbtItem.getCompound("cosmicData"); + long lastUsed = compound.getLong("lastUsed"); + + return lastUsed+(pet.getCooldownInSeconds()* 1000L) > System.currentTimeMillis(); + } + + public static void enterCooldown(Player player) { + NBTItem nbtItem = new NBTItem(player.getItemInHand()); + + NBTCompound compound = nbtItem.getCompound("cosmicData"); + compound.setLong("lastUsed", System.currentTimeMillis()); + player.setItemInHand(nbtItem.getItem()); + } + + public static long getTimeLeftMs(ItemStack item) { + Pet pet = getPetFromItem(item); + NBTItem nbtItem = new NBTItem(item); + + NBTCompound compound = nbtItem.getCompound("cosmicData"); + long lastUsed = compound.getLong("lastUsed"); + + return lastUsed+(pet.getCooldownInSeconds()* 1000L) - System.currentTimeMillis(); + }*/ +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/commands/AdminPetCommand.java b/Pets/src/main/java/net/crankedpvp/crankedpets/commands/AdminPetCommand.java new file mode 100644 index 0000000..ea05d88 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/commands/AdminPetCommand.java @@ -0,0 +1,79 @@ +package net.crankedpvp.crankedpets.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedpets.CollarAPI; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.CrankedPetsAPI; +import net.crankedpvp.crankedpets.language.Language; +import net.crankedpvp.crankedpets.language.LanguageHandler; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.config.PetConfigManager; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("cp") +public class AdminPetCommand extends CommandBase { + + private final LanguageHandler languageHandler; + private final PetConfigManager petConfigManager; + + public AdminPetCommand(CrankedPets plugin) { + this.languageHandler = plugin.getLanguageHandler(); + this.petConfigManager = plugin.getPetConfigManager(); + } + + @Default + @Permission("cranked.admin") + public void mainCommand(CommandSender sender) { + Language.ADMIN_COMMAND_HELP.send(sender); + } + + @SubCommand("pet") + @WrongUsage("&cUsage: /cp pet [player]") + @Permission("cranked.admin") + public void petCommand(CommandSender sender, @Completion("#pets") Pet pet, @Completion("#players") @Optional Player player) { + if (pet == null) { + Language.INVALID_PET.send(sender); + return; + } + + if (player != null) { + player.getInventory().addItem(pet.getItem()); + return; + } + + if (sender instanceof Player) { + ((Player) sender).getInventory().addItem(pet.getItem()); + } + } + + @SubCommand("leash") + @Alias("collar") + @WrongUsage("&cUsage: /cp leash [player]") + @Permission("cranked.admin") + public void leashCommand(final CommandSender commandSender, @Optional @Completion("#players") Player receiver) { + if (receiver != null) { + receiver.getInventory().addItem(CollarAPI.buildCollar()); + return; + } + + if (commandSender instanceof Player) { + ((Player) commandSender).getInventory().addItem(CollarAPI.buildCollar()); + } + } + + @SubCommand("reload") + @WrongUsage("&cUsage: /cp reload") + @Permission("cranked.admin") + public void reloadCommand(Player sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + this.languageHandler.load(); + this.petConfigManager.reloadFiles(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } +} \ No newline at end of file diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/commands/PetsCommand.java b/Pets/src/main/java/net/crankedpvp/crankedpets/commands/PetsCommand.java new file mode 100644 index 0000000..82576a7 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/commands/PetsCommand.java @@ -0,0 +1,24 @@ +package net.crankedpvp.crankedpets.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedpets.inventory.PetsInventory; +import net.crankedpvp.crankedpets.inventory.PetsMainInventory; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("pets") +public class PetsCommand extends CommandBase { + + @Default + public void mainCommand(CommandSender sender) { + if(!(sender instanceof Player)) return; + Player player = (Player)sender; + PetsMainInventory petsInventory = new PetsMainInventory(); + petsInventory.getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/cooldowns/PetCooldown.java b/Pets/src/main/java/net/crankedpvp/crankedpets/cooldowns/PetCooldown.java new file mode 100644 index 0000000..40eca58 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/cooldowns/PetCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedpets.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class PetCooldown extends CurrentCooldown { + public PetCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/events/PetUseEvent.java b/Pets/src/main/java/net/crankedpvp/crankedpets/events/PetUseEvent.java new file mode 100644 index 0000000..741ac21 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/events/PetUseEvent.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedpets.events; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedpets.struct.Pet; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerInteractEvent; + +@Getter +public class PetUseEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + @Setter + private boolean cancelled; + private final Player player; + private final Pet pet; + private final PlayerInteractEvent interacteEvent; + + public PetUseEvent(Player player, Pet pet, PlayerInteractEvent event) { + this.player = player; + this.pet = pet; + this.interacteEvent = event; + this.cancelled = false; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/inventory/PetsInventory.java b/Pets/src/main/java/net/crankedpvp/crankedpets/inventory/PetsInventory.java new file mode 100644 index 0000000..9d25b9a --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/inventory/PetsInventory.java @@ -0,0 +1,67 @@ +package net.crankedpvp.crankedpets.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Collection; + +public class PetsInventory { + private final Gui petsInventory; + + public Gui getUI() { + return this.petsInventory; + } + + Collection pets = CrankedPets.getInstance().getPetRegister().getPets(); + + public PetsInventory(PetType type) { + this.petsInventory = new Gui(1, type + " Pets"); + this.petsInventory.setDefaultClickAction(event -> event.setCancelled(true)); + for(Pet pet : pets) { + if(!pet.getPetType().equals(type)) continue; + this.petsInventory.addItem(new GuiItem(pet.getItem(), event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) event.getWhoClicked().getInventory().addItem(pet.getItem()); + })); + + this.petsInventory.setItem(8, new GuiItem(this.createGoBackItem(), event -> { + event.getWhoClicked().closeInventory(); + PetsMainInventory petsMainInventory = new PetsMainInventory(); + petsMainInventory.getUI().open(event.getWhoClicked()); + })); + } + } + + private ItemStack createGoBackItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.ARROW, "&bGo Back", "&7Go back to select", + "&7a different tier."); + return itemBuilder.colorize().build(); + } + + /* + private ItemStack createInformationItem() { + return new ItemBuilder(Material.BOOK, "&a&lCranked Pets", + "&7Pets are items which can be USED by", + "&7a player to give them buffs.", + "", + "&7Pets can be obtained through", + "&7lootboxes, the underworld, envoys", + "&7and much more.", + "", + "&7Passive pets can be kept inside", + "&7your inventory and their effects", + "&7will keep procing") + .colorize().build(); + } + + */ + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/inventory/PetsMainInventory.java b/Pets/src/main/java/net/crankedpvp/crankedpets/inventory/PetsMainInventory.java new file mode 100644 index 0000000..fef672f --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/inventory/PetsMainInventory.java @@ -0,0 +1,98 @@ +package net.crankedpvp.crankedpets.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Collection; + +public class PetsMainInventory { + private final Gui petsMainInventory; + + public Gui getUI() { + return this.petsMainInventory; + } + + Collection pets = CrankedPets.getInstance().getPetRegister().getPets(); + + public PetsMainInventory() { + this.petsMainInventory = new Gui(1, "Cranked Pets"); + this.petsMainInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + /* + this.petsMainInventory.setItem(1, new GuiItem(this.buildItemForType(PetType.COMMON), event -> { + event.getWhoClicked().closeInventory(); + PetsInventory petsInventory = new PetsInventory(PetType.COMMON); + petsInventory.getUI().open(event.getWhoClicked()); + })); + + */ + + this.petsMainInventory.setItem(2, new GuiItem(this.buildItemForType(PetType.RARE), event -> { + event.getWhoClicked().closeInventory(); + PetsInventory petsInventory = new PetsInventory(PetType.RARE); + petsInventory.getUI().open(event.getWhoClicked()); + })); + this.petsMainInventory.setItem(4, new GuiItem(this.buildItemForType(PetType.MYTHIC), event -> { + event.getWhoClicked().closeInventory(); + PetsInventory petsInventory = new PetsInventory(PetType.MYTHIC); + petsInventory.getUI().open(event.getWhoClicked()); + })); + /* + this.petsMainInventory.setItem(6, new GuiItem(this.buildItemForType(PetType.SEASON), event -> { + event.getWhoClicked().closeInventory(); + PetsInventory petsInventory = new PetsInventory(PetType.SEASON); + petsInventory.getUI().open(event.getWhoClicked()); + })); + + */ + this.petsMainInventory.setItem(6, new GuiItem(this.buildItemForType(PetType.CURSED), event -> { + event.getWhoClicked().closeInventory(); + PetsInventory petsInventory = new PetsInventory(PetType.CURSED); + petsInventory.getUI().open(event.getWhoClicked()); + })); + } + + private ItemStack buildItemForType(PetType petType) { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, petType.getData()) + .setName(petType.getName() + " &7Pets") + .setLore( + "", + "&fClick me to view all of the", + petType.getName() + " &fpets", + "" + ).colorize().build(); + } + + + private ItemStack createInformationItem() { + return new ItemBuilder(Material.BOOK, "&a&lCranked Pets", + "&7Pets are items which can be USED by", + "&7a player to give them buffs.", + "", + "&7Pets can be obtained through", + "&7lootboxes, the underworld, envoys", + "&7and much more.", + "", + "&7Passive pets can be kept inside", + "&7your inventory and their effects", + "&7will keep procing") + .colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/language/Language.java b/Pets/src/main/java/net/crankedpvp/crankedpets/language/Language.java new file mode 100644 index 0000000..208ed1b --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/language/Language.java @@ -0,0 +1,102 @@ +package net.crankedpvp.crankedpets.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + ADMIN_COMMAND_HELP, + INVALID_PET, + PASSIVE_PET, + PVP_DISABLED_REGION, + ADMIN_RELOADING, + ADMIN_RELOADED, + PET_ON_COOLDOWN, + PET_USED, + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return value != null ? value : this.name(); + } + + public String getValue(UnaryOperator function) { + return value != null ? function.apply(value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(getValue(function)); + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/language/LanguageHandler.java b/Pets/src/main/java/net/crankedpvp/crankedpets/language/LanguageHandler.java new file mode 100644 index 0000000..0967015 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.crankedpets.language; + +import net.crankedpvp.crankedpets.CrankedPets; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final CrankedPets plugin; + + public LanguageHandler(CrankedPets plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/ApplyPetCollarListener.java b/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/ApplyPetCollarListener.java new file mode 100644 index 0000000..91993be --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/ApplyPetCollarListener.java @@ -0,0 +1,54 @@ +package net.crankedpvp.crankedpets.listeners; + +import net.crankedpvp.crankedpets.CollarAPI; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.CrankedPetsAPI; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class ApplyPetCollarListener implements Listener { + + private CrankedPets plugin; + public ApplyPetCollarListener(CrankedPets plugin) { + this.plugin = plugin; + } + + @EventHandler + public void applyPetCollar(InventoryClickEvent event) { + if(event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR || event.getCursor() == null || event.getCursor().getType() == Material.AIR) return; + Player player = (Player) event.getWhoClicked(); + + if(!CollarAPI.isPetCollar(event.getCursor())) return; + event.setCancelled(true); + if(!CrankedPetsAPI.isPet(event.getCurrentItem())) { + player.sendMessage(CC.translate("&c&l(!) &cYou cannot apply a pet collar to this item")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(CollarAPI.hasPetCollar(event.getCurrentItem())) { + player.sendMessage(CC.translate("&c&l(!) &cThis pet already has a collar applied")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + ItemStack cursor = event.getCursor(); + int amount = cursor.getAmount(); + if (amount <= 1) { + event.setCursor(null); + } else { + cursor.setAmount(amount - 1); + event.setCursor(cursor); + } + + event.setCurrentItem(CollarAPI.addCollarToPet(event.getCurrentItem())); + player.sendMessage(CC.translate("&a&l(!) &aYou have successfully applied a pet collar to your pet")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/PetListeners.java b/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/PetListeners.java new file mode 100644 index 0000000..d3f5057 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/PetListeners.java @@ -0,0 +1,75 @@ +package net.crankedpvp.crankedpets.listeners; + +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.CrankedPetsAPI; +import net.crankedpvp.crankedpets.events.PetUseEvent; +import net.crankedpvp.crankedpets.language.Language; +import net.crankedpvp.crankedpets.struct.PassivePet; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +public class PetListeners implements Listener { + + @EventHandler + public void onPlayerInteractWithPet(PlayerInteractEvent event) { + if (!CrankedPetsAPI.isPet(event.getItem())) return; + Player player = event.getPlayer(); + Pet pet = CrankedPetsAPI.getPetFromItem(event.getItem()); + + if (!WorldGuardUtils.canPvPInRegion(player) && !(pet instanceof PassivePet)) { + Language.PVP_DISABLED_REGION.send(player); + event.setCancelled(true); + return; + } + + if (pet instanceof PassivePet) { + Language.PASSIVE_PET.send(player); + } else { + + PetUseEvent petUseEvent = new PetUseEvent(player, pet, event); + Bukkit.getServer().getPluginManager().callEvent(petUseEvent); + + if (petUseEvent.isCancelled()) { + return; + } + + if (CooldownUtils.isCooldownActive(player, pet.getID())) { + String msg = Language.PET_ON_COOLDOWN.getMessage(); + msg = msg.replace("%timeLeft%", CooldownUtils.getFormattedCooldown(player, pet.getID())); + msg = msg.replace("%pet%", pet.getDisplayName()); + player.sendMessage(CC.translate(msg)); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + event.setCancelled(true); + return; + } + pet.procAbility(player); + String msg = Language.PET_USED.getMessage(); + msg = msg.replace("%pet%", pet.getDisplayName()); + player.sendMessage(CC.translate(msg)); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).incrementPetsUsed(); + } + event.setCancelled(true); + } + + @EventHandler + public void onCowEffect(PotionEffectAddEvent event) { + if (event.getEntity() instanceof Player) { + if (PotionEffectUtils.getDebuffsList().contains(event.getEffect().getType()) && CrankedPetsAPI.hasPetInInventory((Player) event.getEntity(), CrankedPets.getInstance().getPetRegister().getPetFromID("cow"))) { + event.setCancelled(true); + } + } + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/PlayerDeathListener.java b/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/PlayerDeathListener.java new file mode 100644 index 0000000..b676770 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/listeners/PlayerDeathListener.java @@ -0,0 +1,51 @@ +package net.crankedpvp.crankedpets.listeners; + + +import net.crankedpvp.crankedpets.CollarAPI; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class PlayerDeathListener implements Listener { + + private final CrankedPets plugin; + private final List disabledWorlds = new ArrayList<>(); + public PlayerDeathListener(CrankedPets plugin) { + this.plugin = plugin; + disabledWorlds.add("world_nether"); + disabledWorlds.add("world_duels"); + //disabledWorlds.add(ArcadeAPI.WORLD_NAME); + } + + + @EventHandler(priority = EventPriority.LOWEST) + public void playerDeathListener(PlayerDeathEvent event) { + if(event.getEntity() == null) return; + if (disabledWorlds.contains(event.getEntity().getWorld().getName())) return; + final Player victim = event.getEntity(); + List collaredPets = new ArrayList<>(event.getDrops()) + .stream() + .filter(CollarAPI::hasPetCollar) + .collect(Collectors.toList()); + if(collaredPets.isEmpty()) return; + event.getDrops().removeAll(collaredPets); + List finalCollaredPets = collaredPets.stream().map(CollarAPI::removePetCollarFromItem).collect(Collectors.toList()); + + Bukkit.getScheduler().runTaskLater(plugin, () -> finalCollaredPets.forEach(itemStack -> { + victim.getInventory().addItem(itemStack); + victim.sendMessage(CC.translate("&a&l+ &6&l*COLLAR* PROTECTION &8➥ " + itemStack.getItemMeta().getDisplayName())); + }), 1L); + } + + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/managers/PassivePetManager.java b/Pets/src/main/java/net/crankedpvp/crankedpets/managers/PassivePetManager.java new file mode 100644 index 0000000..7d1240b --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/managers/PassivePetManager.java @@ -0,0 +1,56 @@ +package net.crankedpvp.crankedpets.managers; + +import lombok.Getter; +import net.crankedpvp.crankedpets.CrankedPetsAPI; +import net.crankedpvp.crankedpets.struct.PassivePet; +import net.crankedpvp.crankedpets.struct.Pet; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +public class PassivePetManager { + @Getter + public Map> passivePetsMap = new HashMap<>(); + + public List getPassivePets(Player player) { + if (!passivePetsMap.containsKey(player.getUniqueId())) { + List passivePets = new ArrayList<>(); + passivePetsMap.put(player.getUniqueId(), passivePets); + } + return passivePetsMap.get(player.getUniqueId()); + } + + public void scanPlayerInventory(Player player) { + if (player.getInventory().getContents().length == 0) return; + List pets = getPassivePets(player); + pets.clear(); + for (ItemStack item : player.getInventory().getContents().clone()) { + if (CrankedPetsAPI.isPet(item)) { + Pet pet = CrankedPetsAPI.getPetFromItem(item); + if (pet instanceof PassivePet) { + if (pets.contains(pet)) continue; + pets.add(pet); + } + } + } + passivePetsMap.put(player.getUniqueId(), pets); + } + + + public List getCurrentPassivePets(Player player) { + if (player.getInventory().getContents().length == 0) return Collections.emptyList(); + List pets = new ArrayList<>(); + for (ItemStack item : player.getInventory().getContents().clone()) { + if (CrankedPetsAPI.isPet(item)) { + Pet pet = CrankedPetsAPI.getPetFromItem(item); + if (pet instanceof PassivePet) { + if (pets.contains(pet)) continue; + pets.add(pet); + } + } + } + return pets; + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/CagePet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/CagePet.java new file mode 100644 index 0000000..4ea1d52 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/CagePet.java @@ -0,0 +1,166 @@ +package net.crankedpvp.crankedpets.pets; + +import com.avaje.ebean.validation.NotNull; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitScheduler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CagePet extends Pet { + + private final List locations = new ArrayList<>(); + private final DamageHandler damageHandler = CrankedUtils.getInstance().getDamageHandler(); + @ConfigValue + private final int cageDuration = 7; + + @ConfigValue + private int cooldown = 150; + + @Override + public String getName() { + return "Cage"; + } + + @Override + public String getDisplayName() { + return "&4&lCage Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDhlNjUyNTM4NWY3NDgzMjJlZWNjNDE2ODliNjkwYWExZWJiYjIxNzJlYzJjNGEyZWFjMTRmMjJkOTRlZTNiYSJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fSummons a dimensional", + "&fcage for 7 seconds." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oA dangerous pet created", + "&7&oby prisoners that", + "&7&oescaped from the metal cages." + ); + } + + @Override + public PetType getPetType() { + return PetType.CURSED; + } + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + @Override + public void procAbility(Player player) { + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + player.playSound(player.getLocation(), Sound.DIG_SNOW, 1.1F, 3.0F); + player.playSound(player.getLocation(), Sound.WITHER_SHOOT, 1.1F, 3.0F); + + cagePlayer(player); + } + + public void cagePlayer(Player affected) { + final List list = new ArrayList(); + final BukkitScheduler scheduler = Bukkit.getScheduler(); + final Location baseLocation = affected.getLocation(); + list.addAll(setInside(baseLocation.clone().add(0.0, -1.0, 0.0), Material.OBSIDIAN)); + list.addAll(setInside(baseLocation.clone().add(0.0, 3.0, 0.0), Material.OBSIDIAN)); + list.addAll(setOutside(baseLocation.clone().add(0.0, -1.0, 0.0), Material.OBSIDIAN)); + list.addAll(setOutside(baseLocation.clone().add(0.0, 3.0, 0.0), Material.OBSIDIAN)); + list.addAll(setOutside(baseLocation.clone().add(0.0, 0.0, 0.0), Material.IRON_FENCE)); + list.addAll(setOutside(baseLocation.clone().add(0.0, 1.0, 0.0), Material.IRON_FENCE)); + list.addAll(setOutside(baseLocation.clone().add(0.0, 2.0, 0.0), Material.IRON_FENCE)); + locations.addAll(list); + scheduler.scheduleSyncDelayedTask(CrankedPets.getInstance(), (Runnable)new BukkitRunnable() { + int count = 0; + public void run() { + if (this.count >= cageDuration) { + removeBlocks(list); + this.cancel(); + } + if (affected.getHealth() <= 0.0 || affected.isDead()) { + removeBlocks(list); + this.cancel(); + } + ++this.count; + } + }.runTaskTimer(CrankedPets.getInstance(), 20L, 20L)); + } + + private static List setInside(Location baseLocation, Material material) { + List locs = new ArrayList<>(Arrays.asList(baseLocation, baseLocation + + .clone().add(-1.0D, 0.0D, 0.0D), baseLocation + .clone().add(0.0D, 0.0D, 1.0D), baseLocation + .clone().add(-1.0D, 0.0D, 1.0D))); + return setWithLocations(material, locs); + } + + private List setOutside(Location baseLocation, Material material) { + List locs = new ArrayList<>(Arrays.asList(baseLocation + .clone().add(0.0D, 0.0D, -1.0D), baseLocation + .clone().add(1.0D, 0.0D, 0.0D), baseLocation + .clone().add(1.0D, 0.0D, -1.0D), baseLocation + .clone().add(1.0D, 0.0D, 1.0D), baseLocation + .clone().add(1.0D, 0.0D, 2.0D), baseLocation + .clone().add(0.0D, 0.0D, 2.0D), baseLocation + .clone().add(-1.0D, 0.0D, 2.0D), baseLocation + .clone().add(-2.0D, 0.0D, 2.0D), baseLocation + .clone().add(-2.0D, 0.0D, 0.0D), baseLocation + .clone().add(-2.0D, 0.0D, 1.0D), + baseLocation + .clone().add(-2.0D, 0.0D, -1.0D), baseLocation + .clone().add(-1.0D, 0.0D, -1.0D))); + return setWithLocations(material, locs); + } + + public void removeBlocks(List list) { + for (Location location : list) { + Block block = location.getBlock(); + if (block != null) { + block.setType(Material.AIR); + locations.remove(location); + location.getBlock().removeMetadata("cage", CrankedPets.getInstance()); + } + } + } + + @NotNull + private static List setWithLocations(Material material, List locs) { + List filteredLocations = new ArrayList<>(); + for (Location loc : locs) { + if (loc.getBlock().getType() == Material.AIR) { + filteredLocations.add(loc); + loc.getBlock().setType(material); + loc.getBlock().setMetadata("cage", new FixedMetadataValue(CrankedPets.getInstance(), "cage")); + } + } + return filteredLocations; + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ChickenPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ChickenPet.java new file mode 100644 index 0000000..6ec3c81 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ChickenPet.java @@ -0,0 +1,71 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.struct.PassivePet; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class ChickenPet extends Pet implements PassivePet { + + + @Override + public String getName() { + return "Chicken"; + } + + @Override + public String getDisplayName() { + return "&b&lChicken Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvY2EzNTgyY2U0ODg5MzMzZGFkMzI5ZTRlMjQzNzJhMDNhNWRhYTJjMzQyODBjNTYyNTZhZjUyODNlZGIwNDNmOCJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fGain a permanent speed effect" + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oYou shall run fast by", + "&7&omy side, flap flap." + ); + } + + @Override + public PetType getPetType() { + return PetType.RARE; + } + + @Override + public int getCooldownInSeconds() { + return 300; + } + + @Override + public void procAbility(Player player) { + } + + @Override + public void passiveAbility(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "ChickenPet"); + } + + + @Override + public void disablePassiveAbility(Player player) { + PotionEffectUtils.removePotionEffect(player, "ChickenPet"); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/CowPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/CowPet.java new file mode 100644 index 0000000..526c0e2 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/CowPet.java @@ -0,0 +1,67 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.struct.PassivePet; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class CowPet extends Pet implements PassivePet { + + + @Override + public String getName() { + return "Cow"; + } + + @Override + public String getDisplayName() { + return "&4&lCow Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDY1NTE4NDA5NTVmNTI0MzY3NTgwZjExYjM1MjI4OTM4YjY3ODYzOTdhOGYyZThjOGNjNmIwZWIwMWI1ZGIzZCJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fNegate all negative", + "&fpotion effects." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oWho would harm a cow", + "&7&owhen it did nothing wrong", + "&7&oto them. It's just tasty." + ); + } + + @Override + public PetType getPetType() { + return PetType.CURSED; + } + + @Override + public int getCooldownInSeconds() { + return 300; + } + + @Override + public void procAbility(Player player) { + } + + @Override + public void passiveAbility(Player player) { + } + + @Override + public void disablePassiveAbility(Player player) { + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ExperiencePet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ExperiencePet.java new file mode 100644 index 0000000..dbd2267 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ExperiencePet.java @@ -0,0 +1,90 @@ +package net.crankedpvp.crankedpets.pets; + +import lombok.Getter; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.CrankedPetsAPI; +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +public class ExperiencePet extends Pet { + + @Getter + private List playersUsingExpPet = new ArrayList<>(); + + @ConfigValue + @Getter + private double expMultiplier = 2.5; + + @ConfigValue + private int duration = 300; + + @ConfigValue + private int cooldown = 1500; + + @Override + public String getName() { + return "Experience"; + } + + @Override + public String getDisplayName() { + return "&b&lExperience Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYjIwNjU3ZTI0YjU2ZTFiMmY4ZmMyMTlkYTFkZTc4OGMwYzI0ZjM2Mzg4YjFhNDA5ZDBjZDJkOGRiYTQ0YWEzYiJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fGain an EXP multiplier", + "&ffor 5 minutes." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oAn experimental pet dedicated", + "&7&oto boosting the experience", + "&7&oof it's empowered owner." + ); + } + + @Override + public PetType getPetType() { + return PetType.RARE; + } + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + @Override + public void procAbility(Player player) { + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + final UUID uuid = player.getUniqueId(); + playersUsingExpPet.add(uuid); + Bukkit.getScheduler().runTaskLaterAsynchronously(CrankedPets.getInstance(), () -> { + if (player.isOnline()) { + player.sendMessage(CC.translate("&d&lPets &8➥ &7Your experience pet ability has &c&lEXPIRED&7!")); + } + playersUsingExpPet.remove(uuid); + }, 20L * duration); + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/IronGolemPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/IronGolemPet.java new file mode 100644 index 0000000..a2e255a --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/IronGolemPet.java @@ -0,0 +1,75 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedpets.CrankedPetsAPI; +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.*; + +public class IronGolemPet extends Pet { + @ConfigValue + private int potionLevel = 5; + + @ConfigValue + private int duration = 10; + + @ConfigValue + private int cooldown = 300; + + @Override + public String getName() { + return "Iron Golem"; + } + + @Override + public String getDisplayName() { + return "&e&lIron Golem Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTIyY2M2ZWEzODdmYWQ1ZjI1Y2VmMjU3YTgzMWVhOGQ5N2UwZGZhMmMzNDU0MWZkOGM3ODMwMjAzOGFkMWZiMyJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fGain temporary absorption hearts." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oA heavy and bulky pet", + "&7&ocreated to protect it's owner."); + } + + @Override + public PetType getPetType() { + return PetType.MYTHIC; + } + + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + @Override + public void procAbility(Player player) { + int potionLevel = this.potionLevel; + if(Objects.equals(CrankedArmorAPI.getCurrentArmorSet(player), CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID("reaper"))) + potionLevel += 2; + PotionEffectUtils.addExtraPotionEffect(player, PotionEffectType.ABSORPTION, potionLevel, "IronGolemPet", duration); + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/KrakenPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/KrakenPet.java new file mode 100644 index 0000000..297d1c3 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/KrakenPet.java @@ -0,0 +1,94 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.struct.PassivePet; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class KrakenPet extends Pet implements PassivePet, Listener { + + @ConfigValue + private int outgoingDamageWhileInWater; + + @Override + public String getName() { + return "Kraken"; + } + + @Override + public String getDisplayName() { + return "&b&lKraken Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTUzMGQyMDY1MWFhMzhjMGU4MmMyZGFmYzM1MDQ0NDNjYzZhNGI5ZTZlZWQxNDViNmVkY2U5OTQ3OWNlODQ4ZiJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fDeal more outgoing damage", + "&fwhile submerged in water" + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oA legendary sea monster", + "&7&oin the form of a pocket", + "&7&osized inventory pet." + ); + } + + @Override + public PetType getPetType() { + return PetType.RARE; + } + + @Override + public int getCooldownInSeconds() { + return 300; + } + + @Override + public void procAbility(Player player) { + } + + @Override + public void passiveAbility(Player player) { + } + + @Override + public void disablePassiveAbility(Player player) { + } + + @EventHandler + public void moreDamage(EntityDamageByEntityEvent event) { + if(event.getDamager() == null) return; + if(event.getEntity() == null) return; + + if (!(event.getDamager() instanceof Player)) return; + Player damager = (Player) event.getDamager(); + if(CrankedPets.getInstance().getPassivePetManager().getPassivePets(damager).contains(this)) { + if(event.getEntity() instanceof Player) { + Player victim = (Player) event.getEntity(); + if(CrankedMasksAPI.hasMaskEquipped(victim, CrankedMasks.getInstance().getMasksRegister().getMaskFromID("leviathan"))) return; + } + if(damager.getLocation().getBlock().isLiquid()) { + super.getDamageHandler().increaseDamage(this.outgoingDamageWhileInWater, event, "KrakenPet"); + } + } + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/PigPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/PigPet.java new file mode 100644 index 0000000..eb2a6ca --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/PigPet.java @@ -0,0 +1,67 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.struct.PassivePet; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class PigPet extends Pet implements PassivePet { + + + @Override + public String getName() { + return "Pig"; + } + + @Override + public String getDisplayName() { + return "&b&lPig Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYmVlODUxNDg5MmYzZDc4YTMyZTg0NTZmY2JiOGM2MDgxZTIxYjI0NmQ4MmYzOThiZDk2OWZlYzE5ZDNjMjdiMyJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fGain a permanent saturation effect" + ); + } + + @Override + public List getLore() { + return Arrays.asList( + ); + } + + @Override + public PetType getPetType() { + return PetType.RARE; + } + + @Override + public int getCooldownInSeconds() { + return 300; + } + + @Override + public void procAbility(Player player) { + } + + @Override + public void passiveAbility(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SATURATION, 1, "Pig Pet"); + } + + @Override + public void disablePassiveAbility(Player player) { + PotionEffectUtils.removePotionEffect(player, "Pig Pet"); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ProteinPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ProteinPet.java new file mode 100644 index 0000000..16415aa --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ProteinPet.java @@ -0,0 +1,74 @@ +package net.crankedpvp.crankedpets.pets; + +import com.massivecraft.factions.util.RelationUtil; +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class ProteinPet extends Pet { + + @ConfigValue + private int potionLevel = 3; + + @ConfigValue + private int cooldown = 300; + + @ConfigValue + private int duration = 4; + + @Override + public String getName() { + return "Protein"; + } + + @Override + public String getDisplayName() { + return "&e&lProtein Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYjhiNjRjZWQxYTM4YTljYzBmYTQ3ZTEzN2ZjZWJhOGJhYjU4YzIxNGZmZmYwZmNhNzYxYjg0NmU2OGNiZWU5YSJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fGives all allies within an 8 block", + "&fradius a temporary Strength buff", + "&ffor four seconds." + ); + } + + @Override + public PetType getPetType() { + return PetType.MYTHIC; + } + + @Override + public int getCooldownInSeconds() { + return this.cooldown; + } + + @Override + public void procAbility(Player player) { + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + PlayerUtils.getNearbyPlayers(player, 8) + .stream() + .filter(loopPlayer -> !FactionUtils.cantPvPFaction(loopPlayer, player)) + .filter(loopPlayer -> !CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(loopPlayer)) + .forEach(loopPlayer -> PotionEffectUtils.addPotionEffect(loopPlayer, PotionEffectType.INCREASE_DAMAGE, this.potionLevel, this.getName(), this.duration)); + PotionEffectUtils.addPotionEffect(player, PotionEffectType.INCREASE_DAMAGE, this.potionLevel, this.getName(), this.duration); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ShieldPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ShieldPet.java new file mode 100644 index 0000000..5a96799 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ShieldPet.java @@ -0,0 +1,72 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.CrankedPetsAPI; +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.*; + +public class ShieldPet extends Pet { + @ConfigValue + private int resLevel = 1; + + @ConfigValue + private int duration = 10; + + @ConfigValue + private int cooldown = 900; + + @Override + public String getName() { + return "Shield"; + } + + @Override + public String getDisplayName() { + return "&b&lShield Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTFkMDIyNTkzNzkxZjA1OTM5ZjYyZDYwY2Q1ZDg2NWZmNjhjOWI0OTNlYWFmYWI1ZTQ0MjZjODllMDE2ZTNkIn19fQ=="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fGain a temporary resistance effect." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oA shield made by the", + "&7&oancient warriors from camelot."); + } + + @Override + public PetType getPetType() { + return PetType.RARE; + } + + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + @Override + public void procAbility(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.DAMAGE_RESISTANCE, resLevel, "ShieldPet", duration); + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/SnowGolemPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/SnowGolemPet.java new file mode 100644 index 0000000..4cd56a5 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/SnowGolemPet.java @@ -0,0 +1,100 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.*; + +public class SnowGolemPet extends Pet implements Listener { + + private List proced = new ArrayList<>(); + + @ConfigValue + private int duration = 7; + + @ConfigValue + private int cooldown = 300; + + @Override + public String getName() { + return "Snow Golem"; + } + + @Override + public String getDisplayName() { + return "&e&lSnow Golem Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzIwMGExZDc2YTJiODMwMjUyZTAxN2MyMDJjZDUwYzlhM2NkNjIzYjQ5MTdlZDc4NjYxYTlhMzcyNjBhNDE5MSJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fBecome immune to taking damage in", + "&fexchange for the ability to attack", + "&ffor a short period of time" + ); + } + + @Override + public List getLore() { + return Collections.emptyList(); + } + + @Override + public PetType getPetType() { + return PetType.MYTHIC; + } + + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + @Override + public void procAbility(Player player) { + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + this.proced.add(player.getUniqueId()); + CrankedPets.getInstance().getServer().getScheduler().runTaskLater(CrankedPets.getInstance(), () -> this.proced.remove(player.getUniqueId()), this.duration * 20L); + } + + @EventHandler + public void onEntityDamage(EntityDamageByEntityEvent event) { + if(event.getDamager() instanceof Player && event.getEntity() instanceof Player) { + + Player damager = (Player) event.getDamager(); + Player entity = (Player) event.getEntity(); + + if(this.proced.contains(entity.getUniqueId())) { + if(!StarItemsAPI.playerHasStarItem(damager, "void")) { + CrankedUtils.getInstance().getDamageHandler().cancelDamage(event, "Snowgolem"); + damager.sendMessage(CC.translate("&c&lSnow Golem &8" + Arrow.arrow() + " &eNo damage was dealt due to the Snow Golem Pet")); + return; + } + damager.sendMessage(CC.translate("&d&lVoid &8" + Arrow.arrow() + " &eYou bypassed the &c&lSnow Golem &epet damage cancellation")); + } + + if(this.proced.contains(damager.getUniqueId())) { + CrankedUtils.getInstance().getDamageHandler().cancelDamage(event, "Snowgolem"); + damager.sendMessage(CC.translate("&c&lSnow Golem &8" + Arrow.arrow() + " &eNo damage was dealt due to the Snow Golem Pet")); + } + } + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/SpiderPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/SpiderPet.java new file mode 100644 index 0000000..3ceaaf3 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/SpiderPet.java @@ -0,0 +1,112 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.BlockUtil; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.wildpvp.CagePvPPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class SpiderPet extends Pet { + + @ConfigValue + private int abilityDuration = 5; + + @ConfigValue + private int cooldown = 900; + + @ConfigValue + private int radius = 10; + + @Override + public String getName() { + return "Spider"; + } + + @Override + public String getDisplayName() { + return "&e&lSpider Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzVlMjQ4ZGEyZTEwOGYwOTgxM2E2Yjg0OGEwZmNlZjExMTMwMDk3ODE4MGVkYTQxZDNkMWE3YThlNGRiYTNjMyJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fTrap nearby enemies in", + "&fa sticky cobweb" + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oYour fellow spider companion", + "&7&othat'll lure enemies into it's", + "&7&owebs, allowing you to strike." + ); + } + + @Override + public PetType getPetType() { + return PetType.MYTHIC; + } + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + + @Override + public void procAbility(Player player) { + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + for(Player target : PVPUtils.getNearbyEnemyPlayersExceptPlayer(player, radius)) { + if(StarItemsAPI.playerHasStarItem(target, "ignitedholograph")) continue; + if(StarItemsAPI.playerHasStarItem(target, "combo")) continue; + if (CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(target) && !CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(player) || !CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(target) && CagePvPPlugin.getInstance().getWildPvPManager().hasWildPvP(player)) continue; + if (EssentialsUtils.isVanished(target)) continue; + Location location = target.getLocation(); + + Block underBlock = location.clone().getBlock(); + + Material underBlockType = underBlock.getType(); + + boolean setAtLeastOne = false; + + if(underBlockType == Material.AIR) { + BlockUtil.setBlockFast(underBlock, Material.WEB.getId(), (byte) 0, false); + setAtLeastOne = true; + } + if(setAtLeastOne) { + Bukkit.getScheduler().runTaskLater(CrankedPets.getInstance(), () -> { + + + if (underBlock.getType() == Material.WEB) { + //underBlock.setType(Material.AIR); + BlockUtil.setAir(underBlock, true); + + } + }, abilityDuration * 20L); + + } + } + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/TitanPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/TitanPet.java new file mode 100644 index 0000000..08e91b9 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/TitanPet.java @@ -0,0 +1,110 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class TitanPet extends Pet implements Listener { + + @ConfigValue + private int duration = 5; + + @ConfigValue + private int cooldown = 300; + + @ConfigValue + private double damageIncreasePercent = 10; + + @ConfigValue + private double damageIncreasePercentCritical = 5; + + private List titanAbility = new ArrayList<>(); + + @Override + public String getName() { + return "Titan"; + } + + @Override + public String getDisplayName() { + return "&4&lTitan Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzJlNWE5ODRjMzZlZTczMjE3Y2I0YjAzMmQyMTM2MDk2YWZiMWQ3NjEwNDU1OWExNTM5OWI5YzBjNGQyN2NmNiJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&f* Clear all debuffs", + "&f* 1.1x Outgoing damage (5s)", + "&f* 1.15x Outgoing critical damage (5s)", + "&f* Automatic /fix all" + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oMark your target for assured destruction"); + } + + @Override + public PetType getPetType() { + return PetType.CURSED; + } + + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + @Override + public void procAbility(Player player) { + this.titanAbility.add(player); + for(ItemStack itemStack : player.getInventory().getArmorContents()) + if(ItemUtils.isEnchantable(itemStack)) itemStack.setDurability((short) 0); + for(ItemStack itemStack : player.getInventory().getContents()) + if(ItemUtils.isEnchantable(itemStack)) itemStack.setDurability((short) 0); + PotionEffectUtils.bless(player); + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + player.updateInventory(); + + Bukkit.getScheduler().runTaskLater(CrankedPets.getInstance(), () -> this.titanAbility.remove(player), this.duration * 20L); + } + + @EventHandler + public void extraDamageOnTitanPet(EntityDamageByEntityEvent event) { + if(event.getEntity() == null) return; + if(event.getDamager() == null) return; + if(!(event.getDamager() instanceof Player)) return; + Player player = (Player)event.getDamager(); + if(!this.titanAbility.contains(player)) return; + if(event.getEntity() instanceof Player && StarItemsAPI.playerHasStarItem((Player) event.getEntity(), "olympus")) return; + if(event.getEntity() instanceof Player && StarItemsAPI.playerHasStarItem((Player) event.getEntity(), "combo")) return; + super.getDamageHandler().increaseDamage(this.damageIncreasePercent, event, "TitanPet"); + if(PVPUtils.isCritical(player)) { + super.getDamageHandler().increaseDamage(this.damageIncreasePercentCritical, event, "TitanPetCritical"); + } + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ValentinePet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ValentinePet.java new file mode 100644 index 0000000..68a2f68 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/ValentinePet.java @@ -0,0 +1,74 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class ValentinePet extends Pet { + @ConfigValue + private int regenLevel = 5; + + @ConfigValue + private int regenDuration = 10; + + + @ConfigValue + private int cooldown = 900; + + @Override + public String getName() { + return "Valentine"; + } + + @Override + public String getDisplayName() { + return "&e&lValentine Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWUzNGQ0MjlkMWJhOTIzYzlmYjBjZjg1MWZiY2Y4YjQ0YmYxMGY3ZGE1MWZmMzI2NjJmNDc2NmE2ZjZlNTYyOSJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fGain a temporary regeneration effect." + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oA pet that is not scared", + "&7&oto to spread it's positive", + "&7&ovibes among it's owners." + ); + } + + @Override + public PetType getPetType() { + return PetType.MYTHIC; + } + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + + @Override + public void procAbility(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.REGENERATION, regenLevel, "ValentinePet", regenDuration); + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/pets/WizardPet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/WizardPet.java new file mode 100644 index 0000000..5c516ff --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/pets/WizardPet.java @@ -0,0 +1,82 @@ +package net.crankedpvp.crankedpets.pets; + +import net.crankedpvp.crankedpets.cooldowns.PetCooldown; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.PetType; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.Potion; +import org.bukkit.potion.PotionType; + +import java.util.Arrays; +import java.util.List; + +public class WizardPet extends Pet { + + @ConfigValue + private int cooldown = 900; + + @ConfigValue + private int amountOfPotions = 3; + + @Override + public String getName() { + return "Wizard"; + } + + @Override + public String getDisplayName() { + return "&4&lWizard Pet"; + } + + @Override + public String getTexture() { + return "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvN2JmYzE3ZWQ5MjhhZGZhZmZmYmY5ZjkxNTg5ZjBkNWI3YWIyMTZmNzRjMGQ3MjE0ZjI5ZTY5NDM4ZTYwOTdiMCJ9fX0="; + } + + @Override + public List getPerks() { + return Arrays.asList( + "&fGive yourself " + this.amountOfPotions + " instant", + "&fhealth two potions" + ); + } + + @Override + public List getLore() { + return Arrays.asList( + "&7&oA pet that is willing to", + "&7&ogive you potions at the", + "&7&oexpense of it's own sanity" + ); + } + + @Override + public PetType getPetType() { + return PetType.CURSED; + } + + + @Override + public int getCooldownInSeconds() { + return cooldown; + } + + + @Override + public void procAbility(Player player) { + for(int i = 0; i < this.amountOfPotions; i++) + player.getInventory().addItem(getPotion()); + CooldownUtils.registerCooldown(player, new PetCooldown(getID(), getCooldownInSeconds())); + + } + + private ItemStack getPotion() { + Potion splash = new Potion(PotionType.INSTANT_HEAL, 2); + splash.setSplash(true); + return splash.toItemStack(1); + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PassivePet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PassivePet.java new file mode 100644 index 0000000..c315103 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PassivePet.java @@ -0,0 +1,9 @@ +package net.crankedpvp.crankedpets.struct; + +import org.bukkit.entity.Player; + +public interface PassivePet { + void passiveAbility(Player player); + void disablePassiveAbility(Player player); + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/struct/Pet.java b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/Pet.java new file mode 100644 index 0000000..d2bdb4b --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/Pet.java @@ -0,0 +1,80 @@ +package net.crankedpvp.crankedpets.struct; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +public abstract class Pet implements Listener { + + @Getter + private final DamageHandler damageHandler; + + public Pet() { + this.damageHandler = CrankedUtils.instance.getDamageHandler(); + } + + public abstract String getName(); + + public abstract String getDisplayName(); + + public abstract String getTexture(); + + public abstract List getPerks(); + + public List getLore() { + return null; + } + //make abstract if want to use ^ + + public abstract PetType getPetType(); + + public abstract int getCooldownInSeconds(); + + public abstract void procAbility(Player player); + + public String getID() { + return this.getName().toLowerCase(Locale.ROOT).replace(" ", ""); + } + + + public ItemStack getItem() { + List lore = new ArrayList<>(); + lore.add(this.getPetType().getName() + " Pet"); + lore.add(""); + lore.add(this instanceof PassivePet ? "&e&lPASSIVE" : "&a&lACTIVE"); + lore.addAll(this.getPerks()); + if(!(this instanceof PassivePet)) { + lore.add(""); + lore.add("&f&lCooldown:"); + lore.add("&7" + TimeUtils.formatSeconds(this.getCooldownInSeconds())); + } + lore.add(""); + lore.add("&e&lLevel: 100"); + lore.add("&e&lEXP: 0/10100"); + lore.add("&c;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"); + + ItemStack skull = SkullUtils.getSkull(this.getTexture()); + skull = new ItemBuilder(skull).setName(this.getDisplayName() + " &7[Level 100]") + .setLore(lore) + .colorize() + .build(); + NBTItem wrapper = new NBTItem(skull); + wrapper.setString("cosmicType", "pet"); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + cosmicData.setString("petType", this.getID()); + return wrapper.getItem(); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PetType.java b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PetType.java new file mode 100644 index 0000000..3961ae1 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PetType.java @@ -0,0 +1,18 @@ +package net.crankedpvp.crankedpets.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter @AllArgsConstructor +public enum PetType { + //COMMON("&7Common", (short) 8), + RARE("&bRare", (short) 3), + MYTHIC("&eMythic", (short) 4), + //SEASON("&cSeason", (short) 14), + CURSED("&4Cursed", (short) 14) + ; + + + private final String name; + private final short data; +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PetsRegister.java b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PetsRegister.java new file mode 100644 index 0000000..d0db3ef --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/PetsRegister.java @@ -0,0 +1,85 @@ +package net.crankedpvp.crankedpets.struct; + +import lombok.Getter; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.pets.*; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; + +import java.util.*; + +public class PetsRegister { + + @Getter + private static PetsRegister instance; + private final Map pets; + + + public PetsRegister() { + instance = this; + this.pets = new HashMap<>(); + } + + public void initialize() { + this.registerAll( + new ChickenPet(), new CowPet(), new ExperiencePet(), new IronGolemPet(), + new KrakenPet(), new SpiderPet(), new ValentinePet(), new WizardPet(), + new ProteinPet(), new TitanPet(), new SnowGolemPet(), new CagePet(), new ShieldPet() + ); + } + + public void registerAll(Pet... Pets) { + for (Pet set : Pets) { + this.register(set); + } + } + + public void register(Pet pet) { + try { + this.pets.put(pet.getID(), pet); + CrankedPets.getInstance().getServer().getPluginManager().registerEvents(pet, CrankedPets.getInstance()); + } catch (Exception e) { + Bukkit.getLogger().warning("Failed to register pet " + pet.getID()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.pets.clear(); + } + + public void unregister(Pet pet) { + this.pets.remove(pet.getID()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isPet(String name) { + return (this.getPetFromID(name) != null); + } + + public Pet getPetFromID(String id) { + Validate.notNull(id); + Validate.notEmpty(id); + return this.pets.get(id.toLowerCase()); + } + + public Pet getPetFromName(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + name = this.getPetIDFromName(name); + return this.pets.get(name.toLowerCase()); + } + + public String getPetIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getPets() { + return Collections.unmodifiableCollection(this.pets.values()); + } + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/struct/annotations/ConfigValue.java b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/annotations/ConfigValue.java new file mode 100644 index 0000000..2250daf --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/annotations/ConfigValue.java @@ -0,0 +1,19 @@ +package net.crankedpvp.crankedpets.struct.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * don't forget to not make the field final when using this annotation + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigValue { + + String path() default "pet."; + String name() default ""; + +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/struct/config/PetConfig.java b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/config/PetConfig.java new file mode 100644 index 0000000..153dbcb --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/config/PetConfig.java @@ -0,0 +1,118 @@ +package net.crankedpvp.crankedpets.struct.config; + +import lombok.AccessLevel; +import lombok.Getter; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.struct.Pet; +import net.crankedpvp.crankedpets.struct.annotations.ConfigValue; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; + +@Getter +public class PetConfig { + + @Getter(value = AccessLevel.PRIVATE) + private final CrankedPets plugin; + private final String path; + private FileConfiguration config; + private final File configFile; + private final Pet pet; + + public PetConfig(CrankedPets plugin, String path, Pet pet) { + this.plugin = plugin; + this.path = path; + this.pet = pet; + this.configFile = new File(plugin.getDataFolder(), path); + } + + public void setupConfigFile() { + this.createDefaultFile(); + this.config = YamlConfiguration.loadConfiguration(configFile); + + this.loadVariables(); + + boolean result = this.saveConfig(); + if (result) this.loadConfigFromDisk(); + + } + + public boolean saveConfig() { + try { + config.save(configFile); + return true; + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + path); + e.printStackTrace(); + } + return false; + } + + public void createDefaultFile() { + if (!configFile.exists()) { + try { + configFile.getParentFile().mkdirs(); + configFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().severe("Could not create config file for " + path); + e.printStackTrace(); + } + } + } + + public void reloadConfig() { + config = YamlConfiguration.loadConfiguration(configFile); + this.loadVariables(); + } + + public void loadConfigFromDisk() { + try { + config.load(configFile); + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Could not load config for " + path); + e.printStackTrace(); + } + } + + public void loadVariables() { + boolean needSave = false; + for (Field field : this.pet.getClass().getDeclaredFields()) { + + try { + field.setAccessible(true); + + if (field.isAnnotationPresent(ConfigValue.class)) { + ConfigValue annotationValue = field.getAnnotation(ConfigValue.class); + + String name = annotationValue.name().equals("") ? field.getName() : annotationValue.name(); + + String path = annotationValue.path().endsWith(".") ? annotationValue.path() : annotationValue.path() + "."; + + if (!this.config.contains(path + name)) { + this.config.set(path + name, field.get(this.pet)); + needSave = true; + continue; + } + + Object fieldValue = this.config.get(path + name); + + if (fieldValue instanceof String) fieldValue = CC.translate((String) fieldValue); + + field.set(this.pet, fieldValue); + } + } catch (IllegalAccessException | NullPointerException | IllegalArgumentException e) { + Bukkit.getConsoleSender().sendMessage(CC.translate("&c[CrankedPets] - Error invalid config value for pet " + pet.getName())); + } + } + if (needSave) { + saveConfig(); + reloadConfig(); + } + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/struct/config/PetConfigManager.java b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/config/PetConfigManager.java new file mode 100644 index 0000000..ecb0491 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/struct/config/PetConfigManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.crankedpets.struct.config; + +import lombok.Getter; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.struct.Pet; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class PetConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public PetConfigManager(CrankedPets plugin) { + for (Pet pet : plugin.getPetRegister().getPets()) { + PetConfig petConfig = new PetConfig(plugin, "pets/" + pet.getID() + ".yml", pet); + configs.put(pet, petConfig); + } + } + + public void setupFiles() { + configs.values().forEach(PetConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(PetConfig::reloadConfig); + } + + public PetConfig getAbstractConfig(Pet pet) { + return configs.get(pet); + } + + public FileConfiguration getConfig(Pet pet) { + return getAbstractConfig(pet).getConfig(); + } +} diff --git a/Pets/src/main/java/net/crankedpvp/crankedpets/tasks/PassivePetTask.java b/Pets/src/main/java/net/crankedpvp/crankedpets/tasks/PassivePetTask.java new file mode 100644 index 0000000..0626c43 --- /dev/null +++ b/Pets/src/main/java/net/crankedpvp/crankedpets/tasks/PassivePetTask.java @@ -0,0 +1,47 @@ +package net.crankedpvp.crankedpets.tasks; + +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.managers.PassivePetManager; +import net.crankedpvp.crankedpets.struct.PassivePet; +import net.crankedpvp.crankedpets.struct.Pet; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.*; +import java.util.stream.Collectors; + +public class PassivePetTask extends BukkitRunnable { + private final PassivePetManager passivePetManager = CrankedPets.instance.getPassivePetManager(); + + @Override + public void run() { + Map> mapCopy = new HashMap<>(passivePetManager.getPassivePetsMap()); + for (Map.Entry> entry : mapCopy.entrySet()) { + UUID uuid = entry.getKey(); + Player player = Bukkit.getPlayer(uuid); + if (player == null || !player.isOnline()) { + passivePetManager.getPassivePetsMap().remove(uuid); + continue; + } + List oldPets = entry.getValue(); + List currentPets = passivePetManager.getCurrentPassivePets(player); + + for (Pet pet : oldPets) { + if (!currentPets.contains(pet)) { + ((PassivePet)pet).disablePassiveAbility(player); + } + } + + + for (Pet pet : currentPets) { + ((PassivePet)pet).passiveAbility(player); + } + } + for (Player player : Bukkit.getOnlinePlayers()) { + passivePetManager.scanPlayerInventory(player); + } + } + + +} diff --git a/Pets/src/main/resources/language.yml b/Pets/src/main/resources/language.yml new file mode 100644 index 0000000..3d32273 --- /dev/null +++ b/Pets/src/main/resources/language.yml @@ -0,0 +1,17 @@ +INVALID_PET: "&c&l(!)&c Invalid pet name." + +ADMIN_COMMAND_HELP: + - "&8--- &3Cranked &fPets &8---" + - "&3/cp &fpet &7 [player]" + - +PASSIVE_PET: + - "&eWrite some stuff" + - "&7About how passive pets work" + +ADMIN_RELOADING: "&3&l(!) &7Reloading configs now..." +ADMIN_RELOADED: "&3&l(!) &7Reloaded configs and other cool stuff. Took &3%took%ms&7." + +PVP_DISABLED_REGION: "&d&lPets &8➥ &7You cannot use pets in a pvp-disabled region" +PET_ON_COOLDOWN: "&d&lPets &8➥ &7Your %pet% is still on cooldown for %timeLeft%." +PET_USED: "&d&lPets &8➥ &7you have &a&lACTIVATED&7 your %pet%&7." + diff --git a/Pets/src/main/resources/plugin.yml b/Pets/src/main/resources/plugin.yml new file mode 100644 index 0000000..c72dca5 --- /dev/null +++ b/Pets/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedPets +main: net.crankedpvp.crankedpets.CrankedPets +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/PlayerVaultsX/pom.xml b/PlayerVaultsX/pom.xml new file mode 100644 index 0000000..2da1e29 --- /dev/null +++ b/PlayerVaultsX/pom.xml @@ -0,0 +1,156 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + PlayerVaultsX + + + 8 + 8 + + + + clean install + PlayerVaultsX + + + true + src/main/resources/ + + *.yml + lang/*.yml + credit/*.txt + + + + + + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + false + + + net.kyori + com.drtshock.playervaults.lib.net.kyori + + + com.google.gson + com.drtshock.playervaults.lib.com.google.gson + + + org.kitteh + com.drtshock.playervaults.lib.org.kitteh + + + + + + package + + shade + + + + + + + + + + + fuuid-repo + https://github.com/factions-site/repo/raw/public + + + spigot-repo + https://hub.spigotmc.org/nexus/content/groups/public/ + + + sonatype + https://oss.sonatype.org/content/repositories/snapshots + + false + + + true + + + + jitpack.io + https://jitpack.io + + + + + + Utils + net.crankedpvp + + + net.kyori + adventure-platform-bukkit + 4.0.1 + compile + + + net.kyori + adventure-text-minimessage + 4.11.0 + compile + + + com.google.code.gson + gson + 2.8.8 + compile + + + org.kitteh + cardboardbox + 0.2.2 + compile + + + com.github.MilkBowl + VaultAPI + + + org.kitteh + paste-gg-api + 0.9.1 + compile + + + org.checkerframework + checker-qual + 3.3.0 + provided + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + + diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/Conversion.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/Conversion.java new file mode 100644 index 0000000..63bd916 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/Conversion.java @@ -0,0 +1,253 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults; + +import com.drtshock.playervaults.vaultmanagement.CardboardBoxSerialization; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.logging.Logger; + +class Conversion { + /** + * Fancy JSON serialization mostly by evilmidget38. + * + * @author evilmidget38, gomeow + */ + @SuppressWarnings("unchecked") + static class OldestSerialization { + private static Map toMap(JSONObject object) { + Map map = new HashMap<>(); + + // Weird case of bad meta causing null map to be passed here. + if (object == null) { + return map; + } + + for (Object key : object.keySet()) { + map.put(key.toString(), fromJson(object.get(key))); + } + return map; + } + + private static Object fromJson(Object json) { + if (json == null) { + return null; + } else if (json instanceof JSONObject) { + return toMap((JSONObject) json); + } else if (json instanceof JSONArray) { + return toList((JSONArray) json); + } else { + return json; + } + } + + private static List toList(JSONArray array) { + List list = new ArrayList<>(); + for (Object value : array) { + list.add(fromJson(value)); + } + return list; + } + + private static ItemStack[] getItems(List stringItems) { + List contents = new ArrayList<>(); + for (String piece : stringItems) { + if (piece.equalsIgnoreCase("null")) { + contents.add(null); + } else { + ItemStack item = (ItemStack) deserialize(toMap((JSONObject) JSONValue.parse(piece))); + contents.add(item); + } + } + ItemStack[] items = new ItemStack[contents.size()]; + for (int x = 0; x < contents.size(); x++) { + items[x] = contents.get(x); + } + return items; + } + + private static Map recreateMap(Map original) { + return new HashMap<>(original); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static Object deserialize(Map map) { + for (Entry entry : map.entrySet()) { + if (entry.getValue() instanceof Map) { + entry.setValue(deserialize((Map) entry.getValue())); + } else if (entry.getValue() instanceof Iterable) { + entry.setValue(convertIterable((Iterable) entry.getValue())); + } else if (entry.getValue() instanceof Number) { + entry.setValue(convertNumber((Number) entry.getValue())); + } + } + return map.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY) ? ConfigurationSerialization.deserializeObject(map) : map; + } + + private static List convertIterable(Iterable iterable) { + List newList = new ArrayList<>(); + for (Object object : iterable) { + if (object instanceof Map) { + object = deserialize((Map) object); + } else if (object instanceof List) { + object = convertIterable((Iterable) object); + } else if (object instanceof Number) { + object = convertNumber((Number) object); + } + newList.add(object); + } + return newList; + } + + private static Number convertNumber(Number number) { + if (number instanceof Long) { + Long longObj = (Long) number; + if (longObj == longObj.intValue()) { + return longObj.intValue(); + } + } + return number; + } + } + + static void convert(PlayerVaults plugin) { + Logger logger = plugin.getLogger(); + + File newDir = plugin.getVaultData(); + File oldVaults = plugin.getDataFolder().toPath().resolve("base64vaults").toFile(); + File reallyOldVaults = plugin.getDataFolder().toPath().resolve("uuidvaults").toFile(); + + if (newDir.exists()) { + plugin.getDataFolder().toPath().resolve("oldVaultsData").toFile().mkdirs(); + if (oldVaults.exists()) { + try { + Files.move(oldVaults.toPath(), plugin.getDataFolder().toPath().resolve("oldVaultsData").resolve("base64vaults")); + } catch (IOException e) { + plugin.getLogger().warning("Failed to move old vaults dir: " + e.getMessage()); + } + } + if (reallyOldVaults.exists()) { + try { + Files.move(reallyOldVaults.toPath(), plugin.getDataFolder().toPath().resolve("oldVaultsData").resolve("uuidvaults")); + } catch (IOException e) { + plugin.getLogger().warning("Failed to move old vaults dir: " + e.getMessage()); + } + } + return; + } + + newDir.mkdirs(); + + File oldDir; + boolean recent; + if (oldVaults.exists() && oldVaults.isDirectory()) { + logger.info("********** Starting data storage conversion **********"); + logger.info("This might take a while and might say \"unable to resolve\""); + logger.info(oldVaults.toString() + " will remain as a backup."); + recent = true; + oldDir = oldVaults; + } else if (reallyOldVaults.exists() && reallyOldVaults.isDirectory()) { + logger.info("********** Starting data storage conversion **********"); + logger.info("This might take a while and might say \"unable to resolve\""); + logger.info(reallyOldVaults.toString() + " will remain as a backup."); + recent = false; + oldDir = reallyOldVaults; + } else { + logger.info("No old vaults found to convert to new format. :)"); + return; + } + + int players = 0; + int vaults = 0; + int failed = 0; + for (File file : oldDir.listFiles()) { + if (file.isDirectory() || !file.getName().endsWith(".yml")) { + continue; // backups folder. + } + + FileConfiguration uuidFile = YamlConfiguration.loadConfiguration(file); + String stringUUID = file.getName().replace(".yml", ""); + + for (String key : uuidFile.getKeys(false)) { + if (!key.startsWith("vault")) { + continue; + } + + int vaultNumber = Integer.parseInt(key.replace("vault", "")); + + try { + + ItemStack[] contents; + if (recent) { + String data = uuidFile.getString(key); + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + contents = new ItemStack[dataInput.readInt()]; + // Read the serialized inventory + for (int i = 0; i < contents.length; i++) { + contents[i] = (ItemStack) dataInput.readObject(); + } + dataInput.close(); + } else { + ConfigurationSection section = uuidFile.getConfigurationSection(key); + List data = new ArrayList<>(); + for (String s : section.getKeys(false)) { + String value = section.getString(s); + data.add(value); + } + contents = OldestSerialization.getItems(data); + } + String newData = Base64Coder.encodeLines(CardboardBoxSerialization.writeInventory(contents)); + uuidFile.set(key, newData); + vaults++; + } catch (Exception e) { + logger.severe("Failed to parse vault " + vaultNumber + " for " + stringUUID); + failed++; + } + } + try { + uuidFile.save(newDir.toPath().resolve(file.getName()).toFile()); + } catch (IOException e) { + logger.severe("Failed to save new file " + file.getName()); + } + + players++; + } + + logger.info(String.format("Converted %d vaults for %d players to new storage. %d failed to convert", vaults, players, failed)); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/Metrics.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/Metrics.java new file mode 100644 index 0000000..caf9f92 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/Metrics.java @@ -0,0 +1,732 @@ +package com.drtshock.playervaults; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; + +import javax.net.ssl.HttpsURLConnection; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +// CONTAINS CUSTOM MODIFICATIONS + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Metrics { + + static { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'c', 'o', 'm', '.', 'd', 'r', 't', 's', 'h', 'o', 'c', 'k', '.', 'p', 'l', 'a', 'y', 'e', 'r', 'v', 'a', 'u', 'l', 't', 's'}); + if (!Metrics.class.getPackage().getName().equals(defaultPackage)) { + throw new IllegalStateException("You done screwed up! Go grab the right file to copy from bstats.org"); + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // The plugin id + private final int pluginId; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + * @param pluginId The id of the plugin. + * It can be found at What is my plugin id? + */ + public Metrics(Plugin plugin, int pluginId) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + this.pluginId = pluginId; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { + } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JsonObject getPluginData() { + JsonObject data = new JsonObject(); + + String pluginName = "PlayerVaultsX"; + String pluginVersion = plugin.getDescription().getVersion(); + + data.addProperty("pluginName", pluginName); // Append the name of the plugin + data.addProperty("id", pluginId); // Append the id of the plugin + data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin + JsonArray customCharts = new JsonArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JsonObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.add("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JsonObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + String bukkitName = Bukkit.getName(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JsonObject data = new JsonObject(); + + data.addProperty("serverUUID", serverUUID); + + data.addProperty("playerAmount", playerAmount); + data.addProperty("onlineMode", onlineMode); + data.addProperty("bukkitVersion", bukkitVersion); + data.addProperty("bukkitName", bukkitName); + + data.addProperty("javaVersion", javaVersion); + data.addProperty("osName", osName); + data.addProperty("osArch", osArch); + data.addProperty("osVersion", osVersion); + data.addProperty("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JsonObject data = getServerData(); + + JsonArray pluginData = new JsonArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); + if (plugin instanceof JsonObject) { + pluginData.add((JsonObject) plugin); + } else { // old bstats version compatibility + try { + Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); + if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { + Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); + jsonStringGetter.setAccessible(true); + String jsonString = (String) jsonStringGetter.invoke(plugin); + JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); + pluginData.add(object); + } + } catch (ClassNotFoundException e) { + // minecraft version 1.14+ + if (logFailedRequests) { + this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); + } + } + } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } + } + } catch (NoSuchFieldException ignored) { + } + } + + data.add("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(() -> { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JsonObject getRequestJsonObject() { + JsonObject chart = new JsonObject(); + chart.addProperty("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.add("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JsonObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObject value = new JsonObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.addProperty(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.add(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JsonArray categoryValues = new JsonArray(); + categoryValues.add(new JsonPrimitive(entry.getValue())); + values.add(entry.getKey(), categoryValues); + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JsonArray categoryValues = new JsonArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(new JsonPrimitive(categoryValue)); + } + values.add(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/PlayerVaults.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/PlayerVaults.java new file mode 100644 index 0000000..53a33cb --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/PlayerVaults.java @@ -0,0 +1,569 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults; + +import com.drtshock.playervaults.commands.*; +import com.drtshock.playervaults.config.Loader; +import com.drtshock.playervaults.config.file.Config; +import com.drtshock.playervaults.config.file.Translation; +import com.drtshock.playervaults.data.PlayerVaultsManager; +import com.drtshock.playervaults.listeners.Listeners; +import com.drtshock.playervaults.listeners.SignListener; +import com.drtshock.playervaults.listeners.VaultPreloadListener; +import com.drtshock.playervaults.tasks.Cleanup; +import com.drtshock.playervaults.vaultmanagement.EconomyOperations; +import com.drtshock.playervaults.vaultmanagement.VaultManager; +import com.drtshock.playervaults.vaultmanagement.VaultViewInfo; +import lombok.Getter; +import net.kyori.adventure.platform.bukkit.BukkitAudiences; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; +import sun.misc.Unsafe; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.regex.Pattern; + +public class PlayerVaults extends JavaPlugin { + public static boolean DEBUG; + private static PlayerVaults instance; + private final HashMap setSign = new HashMap<>(); + // Player name - VaultViewInfo + private final HashMap inVault = new HashMap<>(); + // VaultViewInfo - Inventory + private final HashMap openInventories = new HashMap<>(); + private final Set blockedMats = new HashSet<>(); + private boolean useVault; + private YamlConfiguration signs; + private File signsFile; + private boolean saveQueued; + private boolean backupsEnabled; + private File backupsFolder; + private File uuidData; + private File vaultData; + private String _versionString; + private int maxVaultAmountPermTest; + private Metrics metrics; + private final Config config = new Config(); + private BukkitAudiences platform; + private final Translation translation = new Translation(this); + private final List exceptions = new CopyOnWriteArrayList<>(); + @Getter + private PlayerVaultsManager playerVaultsManager; + + public static PlayerVaults getInstance() { + return instance; + } + + public static void debug(String s, long start) { + if (DEBUG) { + instance.getLogger().log(Level.INFO, "{0} took {1}ms", new Object[]{s, (System.currentTimeMillis() - start)}); + } + } + + public static void debug(String s) { + if (DEBUG) { + instance.getLogger().log(Level.INFO, s); + } + } + + @Override + public void onEnable() { + instance = this; + long start = System.currentTimeMillis(); + long time = System.currentTimeMillis(); + this.platform = BukkitAudiences.create(this); + debug("adventure!", time); + time = System.currentTimeMillis(); + loadConfig(); + DEBUG = getConf().isDebug(); + debug("config", time); + time = System.currentTimeMillis(); + vaultData = new File(this.getDataFolder(), "newvaults"); + Conversion.convert(this); + new VaultManager(this); + debug("conversion", time); + time = System.currentTimeMillis(); + debug("uuidvaultmanager", time); + time = System.currentTimeMillis(); + getServer().getPluginManager().registerEvents(new Listeners(this), this); + getServer().getPluginManager().registerEvents(new VaultPreloadListener(), this); + getServer().getPluginManager().registerEvents(new SignListener(this), this); + debug("registering listeners", time); + time = System.currentTimeMillis(); + this.backupsEnabled = this.getConf().getStorage().getFlatFile().isBackups(); + this.maxVaultAmountPermTest = this.getConf().getMaxVaultAmountPermTest(); + loadSigns(); + debug("loaded signs", time); + time = System.currentTimeMillis(); + getCommand("pv").setExecutor(new VaultCommand(this)); + getCommand("pvdel").setExecutor(new DeleteCommand(this)); + getCommand("pvconvert").setExecutor(new ConvertCommand(this)); + getCommand("pvsign").setExecutor(new SignCommand(this)); + this.getCommand("pvsearch").setExecutor(new SearchCommand()); + debug("registered commands", time); + time = System.currentTimeMillis(); + useVault = EconomyOperations.setup(); + debug("setup economy", time); + + if (getConf().getPurge().isEnabled()) { + getServer().getScheduler().runTaskAsynchronously(this, new Cleanup(getConf().getPurge().getDaysSinceLastEdit())); + } + + new BukkitRunnable() { + @Override + public void run() { + if (saveQueued) { + saveSignsFile(); + } + } + }.runTaskTimer(this, 20, 20); + + this.metrics = new Metrics(this, 6905); + Plugin vault = getServer().getPluginManager().getPlugin("Vault"); + this.metricsDrillPie("vault", () -> this.metricsPluginInfo(vault)); + if (vault != null) { + this.metricsDrillPie("vault_econ", () -> { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + entry.put(!this.useVault ? "none" : EconomyOperations.getName(), 1); + map.put(isEconomyEnabled() ? "enabled" : "disabled", entry); + return map; + }); + if (isEconomyEnabled()) { + String name = EconomyOperations.getName(); + if (name.equals("Essentials Economy")) { + name = "Essentials"; + } + if (name.equals("CMIEconomy")) { + name = "CMI"; + } + Plugin plugin = getServer().getPluginManager().getPlugin(name); + if (plugin != null) { + this.metricsDrillPie("vault_econ_plugins", () -> { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + entry.put(plugin.getDescription().getVersion(), 1); + map.put(plugin.getName(), entry); + return map; + }); + } + } + } + + if (vault != null) { + String name = EconomyOperations.getPermsName(); + if (name != null) { + Plugin plugin = getServer().getPluginManager().getPlugin(name); + final String version; + if (plugin == null) { + version = "unknown"; + } else { + version = plugin.getDescription().getVersion(); + } + this.metricsDrillPie("vault_perms", () -> { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + entry.put(version, 1); + map.put(name, entry); + return map; + }); + } + } + + this.metricsSimplePie("signs", () -> getConf().isSigns() ? "enabled" : "disabled"); + this.metricsSimplePie("cleanup", () -> getConf().getPurge().isEnabled() ? "enabled" : "disabled"); + + this.metricsDrillPie("block_items", () -> { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + if (getConf().getItemBlocking().isEnabled()) { + for (Material material : blockedMats) { + entry.put(material.toString(), 1); + } + } + if (entry.isEmpty()) { + entry.put("none", 1); + } + map.put(getConf().getItemBlocking().isEnabled() ? "enabled" : "disabled", entry); + return map; + }); + + try { + Field f = Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + Unsafe unsafe = (Unsafe) f.get(null); + + Class clazz = Class.forName(this.getServer().getClass().getPackage().getName() + ".util.CraftNBTTagConfigSerializer"); + Field field = clazz.getDeclaredField("INTEGER"); + + Pattern pattern = (Pattern) unsafe.getObject(clazz, unsafe.staticFieldOffset(field)); + + if (pattern.pattern().equals("[-+]?(?:0|[1-9][0-9]*)?i")) { + unsafe.putObject(clazz, unsafe.staticFieldOffset(field), Pattern.compile("[-+]?(?:0|[1-9][0-9]*)i", Pattern.CASE_INSENSITIVE)); + this.getLogger().info("Patched Spigot item storage bug."); + } + } catch (Exception ignored) { + // Don't worry about it. + } + + this.playerVaultsManager = new PlayerVaultsManager(); + this.playerVaultsManager.loadAll(); + + this.getLogger().info("Loaded! Took " + (System.currentTimeMillis() - start) + "ms"); + } + + private void metricsLine(String name, Callable callable) { + this.metrics.addCustomChart(new Metrics.SingleLineChart(name, callable)); + } + + private void metricsDrillPie(String name, Callable>> callable) { + this.metrics.addCustomChart(new Metrics.DrilldownPie(name, callable)); + } + + private void metricsSimplePie(String name, Callable callable) { + this.metrics.addCustomChart(new Metrics.SimplePie(name, callable)); + } + + private Map> metricsPluginInfo(Plugin plugin) { + return this.metricsInfo(plugin, () -> plugin.getDescription().getVersion()); + } + + private Map> metricsInfo(Object plugin, Supplier versionGetter) { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + entry.put(plugin == null ? "nope" : versionGetter.get(), 1); + map.put(plugin == null ? "absent" : "present", entry); + return map; + } + + @Override + public void onDisable() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (this.inVault.containsKey(player.getUniqueId().toString())) { + Inventory inventory = player.getOpenInventory().getTopInventory(); + if (inventory.getViewers().size() == 1) { + VaultViewInfo info = this.inVault.get(player.getUniqueId().toString()); + VaultManager.getInstance().saveVault(inventory, player.getUniqueId().toString(), info.getNumber()); + this.openInventories.remove(info.toString()); + // try this to make sure that they can't make further edits if the process hangs. + player.closeInventory(); + } + + this.inVault.remove(player.getUniqueId().toString()); + debug("Closing vault for " + player.getName()); + player.closeInventory(); + } + } + + if (getConf().getPurge().isEnabled()) { + saveSignsFile(); + } + + VaultManager.getInstance().getVaultCache().shutdown(); + + this.playerVaultsManager.saveAll(); + } + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { + if (cmd.getName().equalsIgnoreCase("pvreload")) { + reloadConfig(); + loadConfig(); // To update blocked materials. + reloadSigns(); + sender.sendMessage(ChatColor.GREEN + "Reloaded PlayerVault's configuration and lang files."); + } + return true; + } + + private void loadConfig() { + File configYaml = new File(this.getDataFolder(), "config.yml"); + if (!(new File(this.getDataFolder(), "config.conf").exists()) && configYaml.exists()) { + this.config.setFromConfig(this.getLogger(), this.getConfig()); + try { + Files.move(configYaml.toPath(), this.getDataFolder().toPath().resolve("old_unused_config.yml")); + } catch (Exception e) { + this.getLogger().log(Level.SEVERE, "Failed to move config for backup: " + e.getMessage()); + configYaml.deleteOnExit(); + } + } + + try { + Loader.loadAndSave("config", this.config); + } catch (IOException | IllegalAccessException e) { + this.getLogger().log(Level.SEVERE, "Could not load config.", e); + } + + // Clear just in case this is a reload. + blockedMats.clear(); + if (getConf().getItemBlocking().isEnabled()) { + for (String s : getConf().getItemBlocking().getList()) { + Material mat = Material.matchMaterial(s); + if (mat != null) { + blockedMats.add(mat); + getLogger().log(Level.INFO, "Added {0} to list of blocked materials.", mat.name()); + } + } + } + + File lang = new File(this.getDataFolder(), "lang"); + if (lang.exists()) { + this.getLogger().warning("There is no clean way for us to migrate your old lang data."); + this.getLogger().warning("If you made any customizations, or used another language, you need to migrate the info to the new format in lang.conf"); + try { + Files.move(lang.toPath(), lang.getParentFile().toPath().resolve("old_unused_lang")); + } catch (Exception e) { + this.getLogger().log(Level.SEVERE, "Failed to rename lang folder as it is no longer used: " + e.getMessage()); + configYaml.deleteOnExit(); + } + } + + try { + Loader.loadAndSave("lang", this.translation); + } catch (IOException | IllegalAccessException e) { + this.getLogger().log(Level.SEVERE, "Could not load lang.", e); + } + } + + public Config getConf() { + return this.config; + } + + private void loadSigns() { + File signs = new File(getDataFolder(), "signs.yml"); + if (!signs.exists()) { + try { + signs.createNewFile(); + } catch (IOException e) { + getLogger().severe("PlayerVaults has encountered a fatal error trying to load the signs file."); + getLogger().severe("Please report this error on GitHub @ https://github.com/drtshock/PlayerVaults/"); + e.printStackTrace(); + } + } + this.signsFile = signs; + this.signs = YamlConfiguration.loadConfiguration(signs); + } + + private void reloadSigns() { + if (!getConf().isSigns()) { + return; + } + if (!signsFile.exists()) loadSigns(); + try { + signs.load(signsFile); + } catch (IOException | InvalidConfigurationException e) { + getLogger().severe("PlayerVaults has encountered a fatal error trying to reload the signs file."); + getLogger().severe("Please report this error on GitHub @ https://github.com/drtshock/PlayerVaults/"); + e.printStackTrace(); + } + } + + /** + * Get the signs.yml config. + * + * @return The signs.yml config. + */ + public YamlConfiguration getSigns() { + return this.signs; + } + + /** + * Save the signs.yml file. + */ + public void saveSigns() { + saveQueued = true; + } + + private void saveSignsFile() { + if (!getConf().isSigns()) { + return; + } + + saveQueued = false; + try { + signs.save(this.signsFile); + } catch (IOException e) { + getLogger().severe("PlayerVaults has encountered an error trying to save the signs file."); + getLogger().severe("Please report this error on GitHub @ https://github.com/drtshock/PlayerVaults/"); + e.printStackTrace(); + } + } + + public HashMap getSetSign() { + return this.setSign; + } + + public HashMap getInVault() { + return this.inVault; + } + + public HashMap getOpenInventories() { + return this.openInventories; + } + + public boolean isEconomyEnabled() { + return this.getConf().getEconomy().isEnabled() && this.useVault; + } + + public File getVaultData() { + return this.vaultData; + } + + /** + * Get the legacy UUID vault data folder. + * Deprecated in favor of base64 data. + * + * @return uuid folder + */ + @Deprecated + public File getUuidData() { + return this.uuidData; + } + + public boolean isBackupsEnabled() { + return this.backupsEnabled; + } + + public File getBackupsFolder() { + // having this in #onEnable() creates the 'uuidvaults' directory, preventing the conversion from running + if (this.backupsFolder == null) { + this.backupsFolder = new File(this.getVaultData(), "backups"); + this.backupsFolder.mkdirs(); + } + + return this.backupsFolder; + } + + /** + * Tries to get a name from a given String that we hope is a UUID. + * + * @param potentialUUID - potential UUID to try to get the name for. + * @return the player's name if we can find it, otherwise return what got passed to us. + */ + public String getNameIfPlayer(String potentialUUID) { + UUID uuid; + try { + uuid = UUID.fromString(potentialUUID); + } catch (Exception e) { + return potentialUUID; + } + + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); + return offlinePlayer != null ? offlinePlayer.getName() : potentialUUID; + } + + public boolean isBlockedMaterial(Material mat) { + return blockedMats.contains(mat); + } + + /** + * Tries to grab the server version as a string. + * + * @return Version as raw string + */ + public String getVersion() { + if (_versionString == null) { + final String name = Bukkit.getServer().getClass().getPackage().getName(); + _versionString = name.substring(name.lastIndexOf(46) + 1) + "."; + } + return _versionString; + } + + public int getDefaultVaultRows() { + int def = this.config.getDefaultVaultRows(); + return (def >= 1 && def <= 6) ? def : 6; + } + + public int getDefaultVaultSize() { + return this.getDefaultVaultRows() * 9; + } + + public boolean isSign(Material mat) { + return mat.name().toUpperCase().contains("SIGN"); + } + + public int getMaxVaultAmountPermTest() { + return this.maxVaultAmountPermTest; + } + + public BukkitAudiences getPlatform() { + return this.platform; + } + + public Translation getTL() { + return this.translation; + } + + public String getVaultTitle(String id) { + return this.translation.vaultTitle().with("vault", id).getLegacy(); + } + + public String getExceptions() { + if (this.exceptions.isEmpty()) { + return null; + } + StringBuilder builder = new StringBuilder(); + boolean more = false; + for (String e : this.exceptions) { + if (more) { + builder.append("\n\n"); + } else { + more = true; + } + builder.append(e); + } + return builder.toString(); + } + + public T addException(T t) { + if (this.getConf().isDebug()) { + StringBuilder builder = new StringBuilder(); + builder.append(ZonedDateTime.now(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))).append('\n'); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + t.printStackTrace(printWriter); + builder.append(stringWriter.toString()); + this.exceptions.add(builder.toString()); + } + return t; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/ConvertCommand.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/ConvertCommand.java new file mode 100644 index 0000000..4f1ce56 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/ConvertCommand.java @@ -0,0 +1,82 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.commands; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.converters.BackpackConverter; +import com.drtshock.playervaults.converters.Converter; +import com.drtshock.playervaults.vaultmanagement.VaultOperations; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.List; + +public class ConvertCommand implements CommandExecutor { + + private final List converters = new ArrayList<>(); + private final PlayerVaults plugin; + + public ConvertCommand(PlayerVaults plugin) { + converters.add(new BackpackConverter()); + this.plugin = plugin; + } + + @Override + public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) { + if (!sender.hasPermission("playervaults.convert")) { + this.plugin.getTL().noPerms().title().send(sender); + } else { + if (args.length == 0) { + sender.sendMessage("/" + label + " "); + } else { + String name = args[0]; + final List applicableConverters = new ArrayList<>(); + if (name.equalsIgnoreCase("all")) { + applicableConverters.addAll(converters); + } else { + for (Converter converter : converters) { + if (converter.getName().equalsIgnoreCase(name)) { + applicableConverters.add(converter); + } + } + } + if (applicableConverters.size() <= 0) { + this.plugin.getTL().convertPluginNotFound().title().send(sender); + } else { + // Fork into background + this.plugin.getTL().convertBackground().title().send(sender); + PlayerVaults.getInstance().getServer().getScheduler().runTaskLaterAsynchronously(PlayerVaults.getInstance(), () -> { + int converted = 0; + VaultOperations.setLocked(true); + for (Converter converter : applicableConverters) { + if (converter.canConvert()) { + converted += converter.run(sender); + } + } + VaultOperations.setLocked(false); + this.plugin.getTL().convertComplete().title().with("count", converted + "").send(sender); + }, 5); + } + } + } + return true; + } +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/DeleteCommand.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/DeleteCommand.java new file mode 100644 index 0000000..23c40ca --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/DeleteCommand.java @@ -0,0 +1,79 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.commands; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.vaultmanagement.VaultManager; +import com.drtshock.playervaults.vaultmanagement.VaultOperations; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class DeleteCommand implements CommandExecutor { + private final PlayerVaults plugin; + + public DeleteCommand(PlayerVaults plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (VaultOperations.isLocked()) { + this.plugin.getTL().locked().title().send(sender); + return true; + } + switch (args.length) { + case 1: + if (sender instanceof Player) { + VaultOperations.deleteOwnVault((Player) sender, args[0]); + } else { + this.plugin.getTL().playerOnly().title().send(sender); + } + break; + case 2: + OfflinePlayer searchPlayer = Bukkit.getOfflinePlayer(args[0]); + String target = args[0]; + if (searchPlayer != null && searchPlayer.hasPlayedBefore()) { + target = searchPlayer.getUniqueId().toString(); + } + + // TODO: fix the stupid message inconsistencies where sometimes this class sends, sometimes vaultops does. + if (args[1].equalsIgnoreCase("all")) { + if (sender.hasPermission("playervaults.delete.all")) { + VaultManager.getInstance().deleteAllVaults(target); + this.plugin.getTL().deleteOtherVaultAll().title().with("player", target).send(sender); + PlayerVaults.getInstance().getLogger().info(String.format("%s deleted ALL vaults belonging to %s", sender.getName(), target)); + } else { + this.plugin.getTL().noPerms().title().send(sender); + } + + } + VaultOperations.deleteOtherVault(sender, target, args[1]); + break; + default: + sender.sendMessage("/" + label + " "); + sender.sendMessage("/" + label + " "); + sender.sendMessage("/" + label + " all"); + } + return true; + } +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SearchCommand.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SearchCommand.java new file mode 100644 index 0000000..6327add --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SearchCommand.java @@ -0,0 +1,129 @@ +package com.drtshock.playervaults.commands; + + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.guis.SearchGUI; +import com.drtshock.playervaults.utils.CC; +import com.drtshock.playervaults.vaultmanagement.VaultManager; +import com.drtshock.playervaults.vaultmanagement.VaultOperations; +import com.drtshock.playervaults.vaultmanagement.VaultViewInfo; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +public class SearchCommand implements CommandExecutor { + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] array) { + if (VaultOperations.isLocked()) { + commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7Vaults are locked!")); + return true; + } else { + switch(array.length) { + case 0: + if (commandSender instanceof Player) { + commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7/pvsearch ")); + if (commandSender.hasPermission("playervaults.search.other")) { + commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7/pvsearch ")); + } + return true; + } + case 1: + if (commandSender instanceof Player) { + this.search((Player)commandSender, array[0], (Player)commandSender); + } else { + commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7Only players can execute this command!")); + } + + return true; + case 2: + if (!(commandSender instanceof Player)) { + return true; + } else if (!commandSender.hasPermission("playervaults.search.other")) { + commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7No perms to search other players' pv!")); + return true; + } else { + if (Bukkit.getPlayer(array[1]) == null) { + commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7No online player found with this name")); + return true; + } + + this.search((Player)commandSender, array[0], Bukkit.getPlayer(array[1])); + return true; + } + default: + commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7/pvsearch ")); + if (commandSender.hasPermission("playervaults.search.other")) { + commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7/pvsearch ")); + + } + return true; + } + } + } + + public static void openVault(Player player, UUID otherUUID, int vaultNr) { + if (VaultOperations.openOtherVault(player, otherUUID.toString(), String.valueOf(vaultNr))) { + PlayerVaults.getInstance().getInVault().put(player.getUniqueId().toString(), new VaultViewInfo(otherUUID.toString(), vaultNr)); + } + + } + + private void search(Player executor, String itemName, Player findFor) { + Map> found = new HashMap<>(); + itemName = itemName.toLowerCase(); + YamlConfiguration yamlConfiguration = VaultManager.getInstance().getPlayerVaultFile(findFor.getPlayer().getUniqueId().toString(), false); + if (yamlConfiguration == null) { + executor.sendMessage("&b&lVaults &8➥ &7You have no vaults to search trough."); + } else { + executor.sendMessage(CC.translate("&b&lVaults &8➥ &7Executing vault search query on &f\"" + itemName + "\"&7.")); + Iterator var6 = yamlConfiguration.getKeys(false).iterator(); + + label48: + while(true) { + int pvNumber; + Inventory inventory; + do { + if (!var6.hasNext()) { + break label48; + } + + String str = (String)var6.next(); + pvNumber = Integer.parseInt(str.replace("vault", "")); + inventory = VaultManager.getInstance().getVault(findFor.getUniqueId().toString(), pvNumber); + } while(inventory.getContents().length == 0); + + ArrayList arrayFoundItems = new ArrayList<>(); + ItemStack[] var11 = inventory.getContents(); + + for (ItemStack item : var11) { + if (item != null && item.hasItemMeta() && item.getItemMeta().getDisplayName() != null) { + String displayName = ChatColor.stripColor(item.getItemMeta().getDisplayName()).toLowerCase(); + if (displayName.contains(itemName) && !found.containsKey(pvNumber)) { + arrayFoundItems.add(item); + } + } + } + + if (!arrayFoundItems.isEmpty()) { + found.put(pvNumber, arrayFoundItems); + } + } + } + + Map> sortedFound = new TreeMap<>(found); + if (sortedFound.isEmpty()) { + executor.sendMessage(CC.translate("&b&lVaults &8➥ &7No items found containing &f\"" + itemName + "\" &7in their name.")); + } else { + SearchGUI searchCommand = new SearchGUI(executor, findFor, sortedFound); + searchCommand.getExpShopUI().open(executor); + } + + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SignCommand.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SignCommand.java new file mode 100644 index 0000000..901bd4e --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SignCommand.java @@ -0,0 +1,76 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.commands; + +import com.drtshock.playervaults.PlayerVaults; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class SignCommand implements CommandExecutor { + private final PlayerVaults plugin; + + public SignCommand(PlayerVaults plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (sender.hasPermission("playervaults.signs.set")) { + if (!PlayerVaults.getInstance().getConf().isSigns()) { + this.plugin.getTL().signsDisabled().title().send(sender); + return true; + } + if (sender instanceof Player) { + if (args.length == 1) { + int i; + try { + i = Integer.parseInt(args[0]); + } catch (NumberFormatException nfe) { + this.plugin.getTL().mustBeNumber().title().send(sender); + sender.sendMessage(" /" + label + " [owner] <#>"); + return true; + } + PlayerVaults.getInstance().getSetSign().put(sender.getName(), new SignSetInfo(i)); + this.plugin.getTL().clickASign().title().send(sender); + } else if (args.length >= 2) { + int i; + try { + i = Integer.parseInt(args[1]); + } catch (NumberFormatException nfe) { + this.plugin.getTL().mustBeNumber().title().send(sender); + sender.sendMessage(" /" + label + " [owner] <#>"); + return true; + } + PlayerVaults.getInstance().getSetSign().put(sender.getName(), new SignSetInfo(args[0].toLowerCase(), i)); + this.plugin.getTL().clickASign().title().send(sender); + } else { + this.plugin.getTL().invalidArgs().title().send(sender); + } + } else { + this.plugin.getTL().playerOnly().title().send(sender); + } + } else { + this.plugin.getTL().noPerms().title().send(sender); + } + + return true; + } +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SignSetInfo.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SignSetInfo.java new file mode 100644 index 0000000..6be709d --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/SignSetInfo.java @@ -0,0 +1,78 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.commands; + +/** + * A class for setting signs. Stores information about the sign owner, number, and whether or not is opens a self vault + * or another person's vault. + */ +public class SignSetInfo { + + private final int number; + private String owner; + private boolean self = false; + + /** + * Construct a SignSetInfo object for another person. + * + * @param s The vault owner. + * @param i The vault number. + */ + public SignSetInfo(String s, int i) { + this.owner = s; + this.number = i; + } + + /** + * Construct a SignSetInfo object for opening to self. + * + * @param i The vault number. + */ + public SignSetInfo(int i) { + this.number = i; + this.self = true; + } + + /** + * Get whether or not the sign will open their own vault or another person's. + * + * @return Whether or not it is a 'self' sign. + */ + public boolean isSelf() { + return this.self; + } + + /** + * Get the owner of the vault. + * + * @return The owner of the vault. + */ + public String getOwner() { + return this.owner; + } + + /** + * Get the vault number. + * + * @return The vault number. + */ + public int getChest() { + return this.number; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/VaultCommand.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/VaultCommand.java new file mode 100644 index 0000000..241d103 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/commands/VaultCommand.java @@ -0,0 +1,130 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.commands; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.data.PlayerVaultsManager; +import com.drtshock.playervaults.data.PlayerVaultsPlayer; +import com.drtshock.playervaults.guis.SelectPlayerVaultInventory; +import com.drtshock.playervaults.vaultmanagement.VaultManager; +import com.drtshock.playervaults.vaultmanagement.VaultOperations; +import com.drtshock.playervaults.vaultmanagement.VaultViewInfo; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +public class VaultCommand implements CommandExecutor { + private final PlayerVaults plugin; + + public VaultCommand(PlayerVaults plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (VaultOperations.isLocked()) { + this.plugin.getTL().locked().title().send(sender); + return true; + } + + if (sender instanceof Player) { + Player player = (Player) sender; + if (PlayerVaults.getInstance().getInVault().containsKey(player.getUniqueId().toString())) { + // don't let them open another vault. + return true; + } + + switch (args.length) { + case 1: + if (args[0].equalsIgnoreCase("search")) { + sender.sendMessage(this.plugin.getTL().title() + "/pvsearch "); + return true; + } + if (VaultOperations.openOwnVault(player, args[0], true)) { + PlayerVaults.getInstance().getInVault().put(player.getUniqueId().toString(), new VaultViewInfo(player.getUniqueId().toString(), Integer.parseInt(args[0]))); + } else if (sender.hasPermission("playervaults.admin")) { + OfflinePlayer searchPlayer = Bukkit.getOfflinePlayer(args[0]); + String target = args[0]; + if (searchPlayer != null && searchPlayer.hasPlayedBefore()) { + target = searchPlayer.getUniqueId().toString(); + } + + YamlConfiguration file = VaultManager.getInstance().getPlayerVaultFile(target, false); + if (file == null) { + this.plugin.getTL().vaultDoesNotExist().title().send(sender); + } else { + StringBuilder sb = new StringBuilder(); + for (String key : file.getKeys(false)) { + sb.append(key.replace("vault", "")).append(" "); + } + + this.plugin.getTL().existingVaults().title().with("player", args[0]).with("vault", sb.toString().trim()).send(sender); + } + } + break; + case 2: + if (args[0].equalsIgnoreCase("search")) { + sender.sendMessage(this.plugin.getTL().title() + "/pvsearch "); + return true; + } + if (!player.hasPermission("playervaults.admin")) { + this.plugin.getTL().noPerms().title().send(sender); + break; + } + + int number; + try { + number = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + this.plugin.getTL().mustBeNumber().title().send(sender); + return true; + } + + String target = args[0]; + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[0]); + if (offlinePlayer != null && offlinePlayer.hasPlayedBefore()) { + target = offlinePlayer.getUniqueId().toString(); + } + if (VaultOperations.openOtherVault(player, target, args[1])) { + PlayerVaults.getInstance().getInVault().put(player.getUniqueId().toString(), new VaultViewInfo(target, number)); + } else { + this.plugin.getTL().noOwnerFound().title().with("player", args[0]).send(sender); + } + break; + default: + PlayerVaultsManager playerVaultsManager = this.plugin.getPlayerVaultsManager(); + if(playerVaultsManager.containsKey(player.getUniqueId())) { + SelectPlayerVaultInventory selectPlayerVaultInventory = new SelectPlayerVaultInventory(playerVaultsManager.getFromCache(player.getUniqueId())); + selectPlayerVaultInventory.getSelectPVInventory().open(player); + return true; + } + playerVaultsManager.addToCache(new PlayerVaultsPlayer(player.getUniqueId())); + //this.plugin.getTL().help().title().send(sender); + } + } else { + this.plugin.getTL().playerOnly().title().send(sender); + } + + return true; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/ConfigManager.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/ConfigManager.java new file mode 100644 index 0000000..fe07d9d --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/ConfigManager.java @@ -0,0 +1,47 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.drtshock.playervaults.config; + + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.config.file.Config; +import org.checkerframework.checker.nullness.qual.NonNull; + +import java.io.IOException; +import java.util.logging.Level; + +public class ConfigManager { + private final PlayerVaults plugin; + private final Config config = new Config(); + + public ConfigManager(@NonNull PlayerVaults plugin) { + this.plugin = plugin; + } + + public void loadConfig() { + try { + Loader.loadAndSave("main", this.config); + } catch (IOException | IllegalAccessException e) { + this.plugin.getLogger().log(Level.SEVERE, "Could not load config. Using all default values until resolved.", e); + } + } + + public @NonNull Config getConf() { + return this.config; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/Loader.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/Loader.java new file mode 100644 index 0000000..0dd9759 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/Loader.java @@ -0,0 +1,200 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.drtshock.playervaults.config; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.config.annotation.Comment; +import com.drtshock.playervaults.config.annotation.ConfigName; +import com.drtshock.playervaults.config.annotation.WipeOnReload; +import com.drtshock.playervaults.config.file.Translation; +import com.drtshock.playervaults.lib.com.typesafe.config.Config; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigFactory; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueFactory; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class Loader { + public static void loadAndSave(@NonNull String fileName, @NonNull Object config) throws IOException, IllegalAccessException { + File file = Loader.getFile(fileName); + Loader.loadAndSave(file, Loader.getConf(file), config); + } + + public static @NonNull File getFile(@NonNull String file) { + Path configFolder = PlayerVaults.getInstance().getDataFolder().toPath(); + if (!configFolder.toFile().exists()) { + configFolder.toFile().mkdir(); + } + Path path = configFolder.resolve(file + ".conf"); + return path.toFile(); + } + + public static @NonNull Config getConf(@NonNull File file) { + return ConfigFactory.parseFile(file); + } + + public static void loadAndSave(@NonNull File file, @NonNull Config config, @NonNull Object configObject) throws IOException, IllegalAccessException { + ConfigValue value = Loader.loadNode(config, configObject); + String s = value.render(ConfigRenderOptions.defaults().setOriginComments(false).setComments(true).setJson(false)); + Files.write(file.toPath(), s.getBytes(StandardCharsets.UTF_8)); + } + + public static @NonNull ConfigValue load(Config config, Object configObject) throws IllegalAccessException { + return Loader.loadNode(config, configObject); + } + + private static final Set> types = new HashSet<>(); + + static { + Loader.types.add(Boolean.TYPE); + Loader.types.add(Byte.TYPE); + Loader.types.add(Character.TYPE); + Loader.types.add(Double.TYPE); + Loader.types.add(Float.TYPE); + Loader.types.add(Integer.TYPE); + Loader.types.add(Long.TYPE); + Loader.types.add(Short.TYPE); + Loader.types.add(List.class); + Loader.types.add(Map.class); + Loader.types.add(Set.class); + Loader.types.add(String.class); + Loader.types.add(Translation.TL.class); + } + + private static @NonNull ConfigValue loadNode(@NonNull Config config, @NonNull Object object) throws IllegalAccessException { + return loadNode(config, "", object); + } + + private static @NonNull ConfigValue loadNode(@NonNull Config config, String path, @NonNull Object object) throws IllegalAccessException { + Map map = new HashMap<>(); + for (Field field : Loader.getFields(object.getClass())) { + if (field.isSynthetic()) { + continue; + } + if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { + if (field.getAnnotation(WipeOnReload.class) != null) { + field.setAccessible(true); + field.set(object, null); + } + continue; + } + field.setAccessible(true); + ConfigName configName = field.getAnnotation(ConfigName.class); + Comment comment = field.getAnnotation(Comment.class); + String confName = configName == null || configName.value().isEmpty() ? field.getName() : configName.value(); + String newPath = path.isEmpty() ? confName : (path + '.' + confName); + ConfigValue curValue = Loader.getOrNull(config, newPath); + boolean needsValue = curValue == null; + + ConfigValue newValue; + Object defaultValue = field.get(object); + if (Loader.types.contains(field.getType())) { + if (needsValue) { + if (Translation.TL.class.isAssignableFrom(field.getType())) { + Translation.TL tl = (Translation.TL) defaultValue; + newValue = tl.size() == 1 ? ConfigValueFactory.fromAnyRef(tl.get(0)) : ConfigValueFactory.fromAnyRef(tl); + } else { + newValue = ConfigValueFactory.fromAnyRef(defaultValue); + } + } else { + dance: + try { + if (Translation.TL.class.isAssignableFrom(field.getType())) { + Translation.TL tl; + if (curValue.valueType() == ConfigValueType.STRING) { + String s = curValue.unwrapped().toString(); + tl = Translation.TL.copyOf(Collections.singletonList(s)); + } else if (curValue.valueType() == ConfigValueType.LIST) { + List l = (List) curValue.unwrapped(); + tl = Translation.TL.copyOf(l); + } else { + tl = (Translation.TL) defaultValue; + } + newValue = tl.size() == 1 ? ConfigValueFactory.fromAnyRef(tl.get(0)) : ConfigValueFactory.fromAnyRef(tl); + field.set(object, tl); + break dance; + } + if (List.class.isAssignableFrom(field.getType()) && curValue.valueType() == ConfigValueType.STRING) { + List list = Collections.singletonList(curValue.unwrapped()); + field.set(object, list); + newValue = ConfigValueFactory.fromAnyRef(list); + break dance; + } else if (Set.class.isAssignableFrom(field.getType()) && curValue.valueType() == ConfigValueType.STRING) { + Set set = Collections.singleton(curValue.unwrapped()); + field.set(object, set); + newValue = ConfigValueFactory.fromAnyRef(set); + break dance; + } else if (Set.class.isAssignableFrom(field.getType()) && curValue.valueType() == ConfigValueType.LIST) { + field.set(object, new HashSet((List) curValue.unwrapped())); + } else { + field.set(object, curValue.unwrapped()); + } + newValue = curValue; + } catch (IllegalArgumentException ex) { + PlayerVaults.getInstance().getLogger().warning("Found incorrect type for " + confName + ": Expected " + field.getType() + ", found " + curValue.unwrapped().getClass()); + field.set(object, defaultValue); + newValue = ConfigValueFactory.fromAnyRef(defaultValue); + } + } + } else { + newValue = Loader.loadNode(config, newPath, defaultValue); + } + if (comment != null) { + newValue = newValue.withOrigin(newValue.origin().withComments(Arrays.asList(comment.value().split("\n")))); + } + map.put(confName, newValue); + } + return ConfigValueFactory.fromMap(map); + } + + private static @Nullable ConfigValue getOrNull(@NonNull Config config, @NonNull String path) { + return config.hasPath(path) ? config.getValue(path) : null; + } + + private static @NonNull List getFields(@NonNull Class clazz) { + return Loader.getFields(new ArrayList<>(), clazz); + } + + private static @NonNull List getFields(@NonNull List fields, @NonNull Class clazz) { + fields.addAll(Arrays.asList(clazz.getDeclaredFields())); + + if (clazz.getSuperclass() != null) { + Loader.getFields(fields, clazz.getSuperclass()); + } + + return fields; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/Comment.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/Comment.java new file mode 100644 index 0000000..902d8fe --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/Comment.java @@ -0,0 +1,31 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.drtshock.playervaults.config.annotation; + +import org.checkerframework.checker.nullness.qual.NonNull; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Comment { + @NonNull String value(); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/ConfigName.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/ConfigName.java new file mode 100644 index 0000000..2d802cc --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/ConfigName.java @@ -0,0 +1,31 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.drtshock.playervaults.config.annotation; + +import org.checkerframework.checker.nullness.qual.NonNull; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ConfigName { + @NonNull String value(); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/WipeOnReload.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/WipeOnReload.java new file mode 100644 index 0000000..764110c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/annotation/WipeOnReload.java @@ -0,0 +1,28 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.drtshock.playervaults.config.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface WipeOnReload { +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/file/Config.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/file/Config.java new file mode 100644 index 0000000..71d8f23 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/file/Config.java @@ -0,0 +1,210 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.drtshock.playervaults.config.file; + +import com.drtshock.playervaults.config.annotation.Comment; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.logging.Logger; + +@SuppressWarnings({"FieldMayBeFinal", "FieldCanBeLocal", "InnerClassMayBeStatic", "unused"}) +public class Config { + public class Block { + private boolean enabled = true; + @Comment("Material list for blocked items (does not support ID's), only effective if the feature is enabled.\n" + + " If you don't know material names: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html") + private List list = new ArrayList() { + { + this.add("PUMPKIN"); + this.add("DIAMOND_BLOCK"); + } + }; + + public boolean isEnabled() { + return this.enabled; + } + + public List getList() { + if (this.list == null) { + this.list = new ArrayList<>(); + } + return Collections.unmodifiableList(list); + } + } + + public class Economy { + @Comment("Set me to true to enable economy features!") + private boolean enabled = false; + private double feeToCreate = 100; + private double feeToOpen = 10; + private double refundOnDelete = 50; + + public boolean isEnabled() { + return this.enabled; + } + + public double getFeeToCreate() { + return this.feeToCreate; + } + + public double getFeeToOpen() { + return this.feeToOpen; + } + + public double getRefundOnDelete() { + return this.refundOnDelete; + } + } + + public class PurgePlanet { + private boolean enabled = false; + @Comment("Time, in days, since last edit") + private int daysSinceLastEdit = 30; + + public boolean isEnabled() { + return this.enabled; + } + + public int getDaysSinceLastEdit() { + return this.daysSinceLastEdit; + } + } + + public class Storage { + public class FlatFile { + @Comment("Backups\n" + + " Enabling this will create backups of vaults automagically.") + private boolean backups = true; + + public boolean isBackups() { + return this.backups; + } + } + + private FlatFile flatFile = new FlatFile(); + private String storageType = "flatfile"; + + public FlatFile getFlatFile() { + return this.flatFile; + } + + public String getStorageType() { + return this.storageType; + } + } + + @Comment("PlayerVaults\n" + + "Created by: https://github.com/drtshock/PlayerVaults/graphs/contributors/\n" + + "Resource page: https://www.spigotmc.org/resources/51204/\n" + + "Discord server: https://discordapp.com/invite/JZcWDEt/\n" + + "Made with love <3") + private boolean aPleasantHello = true; + + @Comment("Debug Mode\n" + + " This will print everything the plugin is doing to console.\n" + + " You should only enable this if you're working with a contributor to fix something.") + private boolean debug = false; + + @Comment("Can be 1 through 6.\n" + + "Default: 6") + private int defaultVaultRows = 6; + + @Comment("Signs\n" + + " This will determine whether vault signs are enabled.\n" + + " If you don't know what this is or if it's for you, see the resource page.") + private boolean signs = false; + + @Comment("Economy\n" + + " These are all of the settings for the economy integration. (Requires Vault)\n" + + " Bypass permission is: playervaults.free") + private Economy economy = new Economy(); + + @Comment("Blocked Items\n" + + " This will allow you to block specific materials from vaults.\n" + + " Bypass permission is: playervaults.bypassblockeditems") + private Block itemBlocking = new Block(); + + @Comment("Cleanup\n" + + " Enabling this will purge vaults that haven't been touched in the specified time frame.\n" + + " Reminder: This is only checked during startup.\n" + + " This will not lag your server or touch the backups folder.") + private PurgePlanet purge = new PurgePlanet(); + + @Comment("Sets the highest vault amount this plugin will test perms for") + private int maxVaultAmountPermTest = 99; + + @Comment("Storage option. Currently only flatfile, but soon more! :)") + private Storage storage = new Storage(); + + public void setFromConfig(Logger l, FileConfiguration c) { + l.info("Importing old configuration..."); + l.info("debug = " + (this.debug = c.getBoolean("debug", false))); + l.info("signs = " + (this.signs = c.getBoolean("signs-enabled", false))); + l.info("economy enabled = " + (this.economy.enabled = c.getBoolean("economy.enabled", false))); + l.info(" creation fee = " + (this.economy.feeToCreate = c.getDouble("economy.cost-to-create", 100))); + l.info(" open fee = " + (this.economy.feeToOpen = c.getDouble("economy.cost-to-open", 10))); + l.info(" refund = " + (this.economy.refundOnDelete = c.getDouble("economy.refund-on-delete", 50))); + l.info("item blocking enabled = " + (this.itemBlocking.enabled = c.getBoolean("blockitems", true))); + l.info("blocked items = " + (this.itemBlocking.list = c.getStringList("blocked-items"))); + if (this.itemBlocking.list == null) { + this.itemBlocking.list = new ArrayList<>(); + this.itemBlocking.list.add("PUMPKIN"); + this.itemBlocking.list.add("DIAMOND_BLOCK"); + l.info(" set defaults: " + this.itemBlocking.list); + } + l.info("cleanup purge enabled = " + (this.purge.enabled = c.getBoolean("cleanup.enable", false))); + l.info(" days since last edit = " + (this.purge.daysSinceLastEdit = c.getInt("cleanup.lastEdit", 30))); + l.info("flatfile storage backups = " + (this.storage.flatFile.backups = c.getBoolean("backups.enabled", true))); + l.info("max vault amount to test via perms = " + (this.maxVaultAmountPermTest = c.getInt("max-vault-amount-perm-to-test", 99))); + } + + public boolean isDebug() { + return this.debug; + } + + public int getDefaultVaultRows() { + return this.defaultVaultRows; + } + + public boolean isSigns() { + return this.signs; + } + + public Economy getEconomy() { + return this.economy; + } + + public Block getItemBlocking() { + return this.itemBlocking; + } + + public PurgePlanet getPurge() { + return this.purge; + } + + public int getMaxVaultAmountPermTest() { + return this.maxVaultAmountPermTest; + } + + public Storage getStorage() { + return this.storage; + } +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/file/Translation.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/file/Translation.java new file mode 100644 index 0000000..7e2725a --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/config/file/Translation.java @@ -0,0 +1,364 @@ +package com.drtshock.playervaults.config.file; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.config.annotation.Comment; +import com.google.common.collect.ImmutableMap; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.platform.bukkit.BukkitComponentSerializer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import org.bukkit.command.CommandSender; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +@SuppressWarnings("FieldMayBeFinal") +public class Translation { + public static class TL extends ArrayList { + private static transient PlayerVaults plugin; + private static transient final Pattern REPLACEMENT_PATTERN = Pattern.compile("(?:\\{([a-zA-Z0-9\\-_]+)(?:(?::)([a-zA-Z0-9_\\-|]+))?})"); + private static transient final Pattern TAG_PATTERN = Pattern.compile("(?:<(/?)([a-zA-Z\\-_]+)>)"); + private static transient final String SKIP_LINE_IF_MISSING = "s"; + private static transient final String BLANK_IF_MISSING = "b"; + private static transient final String PRE_FORMATTED = "p"; + + private static @NonNull TL of(@NonNull String... strings) { + TL list = new TL(); + Collections.addAll(list, strings); + return list; + } + + public static @NonNull TL copyOf(@NonNull Collection collection) { + TL list = new TL(); + list.addAll(collection); + return list; + } + + public class Builder { + private transient ImmutableMap.Builder map; + private transient TL title; + + private Builder(@NonNull TL title) { + this.title = title; + } + + private Builder(@NonNull String key, @Nullable String value) { + this.with(key, value); + } + + public @NonNull Builder with(@NonNull String key, @Nullable String value) { + if (this.map == null) { + this.map = ImmutableMap.builder(); + } + this.map.put(key, value); + return this; + } + + public void send(@NonNull CommandSender sender) { + TL.this.send(sender, this.map == null ? Collections.emptyMap() : this.map.build(), this.title); + } + + public @NonNull String getLegacy() { + return TL.this.getLegacy(this.map == null ? Collections.emptyMap() : this.map.build(), this.title); + } + } + + public @NonNull Builder with(@NonNull String key, @Nullable String value) { + return new Builder(key, value); + } + + public @NonNull Builder title() { + return new Builder(TL.plugin.getTL().title()); + } + + public @NonNull Builder title(@NonNull TL title) { + return new Builder(title); + } + + public void send(@NonNull CommandSender sender) { + this.send(sender, Collections.emptyMap(), null); + } + + private void send(@NonNull CommandSender sender, @NonNull Map map, @Nullable TL title) { + this.send(TL.plugin.getPlatform().sender(sender), map, title); + } + + private void send(@NonNull Audience audience, @NonNull Map map, @Nullable TL title) { + this.forEach(line -> { + Component component = this.getComponent(line, map, title); + if (component != null) { + audience.sendMessage(component); + } + }); + } + + private @Nullable Component getComponent(@NonNull String line, @NonNull Map map, @Nullable TL title) { + if (title != null && !title.isEmpty()) { + line = title.get(0) + line; + } + StringBuffer builder = null; + String found; + String foundDetails; + String repl; + String[] features; + Matcher replMatcher = TL.REPLACEMENT_PATTERN.matcher(line); + while (replMatcher.find()) { + if (builder == null) { + builder = new StringBuffer(); + } + found = replMatcher.group(1); + foundDetails = replMatcher.group(2); + features = foundDetails == null ? null : foundDetails.split("\\|"); + repl = map.get(found); + if (repl == null) { + if (this.arrContains(features, TL.SKIP_LINE_IF_MISSING)) { + return null; + } + if (this.arrContains(features, TL.BLANK_IF_MISSING)) { + replMatcher.appendReplacement(builder, ""); + } + } else { + if (this.arrContains(features, TL.PRE_FORMATTED)) { + repl = MiniMessage.miniMessage().escapeTags(repl).replace("\\", "\\\\"); + } + replMatcher.appendReplacement(builder, repl); + } + } + if (builder != null) { + replMatcher.appendTail(builder); + line = builder.toString(); + builder = null; + } + + Matcher tagMatcher = TL.TAG_PATTERN.matcher(line); + while (tagMatcher.find()) { + if (builder == null) { + builder = new StringBuffer(); + } + found = tagMatcher.group(2); + repl = TL.plugin.getTL().colorMappings().get(found); + if (repl != null) { + tagMatcher.appendReplacement(builder, '<' + tagMatcher.group(1) + repl + '>'); + } + } + if (builder != null) { + tagMatcher.appendTail(builder); + line = builder.toString(); + } + return MiniMessage.miniMessage().deserialize(line); + } + + public @NonNull String getLegacy() { + return this.getLegacy(Collections.emptyMap(), null); + } + + public @NonNull String getLegacy(@NonNull Map map) { + return this.getLegacy(map, null); + } + + public @NonNull String getLegacy(@NonNull Map map, @Nullable TL title) { + return this.stream() + .map(line -> this.getComponent(line, map, title)) + .filter(Objects::nonNull) + .map(component -> BukkitComponentSerializer.legacy().serialize(component)) + .collect(Collectors.joining("\n")); + } + + public boolean arrContains(@Nullable String[] array, @NonNull String target) { + if (array == null) { + return false; + } + for (String string : array) { + if (target.equals(string)) { + return true; + } + } + return false; + } + } + + private static class Placeholders { + private TL title = TL.of("[PlayerVaults]: "); + } + + private static class Translations { + private TL openVault = TL.of("Opening vault {vault}"); + private TL openOtherVault = TL.of("Opening vault {vault} of {player}"); + private TL invalidArgs = TL.of("Invalid args!"); + private TL deleteVault = TL.of("Deleted vault {vault}"); + private TL deleteOtherVault = TL.of("Deleted vault {vault} of {player}"); + private TL deleteOtherVaultAll = TL.of("Deleted all vaults belonging to {player}"); + private TL playerOnly = TL.of("Sorry but that can only be run by a player!"); + private TL mustBeNumber = TL.of("You need to specify a valid number."); + private TL noPerms = TL.of("You don't have permission for that!"); + private TL insufficientFunds = TL.of("You don't have enough money for that!"); + private TL refundAmount = TL.of("You were refunded {price} for deleting that vault."); + private TL costToCreate = TL.of("You were charged {price} for creating a vault."); + private TL costToOpen = TL.of("You were charged {price} for opening that vault."); + private TL vaultDoesNotExist = TL.of("That vault does not exist!"); + private TL clickASign = TL.of("Now click a sign!"); + private TL notASign = TL.of("You must click a sign!"); + private TL setSign = TL.of("You have successfully set a PlayerVault access sign!"); + private TL existingVaults = TL.of("{player} has vaults: {vault}"); + private TL vaultTitle = TL.of("Vault #{vault}"); + private TL openWithSign = TL.of("Opening vault {vault} of {player}"); + private TL noOwnerFound = TL.of("Cannot find vault owner: {player}"); + private TL convertPluginNotFound = TL.of("No converter found for that plugin."); + private TL convertComplete = TL.of("Converted {count} players to PlayerVaults."); + private TL convertBackground = TL.of("Conversion has been forked to the background. See console for updates."); + private TL locked = TL.of("Vaults are currently locked while conversion occurs. Please try again in a moment!"); + private TL help = TL.of("/pv "); + private TL blockedItem = TL.of("{item} is blocked from vaults."); + private TL signsDisabled = TL.of("Vault signs are currently disabled."); + private TL blockedBadItem = TL.of("This item is not allowed in a vault."); + } + + private Placeholders placeholders = new Placeholders(); + private Translations translations = new Translations(); + + public Translation(@NonNull PlayerVaults plugin) { + TL.plugin = plugin; + } + + @Comment("https://docs.adventure.kyori.net/minimessage.html#format") + private Map colorMappings = new HashMap() { + { + this.put("error", "red"); + this.put("normal", "white"); + this.put("info", "green"); + } + }; + + public @NonNull TL title() { + return this.placeholders.title; + } + + public @NonNull TL openVault() { + return this.translations.openVault; + } + + public @NonNull TL openOtherVault() { + return this.translations.openOtherVault; + } + + public @NonNull TL invalidArgs() { + return this.translations.invalidArgs; + } + + public @NonNull TL deleteVault() { + return this.translations.deleteVault; + } + + public @NonNull TL deleteOtherVault() { + return this.translations.deleteOtherVault; + } + + public @NonNull TL deleteOtherVaultAll() { + return this.translations.deleteOtherVaultAll; + } + + public @NonNull TL playerOnly() { + return this.translations.playerOnly; + } + + public @NonNull TL mustBeNumber() { + return this.translations.mustBeNumber; + } + + public @NonNull TL noPerms() { + return this.translations.noPerms; + } + + public @NonNull TL insufficientFunds() { + return this.translations.insufficientFunds; + } + + public @NonNull TL refundAmount() { + return this.translations.refundAmount; + } + + public @NonNull TL costToCreate() { + return this.translations.costToCreate; + } + + public @NonNull TL costToOpen() { + return this.translations.costToOpen; + } + + public @NonNull TL vaultDoesNotExist() { + return this.translations.vaultDoesNotExist; + } + + public @NonNull TL clickASign() { + return this.translations.clickASign; + } + + public @NonNull TL notASign() { + return this.translations.notASign; + } + + public @NonNull TL setSign() { + return this.translations.setSign; + } + + public @NonNull TL existingVaults() { + return this.translations.existingVaults; + } + + public @NonNull TL vaultTitle() { + return this.translations.vaultTitle; + } + + public @NonNull TL openWithSign() { + return this.translations.openWithSign; + } + + public @NonNull TL noOwnerFound() { + return this.translations.noOwnerFound; + } + + public @NonNull TL convertPluginNotFound() { + return this.translations.convertPluginNotFound; + } + + public @NonNull TL convertComplete() { + return this.translations.convertComplete; + } + + public @NonNull TL convertBackground() { + return this.translations.convertBackground; + } + + public @NonNull TL locked() { + return this.translations.locked; + } + + public @NonNull TL help() { + return this.translations.help; + } + + public @NonNull TL blockedItem() { + return this.translations.blockedItem; + } + + public @NonNull TL signsDisabled() { + return this.translations.signsDisabled; + } + + public @NonNull TL blockedBadItem() { + return this.translations.blockedBadItem; + } + + public @NonNull Map colorMappings() { + return Collections.unmodifiableMap(this.colorMappings); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/converters/BackpackConverter.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/converters/BackpackConverter.java new file mode 100644 index 0000000..870ac4f --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/converters/BackpackConverter.java @@ -0,0 +1,131 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler, turt2live + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.converters; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.vaultmanagement.VaultManager; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.io.File; +import java.util.UUID; + +/** + * Simple converter for Backpack (http://dev.bukkit.org/bukkit-plugins/backpack/) + * + * @author turt2live + */ +public class BackpackConverter implements Converter { + + @Override + public int run(CommandSender initiator) { + + PlayerVaults plugin = PlayerVaults.getInstance(); + File destination = new File(plugin.getDataFolder().getParentFile(), "Backpack" + File.separator + "backpacks"); + if (!destination.exists()) { + return -1; + } + + int converted = 0; + + File[] worldDirs = destination.listFiles(); + int vaultNum = 1; + for (File file : worldDirs != null ? worldDirs : new File[0]) { + if (file.isDirectory()) { + converted += convert(file, vaultNum); + vaultNum++; + } + } + + return converted; + } + + private int convert(File worldFolder, int intoVaultNum) { + PlayerVaults plugin = PlayerVaults.getInstance(); + VaultManager vaults = VaultManager.getInstance(); + int converted = 0; + long lastUpdate = 0; + File[] files = worldFolder.listFiles(); + for (File file : files != null ? files : new File[0]) { + if (file.isFile() && file.getName().toLowerCase().endsWith(".yml")) { + try { + OfflinePlayer player = Bukkit.getOfflinePlayer(file.getName().substring(0, file.getName().lastIndexOf('.'))); + if (player == null || player.getUniqueId() == null) { + plugin.getLogger().warning("Unable to convert Backpack for player: " + (player != null ? player.getName() : file.getName())); + } else { + UUID uuid = player.getUniqueId(); + FileConfiguration yaml = YamlConfiguration.loadConfiguration(file); + ConfigurationSection section = yaml.getConfigurationSection("backpack"); + if (section.getKeys(false).size() <= 0) { + continue; // No slots + } + + Inventory vault = vaults.getVault(uuid.toString(), intoVaultNum); + if (vault == null) { + vault = plugin.getServer().createInventory(null, section.getKeys(false).size()); + } + for (String key : section.getKeys(false)) { + ConfigurationSection slotSection = section.getConfigurationSection(key); + ItemStack item = slotSection.getItemStack("ItemStack"); + if (item == null) { + continue; + } + + // Overwrite + vault.setItem(Integer.parseInt(key.split(" ")[1]), item); + } + vaults.saveVault(vault, uuid.toString(), intoVaultNum); + converted++; + + if (System.currentTimeMillis() - lastUpdate >= 1500) { + plugin.getLogger().info(converted + " backpacks have been converted in " + worldFolder.getAbsolutePath()); + lastUpdate = System.currentTimeMillis(); + } + } + } catch (Exception e) { + plugin.getLogger().warning("Error converting " + file.getAbsolutePath()); + e.printStackTrace(); + } + } + } + return converted; + } + + @Override + public boolean canConvert() { + PlayerVaults plugin = PlayerVaults.getInstance(); + File expectedFolder = new File(plugin.getDataFolder().getParentFile(), "Backpack"); + if (!expectedFolder.exists()) { + return false; + } + File backpackDir = new File(expectedFolder, "backpacks"); + return backpackDir.exists(); + } + + @Override + public String getName() { + return "Backpack"; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/converters/Converter.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/converters/Converter.java new file mode 100644 index 0000000..e55de51 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/converters/Converter.java @@ -0,0 +1,53 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler, turt2live + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.converters; + +import org.bukkit.command.CommandSender; + +/** + * Represents a simple converter for converting another plugin's content to PlayerVaults. + * + * @author turt2live + */ +public interface Converter { + + /** + * Converts the other plugin's data. + * + * @param initiator the initiator of the conversion. May be null + * @return the number of vaults converted. Returns 0 on none converted or -1 if no vaults were converted. + */ + int run(CommandSender initiator); + + /** + * Determines if this converter is applicable for converting to PlayerVaults. This may check for the existance of a + * plugin, plugin folder, or otherwise. + * + * @return true if this converter can convert, false otherwise + */ + boolean canConvert(); + + /** + * Gets the name of this converter + * + * @return the converter name + */ + String getName(); + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultItem.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultItem.java new file mode 100644 index 0000000..7bab78e --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultItem.java @@ -0,0 +1,13 @@ +package com.drtshock.playervaults.data; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Material; + +@Getter @Setter @AllArgsConstructor +public class PlayerVaultItem { + + private Material material; + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultsManager.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultsManager.java new file mode 100644 index 0000000..2e1dfdf --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultsManager.java @@ -0,0 +1,23 @@ +package com.drtshock.playervaults.data; + +import com.drtshock.playervaults.PlayerVaults; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.struct.NewSaveLoadManager; + +import java.util.UUID; + +public class PlayerVaultsManager extends NewSaveLoadManager { + public PlayerVaultsManager() { + super(PlayerVaults.getInstance(), StorageUtils.getInstance().getGson(), "player-gui-data", PlayerVaultsPlayer.class); + } + + @Override + public String serialize(UUID uuid) { + return uuid.toString(); + } + + @Override + public UUID deserialize(String s) { + return UUID.fromString(s); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultsPlayer.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultsPlayer.java new file mode 100644 index 0000000..234f7b4 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/data/PlayerVaultsPlayer.java @@ -0,0 +1,38 @@ +package com.drtshock.playervaults.data; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.storageutils.struct.NewKeyToSave; +import org.bukkit.Bukkit; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +@Getter @Setter +public class PlayerVaultsPlayer implements NewKeyToSave { + + private UUID playerUUID; + private Map playerVaultItemMap; + private String name; + + public PlayerVaultsPlayer(UUID uuid) { + this(uuid, new HashMap<>()); + } + + public PlayerVaultsPlayer(UUID uuid, Map playerVaultItemMap) { + this.playerUUID = uuid; + this.playerVaultItemMap = playerVaultItemMap; + this.name = Bukkit.getOfflinePlayer(uuid).getName(); + } + + @Override + public UUID getKey() { + return playerUUID; + } + + @Override + public void setKey(UUID uuid) { + this.playerUUID = uuid; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/ChangeMaterialInventory.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/ChangeMaterialInventory.java new file mode 100644 index 0000000..4c80256 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/ChangeMaterialInventory.java @@ -0,0 +1,43 @@ +package com.drtshock.playervaults.guis; + +import com.drtshock.playervaults.data.PlayerVaultItem; +import com.drtshock.playervaults.data.PlayerVaultsPlayer; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class ChangeMaterialInventory { + + private final static Material[] materials = new Material[]{ + Material.DIAMOND_SWORD, Material.DIAMOND_AXE, Material.DIAMOND_BOOTS, Material.DIAMOND_LEGGINGS, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_HELMET, + Material.GOLD_SWORD, Material.GOLD_AXE, Material.GOLD_BOOTS, Material.GOLD_LEGGINGS, Material.GOLD_CHESTPLATE, Material.GOLD_HELMET, + Material.DIAMOND, Material.EMERALD, Material.GOLD_INGOT, Material.IRON_INGOT, Material.REDSTONE, Material.GOLDEN_APPLE, Material.COOKED_BEEF, + Material.SKULL_ITEM, Material.FISHING_ROD, Material.ENDER_PEARL + }; + + private List itemStackList; + + private final Gui selectPVInventory; + + public Gui getSelectPVInventory() { + return this.selectPVInventory; + } + + public ChangeMaterialInventory(Integer vault, PlayerVaultsPlayer playerVaultsPlayer) { + this.selectPVInventory = new Gui(6, "PV Material Selector"); + this.selectPVInventory.setDefaultClickAction((event) -> event.setCancelled(true)); + + for(Material material : materials) { + this.selectPVInventory.addItem(new GuiItem(new ItemStack(material), event -> { + event.getWhoClicked().closeInventory(); + playerVaultsPlayer.getPlayerVaultItemMap().put(vault, new PlayerVaultItem(event.getCurrentItem().getType())); + SelectPlayerVaultInventory selectPlayerVaultInventory = new SelectPlayerVaultInventory(playerVaultsPlayer); + selectPlayerVaultInventory.getSelectPVInventory().open(event.getWhoClicked()); + })); + } + + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/SearchGUI.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/SearchGUI.java new file mode 100644 index 0000000..ebcbfc4 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/SearchGUI.java @@ -0,0 +1,88 @@ +package com.drtshock.playervaults.guis; + +import com.drtshock.playervaults.commands.SearchCommand; +import com.drtshock.playervaults.utils.CC; +import de.tr7zw.nbtapi.NBTItem; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +public class SearchGUI { + private final PaginatedGui expShopUI; + + public PaginatedGui getExpShopUI() { + return this.expShopUI; + } + + public SearchGUI(Player executor, Player openFor, Map> hashMap) { + executor.sendMessage(CC.translate("&b&lVaults &8➥ &7Finished searching... Found &f" + hashMap.size() + "&7 unique vaults.")); + executor.playSound(executor.getLocation(), Sound.valueOf("CHEST_OPEN"), 10.0F, 10.0F); + this.expShopUI = new PaginatedGui(6, 45, ChatColor.DARK_GRAY + openFor.getName() + " Vaults (" + hashMap.size() + " Unique)"); + this.expShopUI.setDefaultClickAction((event) -> { + event.setCancelled(true); + }); + this.expShopUI.getFiller().fillBottom(new GuiItem(this.createFillerItem())); + ItemStack prevPage = new ItemStack(Material.ARROW); + ItemMeta prevMeta = prevPage.getItemMeta(); + prevMeta.setDisplayName(CC.translate("&c<- Previous Page")); + List prevLore = new ArrayList<>(); + prevLore.add(CC.translate("&7Right-Click&7 to go to the previous page.")); + prevMeta.setLore(prevLore); + prevPage.setItemMeta(prevMeta); + ItemStack nextPage = new ItemStack(Material.ARROW); + ItemMeta nextMeta = nextPage.getItemMeta(); + nextMeta.setDisplayName(CC.translate("&aNext Page ->")); + List nextLore = new ArrayList<>(); + nextLore.add(CC.translate("&7Right-Click&7 to go to the next page.")); + nextMeta.setLore(nextLore); + nextPage.setItemMeta(nextMeta); + this.expShopUI.setItem(6, 1, new GuiItem(prevPage, (event) -> { + this.expShopUI.previous(); + event.setCancelled(true); + })); + this.expShopUI.setItem(6, 9, new GuiItem(nextPage, (event) -> { + this.expShopUI.next(); + event.setCancelled(true); + })); + + for (Map.Entry> entry : hashMap.entrySet()) { + int key = entry.getKey(); + List items = entry.getValue(); + for (ItemStack itemStack : items) { + ItemMeta meta = itemStack.getItemMeta(); + meta.setDisplayName(CC.translate(meta.getDisplayName() + " &f&c&lVault &f#" + key)); + + List lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); + + lore.add(""); + lore.add(CC.translate("&7&nLeft-Click&7 to open vault &f&n#" + key + "&7.")); + meta.setLore(lore); + itemStack.setItemMeta(meta); + NBTItem nbti = new NBTItem(itemStack); + nbti.setInteger("vaultNr", key); + this.expShopUI.addItem(new GuiItem(nbti.getItem(), (event) -> { + int vaultNr = nbti.getInteger("vaultNr"); + SearchCommand.openVault(executor, openFor.getUniqueId(), vaultNr); + })); + } + } + + } + + public ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.valueOf("STAINED_GLASS_PANE"), 1, (short)7); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&f")); + item.setItemMeta(meta); + return item; + } + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/SelectPlayerVaultInventory.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/SelectPlayerVaultInventory.java new file mode 100644 index 0000000..993ffd1 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/guis/SelectPlayerVaultInventory.java @@ -0,0 +1,68 @@ +package com.drtshock.playervaults.guis; + +import com.drtshock.playervaults.data.PlayerVaultsPlayer; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.LuckpermUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +public class SelectPlayerVaultInventory { + + private final static Map ranksAndPvs = new HashMap() {{ + put("default", 3); + put("explorer", 6); + put("corrupt", 9); + put("medusa", 12); + put("dracula", 16); + put("satan", 30); + put("media", 30); + }}; + + private final PaginatedGui selectPVInventory; + + public PaginatedGui getSelectPVInventory() { + return this.selectPVInventory; + } + + public SelectPlayerVaultInventory(PlayerVaultsPlayer playerVaultsObject) { + this.selectPVInventory = new PaginatedGui(6, 54, playerVaultsObject.getName() + "'s Player Vaults"); + this.selectPVInventory.setDefaultClickAction((event) -> event.setCancelled(true)); + + + if(Bukkit.getPlayer(playerVaultsObject.getPlayerUUID()) == null) return; + Player player = Bukkit.getPlayer(playerVaultsObject.getPlayerUUID()); + + int amountOfPvs = 0; + for(String s : ranksAndPvs.keySet()) { + if(LuckpermUtils.hasHigherRank(player, s)) amountOfPvs = ranksAndPvs.get(s); + } + + for(int i = 1; i <= amountOfPvs; i++) { + Material material = playerVaultsObject.getPlayerVaultItemMap().containsKey(i) ? playerVaultsObject.getPlayerVaultItemMap().get(i).getMaterial() : Material.EMERALD; + ItemBuilder itemBuilder = new ItemBuilder(material, "&c&l/pv " + i, + "&cLeft Click: &fOpen vault", + "&cRight Click: &fRename vault", + "&cMiddle Click: &fChange vault material"); + ItemStack itemStack = itemBuilder.colorize().build(); + int finalI = i; + this.selectPVInventory.addItem(new GuiItem(itemStack, event -> { + if(event.getClick().equals(ClickType.LEFT)) { + player.performCommand("pv " + finalI); + return; + } + if(event.getClick().equals(ClickType.MIDDLE)) { + ChangeMaterialInventory changeMaterialInventory = new ChangeMaterialInventory(finalI, playerVaultsObject); + changeMaterialInventory.getSelectPVInventory().open(player); + } + })); + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/Config.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/Config.java new file mode 100644 index 0000000..7f1d142 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/Config.java @@ -0,0 +1,1139 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.time.Duration; +import java.time.Period; +import java.time.temporal.TemporalAmount; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * An immutable map from config paths to config values. Paths are dot-separated + * expressions such as foo.bar.baz. Values are as in JSON + * (booleans, strings, numbers, lists, or objects), represented by + * {@link ConfigValue} instances. Values accessed through the + * Config interface are never null. + * + *

+ * {@code Config} is an immutable object and thus safe to use from multiple + * threads. There's never a need for "defensive copies." + * + *

+ * Fundamental operations on a {@code Config} include getting configuration + * values, resolving substitutions with {@link Config#resolve()}, and + * merging configs using {@link Config#withFallback(ConfigMergeable)}. + * + *

+ * All operations return a new immutable {@code Config} rather than modifying + * the original instance. + * + *

+ * Examples + * + *

+ * You can find an example app and library on + * GitHub. Also be sure to read the package overview which + * describes the big picture as shown in those examples. + * + *

+ * Paths, keys, and Config vs. ConfigObject + * + *

+ * Config is a view onto a tree of {@link ConfigObject}; the + * corresponding object tree can be found through {@link Config#root()}. + * ConfigObject is a map from config keys, rather than + * paths, to config values. Think of ConfigObject as a JSON object + * and Config as a configuration API. + * + *

+ * The API tries to consistently use the terms "key" and "path." A key is a key + * in a JSON object; it's just a string that's the key in a map. A "path" is a + * parseable expression with a syntax and it refers to a series of keys. Path + * expressions are described in the spec for + * Human-Optimized Config Object Notation. In brief, a path is + * period-separated so "a.b.c" looks for key c in object b in object a in the + * root object. Sometimes double quotes are needed around special characters in + * path expressions. + * + *

+ * The API for a {@code Config} is in terms of path expressions, while the API + * for a {@code ConfigObject} is in terms of keys. Conceptually, {@code Config} + * is a one-level map from paths to values, while a + * {@code ConfigObject} is a tree of nested maps from keys to values. + * + *

+ * Use {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath} to convert + * between path expressions and individual path elements (keys). + * + *

+ * Another difference between {@code Config} and {@code ConfigObject} is that + * conceptually, {@code ConfigValue}s with a {@link ConfigValue#valueType() + * valueType()} of {@link ConfigValueType#NULL NULL} exist in a + * {@code ConfigObject}, while a {@code Config} treats null values as if they + * were missing. (With the exception of two methods: {@link Config#hasPathOrNull} + * and {@link Config#getIsNull} let you detect null values.) + * + *

+ * Getting configuration values + * + *

+ * The "getters" on a {@code Config} all work in the same way. They never return + * null, nor do they return a {@code ConfigValue} with + * {@link ConfigValue#valueType() valueType()} of {@link ConfigValueType#NULL + * NULL}. Instead, they throw {@link ConfigException.Missing} if the value is + * completely absent or set to null. If the value is set to null, a subtype of + * {@code ConfigException.Missing} called {@link ConfigException.Null} will be + * thrown. {@link ConfigException.WrongType} will be thrown anytime you ask for + * a type and the value has an incompatible type. Reasonable type conversions + * are performed for you though. + * + *

+ * Iteration + * + *

+ * If you want to iterate over the contents of a {@code Config}, you can get its + * {@code ConfigObject} with {@link #root()}, and then iterate over the + * {@code ConfigObject} (which implements java.util.Map). Or, you + * can use {@link #entrySet()} which recurses the object tree for you and builds + * up a Set of all path-value pairs where the value is not null. + * + *

+ * Resolving substitutions + * + *

+ * Substitutions are the ${foo.bar} syntax in config + * files, described in the specification. Resolving substitutions replaces these references with real + * values. + * + *

+ * Before using a {@code Config} it's necessary to call {@link Config#resolve()} + * to handle substitutions (though {@link ConfigFactory#load()} and similar + * methods will do the resolve for you already). + * + *

+ * Merging + * + *

+ * The full Config for your application can be constructed using + * the associative operation {@link Config#withFallback(ConfigMergeable)}. If + * you use {@link ConfigFactory#load()} (recommended), it merges system + * properties over the top of application.conf over the top of + * reference.conf, using withFallback. You can add in + * additional sources of configuration in the same way (usually, custom layers + * should go either just above or just below application.conf, + * keeping reference.conf at the bottom and system properties at + * the top). + * + *

+ * Serialization + * + *

+ * Convert a Config to a JSON or HOCON string by calling + * {@link ConfigObject#render()} on the root object, + * myConfig.root().render(). There's also a variant + * {@link ConfigObject#render(ConfigRenderOptions)} which allows you to control + * the format of the rendered string. (See {@link ConfigRenderOptions}.) Note + * that Config does not remember the formatting of the original + * file, so if you load, modify, and re-save a config file, it will be + * substantially reformatted. + * + *

+ * As an alternative to {@link ConfigObject#render()}, the + * toString() method produces a debug-output-oriented + * representation (which is not valid JSON). + * + *

+ * Java serialization is supported as well for Config and all + * subtypes of ConfigValue. + * + *

+ * This is an interface but don't implement it yourself + * + *

+ * Do not implement {@code Config}; it should only be implemented by + * the config library. Arbitrary implementations will not work because the + * library internals assume a specific concrete implementation. Also, this + * interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface Config extends ConfigMergeable { + /** + * Gets the {@code Config} as a tree of {@link ConfigObject}. This is a + * constant-time operation (it is not proportional to the number of values + * in the {@code Config}). + * + * @return the root object in the configuration + */ + ConfigObject root(); + + /** + * Gets the origin of the {@code Config}, which may be a file, or a file + * with a line number, or just a descriptive phrase. + * + * @return the origin of the {@code Config} for use in error messages + */ + ConfigOrigin origin(); + + @Override + Config withFallback(ConfigMergeable other); + + /** + * Returns a replacement config with all substitutions (the + * ${foo.bar} syntax, see the + * spec) resolved. Substitutions are looked up using this + * Config as the root object, that is, a substitution + * ${foo.bar} will be replaced with the result of + * getValue("foo.bar"). + * + *

+ * This method uses {@link ConfigResolveOptions#defaults()}, there is + * another variant {@link Config#resolve(ConfigResolveOptions)} which lets + * you specify non-default options. + * + *

+ * A given {@link Config} must be resolved before using it to retrieve + * config values, but ideally should be resolved one time for your entire + * stack of fallbacks (see {@link Config#withFallback}). Otherwise, some + * substitutions that could have resolved with all fallbacks available may + * not resolve, which will be potentially confusing for your application's + * users. + * + *

+ * resolve() should be invoked on root config objects, rather + * than on a subtree (a subtree is the result of something like + * config.getConfig("foo")). The problem with + * resolve() on a subtree is that substitutions are relative to + * the root of the config and the subtree will have no way to get values + * from the root. For example, if you did + * config.getConfig("foo").resolve() on the below config file, + * it would not work: + * + *

+     *   common-value = 10
+     *   foo {
+     *      whatever = ${common-value}
+     *   }
+     * 
+ * + *

+ * Many methods on {@link ConfigFactory} such as + * {@link ConfigFactory#load()} automatically resolve the loaded + * Config on the loaded stack of config files. + * + *

+ * Resolving an already-resolved config is a harmless no-op, but again, it + * is best to resolve an entire stack of fallbacks (such as all your config + * files combined) rather than resolving each one individually. + * + * @return an immutable object with substitutions resolved + * @throws ConfigException.UnresolvedSubstitution + * if any substitutions refer to nonexistent paths + * @throws ConfigException + * some other config exception if there are other problems + */ + Config resolve(); + + /** + * Like {@link Config#resolve()} but allows you to specify non-default + * options. + * + * @param options + * resolve options + * @return the resolved Config (may be only partially resolved if options are set to allow unresolved) + */ + Config resolve(ConfigResolveOptions options); + + /** + * Checks whether the config is completely resolved. After a successful call + * to {@link Config#resolve()} it will be completely resolved, but after + * calling {@link Config#resolve(ConfigResolveOptions)} with + * allowUnresolved set in the options, it may or may not be + * completely resolved. A newly-loaded config may or may not be completely + * resolved depending on whether there were substitutions present in the + * file. + * + * @return true if there are no unresolved substitutions remaining in this + * configuration. + * @since 1.2.0 + */ + boolean isResolved(); + + /** + * Like {@link Config#resolve()} except that substitution values are looked + * up in the given source, rather than in this instance. This is a + * special-purpose method which doesn't make sense to use in most cases; + * it's only needed if you're constructing some sort of app-specific custom + * approach to configuration. The more usual approach if you have a source + * of substitution values would be to merge that source into your config + * stack using {@link Config#withFallback} and then resolve. + *

+ * Note that this method does NOT look in this instance for substitution + * values. If you want to do that, you could either merge this instance into + * your value source using {@link Config#withFallback}, or you could resolve + * multiple times with multiple sources (using + * {@link ConfigResolveOptions#setAllowUnresolved(boolean)} so the partial + * resolves don't fail). + * + * @param source + * configuration to pull values from + * @return an immutable object with substitutions resolved + * @throws ConfigException.UnresolvedSubstitution + * if any substitutions refer to paths which are not in the + * source + * @throws ConfigException + * some other config exception if there are other problems + * @since 1.2.0 + */ + Config resolveWith(Config source); + + /** + * Like {@link Config#resolveWith(Config)} but allows you to specify + * non-default options. + * + * @param source + * source configuration to pull values from + * @param options + * resolve options + * @return the resolved Config (may be only partially resolved + * if options are set to allow unresolved) + * @since 1.2.0 + */ + Config resolveWith(Config source, ConfigResolveOptions options); + + /** + * Validates this config against a reference config, throwing an exception + * if it is invalid. The purpose of this method is to "fail early" with a + * comprehensive list of problems; in general, anything this method can find + * would be detected later when trying to use the config, but it's often + * more user-friendly to fail right away when loading the config. + * + *

+ * Using this method is always optional, since you can "fail late" instead. + * + *

+ * You must restrict validation to paths you "own" (those whose meaning are + * defined by your code module). If you validate globally, you may trigger + * errors about paths that happen to be in the config but have nothing to do + * with your module. It's best to allow the modules owning those paths to + * validate them. Also, if every module validates only its own stuff, there + * isn't as much redundant work being done. + * + *

+ * If no paths are specified in checkValid()'s parameter list, + * validation is for the entire config. + * + *

+ * If you specify paths that are not in the reference config, those paths + * are ignored. (There's nothing to validate.) + * + *

+ * Here's what validation involves: + * + *

    + *
  • All paths found in the reference config must be present in this + * config or an exception will be thrown. + *
  • + * Some changes in type from the reference config to this config will cause + * an exception to be thrown. Not all potential type problems are detected, + * in particular it's assumed that strings are compatible with everything + * except objects and lists. This is because string types are often "really" + * some other type (system properties always start out as strings, or a + * string like "5ms" could be used with {@link #getMilliseconds}). Also, + * it's allowed to set any type to null or override null with any type. + *
  • + * Any unresolved substitutions in this config will cause a validation + * failure; both the reference config and this config should be resolved + * before validation. If the reference config is unresolved, it's a bug in + * the caller of this method. + *
+ * + *

+ * If you want to allow a certain setting to have a flexible type (or + * otherwise want validation to be looser for some settings), you could + * either remove the problematic setting from the reference config provided + * to this method, or you could intercept the validation exception and + * screen out certain problems. Of course, this will only work if all other + * callers of this method are careful to restrict validation to their own + * paths, as they should be. + * + *

+ * If validation fails, the thrown exception contains a list of all problems + * found. See {@link ConfigException.ValidationFailed#problems}. The + * exception's getMessage() will have all the problems + * concatenated into one huge string, as well. + * + *

+ * Again, checkValid() can't guess every domain-specific way a + * setting can be invalid, so some problems may arise later when attempting + * to use the config. checkValid() is limited to reporting + * generic, but common, problems such as missing settings and blatant type + * incompatibilities. + * + * @param reference + * a reference configuration + * @param restrictToPaths + * only validate values underneath these paths that your code + * module owns and understands + * @throws ConfigException.ValidationFailed + * if there are any validation issues + * @throws ConfigException.NotResolved + * if this config is not resolved + * @throws ConfigException.BugOrBroken + * if the reference config is unresolved or caller otherwise + * misuses the API + */ + void checkValid(Config reference, String... restrictToPaths); + + /** + * Checks whether a value is present and non-null at the given path. This + * differs in two ways from {@code Map.containsKey()} as implemented by + * {@link ConfigObject}: it looks for a path expression, not a key; and it + * returns false for null values, while {@code containsKey()} returns true + * indicating that the object contains a null value for the key. + * + *

+ * If a path exists according to {@link #hasPath(String)}, then + * {@link #getValue(String)} will never throw an exception. However, the + * typed getters, such as {@link #getInt(String)}, will still throw if the + * value is not convertible to the requested type. + * + *

+ * Note that path expressions have a syntax and sometimes require quoting + * (see {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath}). + * + * @param path + * the path expression + * @return true if a non-null value is present at the path + * @throws ConfigException.BadPath + * if the path expression is invalid + */ + boolean hasPath(String path); + + /** + * Checks whether a value is present at the given path, even + * if the value is null. Most of the getters on + * Config will throw if you try to get a null + * value, so if you plan to call {@link #getValue(String)}, + * {@link #getInt(String)}, or another getter you may want to + * use plain {@link #hasPath(String)} rather than this method. + * + *

+ * To handle all three cases (unset, null, and a non-null value) + * the code might look like: + *


+     * if (config.hasPathOrNull(path)) {
+     *     if (config.getIsNull(path)) {
+     *        // handle null setting
+     *     } else {
+     *        // get and use non-null setting
+     *     }
+     * } else {
+     *     // handle entirely unset path
+     * }
+     * 
+ * + *

However, the usual thing is to allow entirely unset + * paths to be a bug that throws an exception (because you set + * a default in your reference.conf), so in that + * case it's OK to call {@link #getIsNull(String)} without + * checking hasPathOrNull first. + * + *

+ * Note that path expressions have a syntax and sometimes require quoting + * (see {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath}). + * + * @param path + * the path expression + * @return true if a value is present at the path, even if the value is null + * @throws ConfigException.BadPath + * if the path expression is invalid + */ + boolean hasPathOrNull(String path); + + /** + * Returns true if the {@code Config}'s root object contains no key-value + * pairs. + * + * @return true if the configuration is empty + */ + boolean isEmpty(); + + /** + * Returns the set of path-value pairs, excluding any null values, found by + * recursing {@link #root() the root object}. Note that this is very + * different from root().entrySet() which returns the set of + * immediate-child keys in the root object and includes null values. + *

+ * Entries contain path expressions meaning there may be quoting + * and escaping involved. Parse path expressions with + * {@link ConfigUtil#splitPath}. + *

+ * Because a Config is conceptually a single-level map from + * paths to values, there will not be any {@link ConfigObject} values in the + * entries (that is, all entries represent leaf nodes). Use + * {@link ConfigObject} rather than Config if you want a tree. + * (OK, this is a slight lie: Config entries may contain + * {@link ConfigList} and the lists may contain objects. But no objects are + * directly included as entry values.) + * + * @return set of paths with non-null values, built up by recursing the + * entire tree of {@link ConfigObject} and creating an entry for + * each leaf value. + */ + Set> entrySet(); + + /** + * Checks whether a value is set to null at the given path, + * but throws an exception if the value is entirely + * unset. This method will not throw if {@link + * #hasPathOrNull(String)} returned true for the same path, so + * to avoid any possible exception check + * hasPathOrNull() first. However, an exception + * for unset paths will usually be the right thing (because a + * reference.conf should exist that has the path + * set, the path should never be unset unless something is + * broken). + * + *

+ * Note that path expressions have a syntax and sometimes require quoting + * (see {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath}). + * + * @param path + * the path expression + * @return true if the value exists and is null, false if it + * exists and is not null + * @throws ConfigException.BadPath + * if the path expression is invalid + * @throws ConfigException.Missing + * if value is not set at all + */ + boolean getIsNull(String path); + + /** + * + * @param path + * path expression + * @return the boolean value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to boolean + */ + boolean getBoolean(String path); + + /** + * @param path + * path expression + * @return the numeric value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a number + */ + Number getNumber(String path); + + /** + * Gets the integer at the given path. If the value at the + * path has a fractional (floating point) component, it + * will be discarded and only the integer part will be + * returned (it works like a "narrowing primitive conversion" + * in the Java language specification). + * + * @param path + * path expression + * @return the 32-bit integer value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to an int (for example it is out + * of range, or it's a boolean value) + */ + int getInt(String path); + + /** + * Gets the long integer at the given path. If the value at + * the path has a fractional (floating point) component, it + * will be discarded and only the integer part will be + * returned (it works like a "narrowing primitive conversion" + * in the Java language specification). + * + * @param path + * path expression + * @return the 64-bit long value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a long + */ + long getLong(String path); + + /** + * @param path + * path expression + * @return the floating-point value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a double + */ + double getDouble(String path); + + /** + * @param path + * path expression + * @return the string value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a string + */ + String getString(String path); + + /** + * @param enumClass + * an enum class + * @param + * a generic denoting a specific type of enum + * @param path + * path expression + * @return the {@code Enum} value at the requested path + * of the requested enum class + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to an Enum + */ + public > T getEnum(Class enumClass, String path); + + /** + * @param path + * path expression + * @return the {@link ConfigObject} value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to an object + */ + ConfigObject getObject(String path); + + /** + * @param path + * path expression + * @return the nested {@code Config} value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a Config + */ + Config getConfig(String path); + + /** + * Gets the value at the path as an unwrapped Java boxed value ( + * {@link java.lang.Boolean Boolean}, {@link java.lang.Integer Integer}, and + * so on - see {@link ConfigValue#unwrapped()}). + * + * @param path + * path expression + * @return the unwrapped value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + */ + Object getAnyRef(String path); + + /** + * Gets the value at the given path, unless the value is a + * null value or missing, in which case it throws just like + * the other getters. Use {@code get()} on the {@link + * Config#root()} object (or other object in the tree) if you + * want an unprocessed value. + * + * @param path + * path expression + * @return the value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + */ + ConfigValue getValue(String path); + + /** + * Gets a value as a size in bytes (parses special strings like "128M"). If + * the value is already a number, then it's left alone; if it's a string, + * it's parsed understanding unit suffixes such as "128K", as documented in + * the the + * spec. + * + * @param path + * path expression + * @return the value at the requested path, in bytes + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to Long or String + * @throws ConfigException.BadValue + * if value cannot be parsed as a size in bytes + */ + Long getBytes(String path); + + /** + * Gets a value as an amount of memory (parses special strings like "128M"). If + * the value is already a number, then it's left alone; if it's a string, + * it's parsed understanding unit suffixes such as "128K", as documented in + * the the + * spec. + * + * @since 1.3.0 + * + * @param path + * path expression + * @return the value at the requested path, in bytes + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to Long or String + * @throws ConfigException.BadValue + * if value cannot be parsed as a size in bytes + */ + ConfigMemorySize getMemorySize(String path); + + /** + * Get value as a duration in milliseconds. If the value is already a + * number, then it's left alone; if it's a string, it's parsed understanding + * units suffixes like "10m" or "5ns" as documented in the the + * spec. + * + * @deprecated As of release 1.1, replaced by {@link #getDuration(String, TimeUnit)} + * + * @param path + * path expression + * @return the duration value at the requested path, in milliseconds + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to Long or String + * @throws ConfigException.BadValue + * if value cannot be parsed as a number of milliseconds + */ + @Deprecated Long getMilliseconds(String path); + + /** + * Get value as a duration in nanoseconds. If the value is already a number + * it's taken as milliseconds and converted to nanoseconds. If it's a + * string, it's parsed understanding unit suffixes, as for + * {@link #getDuration(String, TimeUnit)}. + * + * @deprecated As of release 1.1, replaced by {@link #getDuration(String, TimeUnit)} + * + * @param path + * path expression + * @return the duration value at the requested path, in nanoseconds + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to Long or String + * @throws ConfigException.BadValue + * if value cannot be parsed as a number of nanoseconds + */ + @Deprecated Long getNanoseconds(String path); + + /** + * Gets a value as a duration in a specified + * {@link java.util.concurrent.TimeUnit TimeUnit}. If the value is already a + * number, then it's taken as milliseconds and then converted to the + * requested TimeUnit; if it's a string, it's parsed understanding units + * suffixes like "10m" or "5ns" as documented in the the + * spec. + * + * @since 1.2.0 + * + * @param path + * path expression + * @param unit + * convert the return value to this time unit + * @return the duration value at the requested path, in the given TimeUnit + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to Long or String + * @throws ConfigException.BadValue + * if value cannot be parsed as a number of the given TimeUnit + */ + long getDuration(String path, TimeUnit unit); + + /** + * Gets a value as a java.time.Duration. If the value is + * already a number, then it's taken as milliseconds; if it's + * a string, it's parsed understanding units suffixes like + * "10m" or "5ns" as documented in the the + * spec. This method never returns null. + * + * @since 1.3.0 + * + * @param path + * path expression + * @return the duration value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to Long or String + * @throws ConfigException.BadValue + * if value cannot be parsed as a number of the given TimeUnit + */ + Duration getDuration(String path); + + /** + * Gets a value as a java.time.Period. If the value is + * already a number, then it's taken as days; if it's + * a string, it's parsed understanding units suffixes like + * "10d" or "5w" as documented in the the + * spec. This method never returns null. + * + * @since 1.3.0 + * + * @param path + * path expression + * @return the period value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to Long or String + * @throws ConfigException.BadValue + * if value cannot be parsed as a number of the given TimeUnit + */ + Period getPeriod(String path); + + /** + * Gets a value as a java.time.temporal.TemporalAmount. + * This method will first try get get the value as a java.time.Duration, and if unsuccessful, + * then as a java.time.Period. + * This means that values like "5m" will be parsed as 5 minutes rather than 5 months + * @param path path expression + * @return the temporal value at the requested path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to Long or String + * @throws ConfigException.BadValue + * if value cannot be parsed as a TemporalAmount + */ + TemporalAmount getTemporal(String path); + + /** + * Gets a list value (with any element type) as a {@link ConfigList}, which + * implements {@code java.util.List}. Throws if the path is + * unset or null. + * + * @param path + * the path to the list value. + * @return the {@link ConfigList} at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a ConfigList + */ + ConfigList getList(String path); + + /** + * Gets a list value with boolean elements. Throws if the + * path is unset or null or not a list or contains values not + * convertible to boolean. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of booleans + */ + List getBooleanList(String path); + + /** + * Gets a list value with number elements. Throws if the + * path is unset or null or not a list or contains values not + * convertible to number. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of numbers + */ + List getNumberList(String path); + + /** + * Gets a list value with int elements. Throws if the + * path is unset or null or not a list or contains values not + * convertible to int. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of ints + */ + List getIntList(String path); + + /** + * Gets a list value with long elements. Throws if the + * path is unset or null or not a list or contains values not + * convertible to long. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of longs + */ + List getLongList(String path); + + /** + * Gets a list value with double elements. Throws if the + * path is unset or null or not a list or contains values not + * convertible to double. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of doubles + */ + List getDoubleList(String path); + + /** + * Gets a list value with string elements. Throws if the + * path is unset or null or not a list or contains values not + * convertible to string. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of strings + */ + List getStringList(String path); + + /** + * Gets a list value with {@code Enum} elements. Throws if the + * path is unset or null or not a list or contains values not + * convertible to {@code Enum}. + * + * @param enumClass + * the enum class + * @param + * a generic denoting a specific type of enum + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of {@code Enum} + */ + > List getEnumList(Class enumClass, String path); + + /** + * Gets a list value with object elements. Throws if the + * path is unset or null or not a list or contains values not + * convertible to ConfigObject. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of objects + */ + List getObjectList(String path); + + /** + * Gets a list value with Config elements. + * Throws if the path is unset or null or not a list or + * contains values not convertible to Config. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of configs + */ + List getConfigList(String path); + + /** + * Gets a list value with any kind of elements. Throws if the + * path is unset or null or not a list. Each element is + * "unwrapped" (see {@link ConfigValue#unwrapped()}). + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list + */ + List getAnyRefList(String path); + + /** + * Gets a list value with elements representing a size in + * bytes. Throws if the path is unset or null or not a list + * or contains values not convertible to memory sizes. + * + * @param path + * the path to the list value. + * @return the list at the path + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of memory sizes + */ + List getBytesList(String path); + + /** + * Gets a list, converting each value in the list to a memory size, using the + * same rules as {@link #getMemorySize(String)}. + * + * @since 1.3.0 + * @param path + * a path expression + * @return list of memory sizes + * @throws ConfigException.Missing + * if value is absent or null + * @throws ConfigException.WrongType + * if value is not convertible to a list of memory sizes + */ + List getMemorySizeList(String path); + + /** + * @deprecated As of release 1.1, replaced by {@link #getDurationList(String, TimeUnit)} + * @param path the path + * @return list of millisecond values + */ + @Deprecated List getMillisecondsList(String path); + + /** + * @deprecated As of release 1.1, replaced by {@link #getDurationList(String, TimeUnit)} + * @param path the path + * @return list of nanosecond values + */ + @Deprecated List getNanosecondsList(String path); + + /** + * Gets a list, converting each value in the list to a duration, using the + * same rules as {@link #getDuration(String, TimeUnit)}. + * + * @since 1.2.0 + * @param path + * a path expression + * @param unit + * time units of the returned values + * @return list of durations, in the requested units + */ + List getDurationList(String path, TimeUnit unit); + + /** + * Gets a list, converting each value in the list to a duration, using the + * same rules as {@link #getDuration(String)}. + * + * @since 1.3.0 + * @param path + * a path expression + * @return list of durations + */ + List getDurationList(String path); + + /** + * Clone the config with only the given path (and its children) retained; + * all sibling paths are removed. + *

+ * Note that path expressions have a syntax and sometimes require quoting + * (see {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath}). + * + * @param path + * path to keep + * @return a copy of the config minus all paths except the one specified + */ + Config withOnlyPath(String path); + + /** + * Clone the config with the given path removed. + *

+ * Note that path expressions have a syntax and sometimes require quoting + * (see {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath}). + * + * @param path + * path expression to remove + * @return a copy of the config minus the specified path + */ + Config withoutPath(String path); + + /** + * Places the config inside another {@code Config} at the given path. + *

+ * Note that path expressions have a syntax and sometimes require quoting + * (see {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath}). + * + * @param path + * path expression to store this config at. + * @return a {@code Config} instance containing this config at the given + * path. + */ + Config atPath(String path); + + /** + * Places the config inside a {@code Config} at the given key. See also + * atPath(). Note that a key is NOT a path expression (see + * {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath}). + * + * @param key + * key to store this config at. + * @return a {@code Config} instance containing this config at the given + * key. + */ + Config atKey(String key); + + /** + * Returns a {@code Config} based on this one, but with the given path set + * to the given value. Does not modify this instance (since it's immutable). + * If the path already has a value, that value is replaced. To remove a + * value, use withoutPath(). + *

+ * Note that path expressions have a syntax and sometimes require quoting + * (see {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath}). + * + * @param path + * path expression for the value's new location + * @param value + * value at the new path + * @return the new instance with the new map entry + */ + Config withValue(String path, ConfigValue value); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigBeanFactory.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigBeanFactory.java new file mode 100644 index 0000000..d246dc2 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigBeanFactory.java @@ -0,0 +1,49 @@ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigBeanImpl; + +/** + * Factory for automatically creating a Java class from a {@link Config}. + * See {@link #create(Config,Class)}. + * + * @since 1.3.0 + */ +public class ConfigBeanFactory { + + /** + * Creates an instance of a class, initializing its fields from a {@link Config}. + * + * Example usage: + * + *

+     * Config configSource = ConfigFactory.load().getConfig("foo");
+     * FooConfig config = ConfigBeanFactory.create(configSource, FooConfig.class);
+     * 
+ * + * The Java class should follow JavaBean conventions. Field types + * can be any of the types you can normally get from a {@link + * Config}, including java.time.Duration or {@link + * ConfigMemorySize}. Fields may also be another JavaBean-style + * class. + * + * Fields are mapped to config by converting the config key to + * camel case. So the key foo-bar becomes JavaBean + * setter setFooBar. + * + * @since 1.3.0 + * + * @param config source of config information + * @param clazz class to be instantiated + * @param the type of the class to be instantiated + * @return an instance of the class populated with data from the config + * @throws ConfigException.BadBean + * If something is wrong with the JavaBean + * @throws ConfigException.ValidationFailed + * If the config doesn't conform to the bean's implied schema + * @throws ConfigException + * Can throw the same exceptions as the getters on Config + */ + public static T create(Config config, Class clazz) { + return ConfigBeanImpl.createInternal(config, clazz); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigException.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigException.java new file mode 100644 index 0000000..d5feb6c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigException.java @@ -0,0 +1,447 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Field; + +import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImplUtil; + +/** + * All exceptions thrown by the library are subclasses of + * ConfigException. + */ +public abstract class ConfigException extends RuntimeException implements Serializable { + private static final long serialVersionUID = 1L; + + final private transient ConfigOrigin origin; + + protected ConfigException(ConfigOrigin origin, String message, + Throwable cause) { + super(origin.description() + ": " + message, cause); + this.origin = origin; + } + + protected ConfigException(ConfigOrigin origin, String message) { + this(origin.description() + ": " + message, null); + } + + protected ConfigException(String message, Throwable cause) { + super(message, cause); + this.origin = null; + } + + protected ConfigException(String message) { + this(message, null); + } + + /** + * Returns an "origin" (such as a filename and line number) for the + * exception, or null if none is available. If there's no sensible origin + * for a given exception, or the kind of exception doesn't meaningfully + * relate to a particular origin file, this returns null. Never assume this + * will return non-null, it can always return null. + * + * @return origin of the problem, or null if unknown/inapplicable + */ + public ConfigOrigin origin() { + return origin; + } + + // we customize serialization because ConfigOrigin isn't + // serializable and we don't want it to be (don't want to + // support it) + private void writeObject(java.io.ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + ConfigImplUtil.writeOrigin(out, origin); + } + + // For deserialization - uses reflection to set the final origin field on the object + private static void setOriginField(T hasOriginField, Class clazz, + ConfigOrigin origin) throws IOException { + // circumvent "final" + Field f; + try { + f = clazz.getDeclaredField("origin"); + } catch (NoSuchFieldException e) { + throw new IOException(clazz.getSimpleName() + " has no origin field?", e); + } catch (SecurityException e) { + throw new IOException("unable to fill out origin field in " + + clazz.getSimpleName(), e); + } + f.setAccessible(true); + try { + f.set(hasOriginField, origin); + } catch (IllegalArgumentException e) { + throw new IOException("unable to set origin field", e); + } catch (IllegalAccessException e) { + throw new IOException("unable to set origin field", e); + } + } + + private void readObject(java.io.ObjectInputStream in) throws IOException, + ClassNotFoundException { + in.defaultReadObject(); + ConfigOrigin origin = ConfigImplUtil.readOrigin(in); + setOriginField(this, ConfigException.class, origin); + } + + /** + * Exception indicating that the type of a value does not match the type you + * requested. + * + */ + public static class WrongType extends ConfigException { + private static final long serialVersionUID = 1L; + + public WrongType(ConfigOrigin origin, String path, String expected, String actual, + Throwable cause) { + super(origin, path + " has type " + actual + " rather than " + expected, cause); + } + + public WrongType(ConfigOrigin origin, String path, String expected, String actual) { + this(origin, path, expected, actual, null); + } + + public WrongType(ConfigOrigin origin, String message, Throwable cause) { + super(origin, message, cause); + } + + public WrongType(ConfigOrigin origin, String message) { + super(origin, message, null); + } + } + + /** + * Exception indicates that the setting was never set to anything, not even + * null. + */ + public static class Missing extends ConfigException { + private static final long serialVersionUID = 1L; + + public Missing(String path, Throwable cause) { + super("No configuration setting found for key '" + path + "'", + cause); + } + + public Missing(String path) { + this(path, null); + } + + protected Missing(ConfigOrigin origin, String message, Throwable cause) { + super(origin, message, cause); + } + + protected Missing(ConfigOrigin origin, String message) { + this(origin, message, null); + } + } + + /** + * Exception indicates that the setting was treated as missing because it + * was set to null. + */ + public static class Null extends Missing { + private static final long serialVersionUID = 1L; + + private static String makeMessage(String path, String expected) { + if (expected != null) { + return "Configuration key '" + path + + "' is set to null but expected " + expected; + } else { + return "Configuration key '" + path + "' is null"; + } + } + + public Null(ConfigOrigin origin, String path, String expected, + Throwable cause) { + super(origin, makeMessage(path, expected), cause); + } + + public Null(ConfigOrigin origin, String path, String expected) { + this(origin, path, expected, null); + } + } + + /** + * Exception indicating that a value was messed up, for example you may have + * asked for a duration and the value can't be sensibly parsed as a + * duration. + * + */ + public static class BadValue extends ConfigException { + private static final long serialVersionUID = 1L; + + public BadValue(ConfigOrigin origin, String path, String message, + Throwable cause) { + super(origin, "Invalid value at '" + path + "': " + message, cause); + } + + public BadValue(ConfigOrigin origin, String path, String message) { + this(origin, path, message, null); + } + + public BadValue(String path, String message, Throwable cause) { + super("Invalid value at '" + path + "': " + message, cause); + } + + public BadValue(String path, String message) { + this(path, message, null); + } + } + + /** + * Exception indicating that a path expression was invalid. Try putting + * double quotes around path elements that contain "special" characters. + * + */ + public static class BadPath extends ConfigException { + private static final long serialVersionUID = 1L; + + public BadPath(ConfigOrigin origin, String path, String message, + Throwable cause) { + super(origin, + path != null ? ("Invalid path '" + path + "': " + message) + : message, cause); + } + + public BadPath(ConfigOrigin origin, String path, String message) { + this(origin, path, message, null); + } + + public BadPath(String path, String message, Throwable cause) { + super(path != null ? ("Invalid path '" + path + "': " + message) + : message, cause); + } + + public BadPath(String path, String message) { + this(path, message, null); + } + + public BadPath(ConfigOrigin origin, String message) { + this(origin, null, message); + } + } + + /** + * Exception indicating that there's a bug in something (possibly the + * library itself) or the runtime environment is broken. This exception + * should never be handled; instead, something should be fixed to keep the + * exception from occurring. This exception can be thrown by any method in + * the library. + */ + public static class BugOrBroken extends ConfigException { + private static final long serialVersionUID = 1L; + + public BugOrBroken(String message, Throwable cause) { + super(message, cause); + } + + public BugOrBroken(String message) { + this(message, null); + } + } + + /** + * Exception indicating that there was an IO error. + * + */ + public static class IO extends ConfigException { + private static final long serialVersionUID = 1L; + + public IO(ConfigOrigin origin, String message, Throwable cause) { + super(origin, message, cause); + } + + public IO(ConfigOrigin origin, String message) { + this(origin, message, null); + } + } + + /** + * Exception indicating that there was a parse error. + * + */ + public static class Parse extends ConfigException { + private static final long serialVersionUID = 1L; + + public Parse(ConfigOrigin origin, String message, Throwable cause) { + super(origin, message, cause); + } + + public Parse(ConfigOrigin origin, String message) { + this(origin, message, null); + } + } + + /** + * Exception indicating that a substitution did not resolve to anything. + * Thrown by {@link Config#resolve}. + */ + public static class UnresolvedSubstitution extends Parse { + private static final long serialVersionUID = 1L; + + public UnresolvedSubstitution(ConfigOrigin origin, String detail, Throwable cause) { + super(origin, "Could not resolve substitution to a value: " + detail, cause); + } + + public UnresolvedSubstitution(ConfigOrigin origin, String detail) { + this(origin, detail, null); + } + } + + /** + * Exception indicating that you tried to use a function that requires + * substitutions to be resolved, but substitutions have not been resolved + * (that is, {@link Config#resolve} was not called). This is always a bug in + * either application code or the library; it's wrong to write a handler for + * this exception because you should be able to fix the code to avoid it by + * adding calls to {@link Config#resolve}. + */ + public static class NotResolved extends BugOrBroken { + private static final long serialVersionUID = 1L; + + public NotResolved(String message, Throwable cause) { + super(message, cause); + } + + public NotResolved(String message) { + this(message, null); + } + } + + /** + * Information about a problem that occurred in {@link Config#checkValid}. A + * {@link ConfigException.ValidationFailed} exception thrown from + * checkValid() includes a list of problems encountered. + */ + public static class ValidationProblem implements Serializable { + + final private String path; + final private transient ConfigOrigin origin; + final private String problem; + + public ValidationProblem(String path, ConfigOrigin origin, String problem) { + this.path = path; + this.origin = origin; + this.problem = problem; + } + + /** + * Returns the config setting causing the problem. + * @return the path of the problem setting + */ + public String path() { + return path; + } + + /** + * Returns where the problem occurred (origin may include info on the + * file, line number, etc.). + * @return the origin of the problem setting + */ + public ConfigOrigin origin() { + return origin; + } + + /** + * Returns a description of the problem. + * @return description of the problem + */ + public String problem() { + return problem; + } + + // We customize serialization because ConfigOrigin isn't + // serializable and we don't want it to be + private void writeObject(java.io.ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + ConfigImplUtil.writeOrigin(out, origin); + } + + private void readObject(java.io.ObjectInputStream in) throws IOException, + ClassNotFoundException { + in.defaultReadObject(); + ConfigOrigin origin = ConfigImplUtil.readOrigin(in); + setOriginField(this, ValidationProblem.class, origin); + } + + @Override + public String toString() { + return "ValidationProblem(" + path + "," + origin + "," + problem + ")"; + } + } + + /** + * Exception indicating that {@link Config#checkValid} found validity + * problems. The problems are available via the {@link #problems()} method. + * The getMessage() of this exception is a potentially very + * long string listing all the problems found. + */ + public static class ValidationFailed extends ConfigException { + private static final long serialVersionUID = 1L; + + final private Iterable problems; + + public ValidationFailed(Iterable problems) { + super(makeMessage(problems), null); + this.problems = problems; + } + + public Iterable problems() { + return problems; + } + + private static String makeMessage(Iterable problems) { + StringBuilder sb = new StringBuilder(); + for (ValidationProblem p : problems) { + sb.append(p.origin().description()); + sb.append(": "); + sb.append(p.path()); + sb.append(": "); + sb.append(p.problem()); + sb.append(", "); + } + if (sb.length() == 0) + throw new ConfigException.BugOrBroken( + "ValidationFailed must have a non-empty list of problems"); + sb.setLength(sb.length() - 2); // chop comma and space + + return sb.toString(); + } + } + + /** + * Some problem with a JavaBean we are trying to initialize. + * @since 1.3.0 + */ + public static class BadBean extends BugOrBroken { + private static final long serialVersionUID = 1L; + + public BadBean(String message, Throwable cause) { + super(message, cause); + } + + public BadBean(String message) { + this(message, null); + } + } + + /** + * Exception that doesn't fall into any other category. + */ + public static class Generic extends ConfigException { + private static final long serialVersionUID = 1L; + + public Generic(String message, Throwable cause) { + super(message, cause); + } + + public Generic(String message) { + this(message, null); + } + } + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigFactory.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigFactory.java new file mode 100644 index 0000000..eecb9e1 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigFactory.java @@ -0,0 +1,1066 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImpl; +import com.drtshock.playervaults.lib.com.typesafe.config.impl.Parseable; + +import java.io.File; +import java.io.Reader; +import java.net.URL; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Callable; + +/** + * Contains static methods for creating {@link Config} instances. + * + *

+ * See also {@link ConfigValueFactory} which contains static methods for + * converting Java values into a {@link ConfigObject}. You can then convert a + * {@code ConfigObject} into a {@code Config} with {@link ConfigObject#toConfig}. + * + *

+ * The static methods with "load" in the name do some sort of higher-level + * operation potentially parsing multiple resources and resolving substitutions, + * while the ones with "parse" in the name just create a {@link ConfigValue} + * from a resource and nothing else. + * + *

You can find an example app and library on + * GitHub. Also be sure to read the package + * overview which describes the big picture as shown in those + * examples. + */ +public final class ConfigFactory { + private static final String STRATEGY_PROPERTY_NAME = "config.strategy"; + + private ConfigFactory() { + } + + /** + * Loads an application's configuration from the given classpath resource or + * classpath resource basename, sandwiches it between default reference + * config and default overrides, and then resolves it. The classpath + * resource is "raw" (it should have no "/" prefix, and is not made relative + * to any package, so it's like {@link ClassLoader#getResource} not + * {@link Class#getResource}). + * + *

+ * Resources are loaded from the current thread's + * {@link Thread#getContextClassLoader()}. In general, a library needs its + * configuration to come from the class loader used to load that library, so + * the proper "reference.conf" are present. + * + *

+ * The loaded object will already be resolved (substitutions have already + * been processed). As a result, if you add more fallbacks then they won't + * be seen by substitutions. Substitutions are the "${foo.bar}" syntax. If + * you want to parse additional files or something then you need to use + * {@link #load(Config)}. + * + *

+ * To load a standalone resource (without the default reference and default + * overrides), use {@link #parseResourcesAnySyntax(String)} rather than this + * method. To load only the reference config use {@link #defaultReference()} + * and to load only the overrides use {@link #defaultOverrides()}. + * + * @param resourceBasename + * name (optionally without extension) of a resource on classpath + * @return configuration for an application relative to context class loader + */ + public static Config load(String resourceBasename) { + return load(resourceBasename, ConfigParseOptions.defaults(), + ConfigResolveOptions.defaults()); + } + + /** + * Like {@link #load(String)} but uses the supplied class loader instead of + * the current thread's context class loader. + * + *

+ * To load a standalone resource (without the default reference and default + * overrides), use {@link #parseResourcesAnySyntax(ClassLoader, String)} + * rather than this method. To load only the reference config use + * {@link #defaultReference(ClassLoader)} and to load only the overrides use + * {@link #defaultOverrides(ClassLoader)}. + * + * @param loader class loader to look for resources in + * @param resourceBasename basename (no .conf/.json/.properties suffix) + * @return configuration for an application relative to given class loader + */ + public static Config load(ClassLoader loader, String resourceBasename) { + return load(resourceBasename, ConfigParseOptions.defaults().setClassLoader(loader), + ConfigResolveOptions.defaults()); + } + + /** + * Like {@link #load(String)} but allows you to specify parse and resolve + * options. + * + * @param resourceBasename + * the classpath resource name with optional extension + * @param parseOptions + * options to use when parsing the resource + * @param resolveOptions + * options to use when resolving the stack + * @return configuration for an application + */ + public static Config load(String resourceBasename, ConfigParseOptions parseOptions, + ConfigResolveOptions resolveOptions) { + ConfigParseOptions withLoader = ensureClassLoader(parseOptions, "load"); + Config appConfig = ConfigFactory.parseResourcesAnySyntax(resourceBasename, withLoader); + return load(withLoader.getClassLoader(), appConfig, resolveOptions); + } + + /** + * Like {@link #load(String,ConfigParseOptions,ConfigResolveOptions)} but + * has a class loader parameter that overrides any from the + * {@code ConfigParseOptions}. + * + * @param loader + * class loader in which to find resources (overrides loader in + * parse options) + * @param resourceBasename + * the classpath resource name with optional extension + * @param parseOptions + * options to use when parsing the resource (class loader + * overridden) + * @param resolveOptions + * options to use when resolving the stack + * @return configuration for an application + */ + public static Config load(ClassLoader loader, String resourceBasename, + ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) { + return load(resourceBasename, parseOptions.setClassLoader(loader), resolveOptions); + } + + private static ClassLoader checkedContextClassLoader(String methodName) { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + if (loader == null) + throw new ConfigException.BugOrBroken("Context class loader is not set for the current thread; " + + "if Thread.currentThread().getContextClassLoader() returns null, you must pass a ClassLoader " + + "explicitly to ConfigFactory." + methodName); + else + return loader; + } + + private static ConfigParseOptions ensureClassLoader(ConfigParseOptions options, String methodName) { + if (options.getClassLoader() == null) + return options.setClassLoader(checkedContextClassLoader(methodName)); + else + return options; + } + + /** + * Assembles a standard configuration using a custom Config + * object rather than loading "application.conf". The Config + * object will be sandwiched between the default reference config and + * default overrides and then resolved. + * + * @param config + * the application's portion of the configuration + * @return resolved configuration with overrides and fallbacks added + */ + public static Config load(Config config) { + return load(checkedContextClassLoader("load"), config); + } + + /** + * Like {@link #load(Config)} but allows you to specify + * the class loader for looking up resources. + * + * @param loader + * the class loader to use to find resources + * @param config + * the application's portion of the configuration + * @return resolved configuration with overrides and fallbacks added + */ + public static Config load(ClassLoader loader, Config config) { + return load(loader, config, ConfigResolveOptions.defaults()); + } + + /** + * Like {@link #load(Config)} but allows you to specify + * {@link ConfigResolveOptions}. + * + * @param config + * the application's portion of the configuration + * @param resolveOptions + * options for resolving the assembled config stack + * @return resolved configuration with overrides and fallbacks added + */ + public static Config load(Config config, ConfigResolveOptions resolveOptions) { + return load(checkedContextClassLoader("load"), config, resolveOptions); + } + + /** + * Like {@link #load(Config,ConfigResolveOptions)} but allows you to specify + * a class loader other than the context class loader. + * + * @param loader + * class loader to use when looking up override and reference + * configs + * @param config + * the application's portion of the configuration + * @param resolveOptions + * options for resolving the assembled config stack + * @return resolved configuration with overrides and fallbacks added + */ + public static Config load(ClassLoader loader, Config config, ConfigResolveOptions resolveOptions) { + return defaultOverrides(loader).withFallback(config).withFallback(defaultReference(loader)) + .resolve(resolveOptions); + } + + + + /** + * Loads a default configuration, equivalent to {@link #load(Config) + * load(defaultApplication())} in most cases. This configuration should be used by + * libraries and frameworks unless an application provides a different one. + *

+ * This method may return a cached singleton so will not see changes to + * system properties or config files. (Use {@link #invalidateCaches()} to + * force it to reload.) + * + * @return configuration for an application + */ + public static Config load() { + ClassLoader loader = checkedContextClassLoader("load"); + return load(loader); + } + + /** + * Like {@link #load()} but allows specifying parse options. + * + * @param parseOptions + * Options for parsing resources + * @return configuration for an application + */ + public static Config load(ConfigParseOptions parseOptions) { + return load(parseOptions, ConfigResolveOptions.defaults()); + } + + /** + * Like {@link #load()} but allows specifying a class loader other than the + * thread's current context class loader. + * + * @param loader + * class loader for finding resources + * @return configuration for an application + */ + public static Config load(final ClassLoader loader) { + final ConfigParseOptions withLoader = ConfigParseOptions.defaults().setClassLoader(loader); + return ConfigImpl.computeCachedConfig(loader, "load", new Callable() { + @Override + public Config call() { + return load(loader, defaultApplication(withLoader)); + } + }); + } + + /** + * Like {@link #load()} but allows specifying a class loader other than the + * thread's current context class loader and also specify parse options. + * + * @param loader + * class loader for finding resources (overrides any loader in parseOptions) + * @param parseOptions + * Options for parsing resources + * @return configuration for an application + */ + public static Config load(ClassLoader loader, ConfigParseOptions parseOptions) { + return load(parseOptions.setClassLoader(loader)); + } + + /** + * Like {@link #load()} but allows specifying a class loader other than the + * thread's current context class loader and also specify resolve options. + * + * @param loader + * class loader for finding resources + * @param resolveOptions + * options for resolving the assembled config stack + * @return configuration for an application + */ + public static Config load(ClassLoader loader, ConfigResolveOptions resolveOptions) { + return load(loader, ConfigParseOptions.defaults(), resolveOptions); + } + + + /** + * Like {@link #load()} but allows specifying a class loader other than the + * thread's current context class loader, parse options, and resolve options. + * + * @param loader + * class loader for finding resources (overrides any loader in parseOptions) + * @param parseOptions + * Options for parsing resources + * @param resolveOptions + * options for resolving the assembled config stack + * @return configuration for an application + */ + public static Config load(ClassLoader loader, ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) { + final ConfigParseOptions withLoader = ensureClassLoader(parseOptions, "load"); + return load(loader, defaultApplication(withLoader), resolveOptions); + } + + /** + * Like {@link #load()} but allows specifying parse options and resolve + * options. + * + * @param parseOptions + * Options for parsing resources + * @param resolveOptions + * options for resolving the assembled config stack + * @return configuration for an application + * + * @since 1.3.0 + */ + public static Config load(ConfigParseOptions parseOptions, final ConfigResolveOptions resolveOptions) { + final ConfigParseOptions withLoader = ensureClassLoader(parseOptions, "load"); + return load(defaultApplication(withLoader), resolveOptions); + } + + /** + * Obtains the default reference configuration, which is currently created + * by merging all resources "reference.conf" found on the classpath and + * overriding the result with system properties. The returned reference + * configuration will already have substitutions resolved. + * + *

+ * Libraries and frameworks should ship with a "reference.conf" in their + * jar. + * + *

+ * The reference config must be looked up in the class loader that contains + * the libraries that you want to use with this config, so the + * "reference.conf" for each library can be found. Use + * {@link #defaultReference(ClassLoader)} if the context class loader is not + * suitable. + * + *

+ * The {@link #load()} methods merge this configuration for you + * automatically. + * + *

+ * Future versions may look for reference configuration in more places. It + * is not guaranteed that this method only looks at + * "reference.conf". + * + * @return the default reference config for context class loader + */ + public static Config defaultReference() { + return defaultReference(checkedContextClassLoader("defaultReference")); + } + + /** + * Like {@link #defaultReference()} but allows you to specify a class loader + * to use rather than the current context class loader. + * + * @param loader class loader to look for resources in + * @return the default reference config for this class loader + */ + public static Config defaultReference(ClassLoader loader) { + return ConfigImpl.defaultReference(loader); + } + + /** + * Obtains the default override configuration, which currently consists of + * system properties. The returned override configuration will already have + * substitutions resolved. + * + *

+ * The {@link #load()} methods merge this configuration for you + * automatically. + * + *

+ * Future versions may get overrides in more places. It is not guaranteed + * that this method only uses system properties. + * + * @return the default override configuration + */ + public static Config defaultOverrides() { + return systemProperties(); + } + + /** + * Like {@link #defaultOverrides()} but allows you to specify a class loader + * to use rather than the current context class loader. + * + * @param loader class loader to look for resources in + * @return the default override configuration + */ + public static Config defaultOverrides(ClassLoader loader) { + return systemProperties(); + } + + /** + * Obtains the default application-specific configuration, + * which defaults to parsing application.conf, + * application.json, and + * application.properties on the classpath, but + * can also be rerouted using the config.file, + * config.resource, and config.url + * system properties. + * + *

The no-arguments {@link #load()} method automatically + * stacks the {@link #defaultReference()}, {@link + * #defaultApplication()}, and {@link #defaultOverrides()} + * configs. You would use defaultApplication() + * directly only if you're somehow customizing behavior by + * reimplementing load(). + * + *

The configuration returned by + * defaultApplication() will not be resolved + * already, in contrast to defaultReference() and + * defaultOverrides(). This is because + * application.conf would normally be resolved after + * merging with the reference and override configs. + * + *

+ * If the system properties config.resource, + * config.file, or config.url are set, then the + * classpath resource, file, or URL specified in those properties will be + * used rather than the default + * application.{conf,json,properties} classpath resources. + * These system properties should not be set in code (after all, you can + * just parse whatever you want manually and then use {@link #load(Config)} + * if you don't want to use application.conf). The properties + * are intended for use by the person or script launching the application. + * For example someone might have a production.conf that + * include application.conf but then change a couple of values. + * When launching the app they could specify + * -Dconfig.resource=production.conf to get production mode. + * + *

+ * If no system properties are set to change the location of the default + * configuration, defaultApplication() is equivalent to + * ConfigFactory.parseResources("application"). + * + * @since 1.3.0 + * + * @return the default application.conf or system-property-configured configuration + */ + public static Config defaultApplication() { + return defaultApplication(ConfigParseOptions.defaults()); + } + + /** + * Like {@link #defaultApplication()} but allows you to specify a class loader + * to use rather than the current context class loader. + * + * @since 1.3.0 + * + * @param loader class loader to look for resources in + * @return the default application configuration + */ + public static Config defaultApplication(ClassLoader loader) { + return defaultApplication(ConfigParseOptions.defaults().setClassLoader(loader)); + } + + /** + * Like {@link #defaultApplication()} but allows you to specify parse options. + * + * @since 1.3.0 + * + * @param options the options + * @return the default application configuration + */ + public static Config defaultApplication(ConfigParseOptions options) { + return getConfigLoadingStrategy().parseApplicationConfig(ensureClassLoader(options, "defaultApplication")); + } + + /** + * Reloads any cached configs, picking up changes to system properties for + * example. Because a {@link Config} is immutable, anyone with a reference + * to the old configs will still have the same outdated objects. However, + * new calls to {@link #load()} or {@link #defaultOverrides()} or + * {@link #defaultReference} may return a new object. + *

+ * This method is primarily intended for use in unit tests, for example, + * that may want to update a system property then confirm that it's used + * correctly. In many cases, use of this method may indicate there's a + * better way to set up your code. + *

+ * Caches may be reloaded immediately or lazily; once you call this method, + * the reload can occur at any time, even during the invalidation process. + * So FIRST make the changes you'd like the caches to notice, then SECOND + * call this method to invalidate caches. Don't expect that invalidating, + * making changes, then calling {@link #load()}, will work. Make changes + * before you invalidate. + */ + public static void invalidateCaches() { + // We rely on this having the side effect that it drops + // all caches + ConfigImpl.reloadSystemPropertiesConfig(); + ConfigImpl.reloadEnvVariablesConfig(); + } + + /** + * Gets an empty configuration. See also {@link #empty(String)} to create an + * empty configuration with a description, which may improve user-visible + * error messages. + * + * @return an empty configuration + */ + public static Config empty() { + return empty(null); + } + + /** + * Gets an empty configuration with a description to be used to create a + * {@link ConfigOrigin} for this Config. The description should + * be very short and say what the configuration is, like "default settings" + * or "foo settings" or something. (Presumably you will merge some actual + * settings into this empty config using {@link Config#withFallback}, making + * the description more useful.) + * + * @param originDescription + * description of the config + * @return an empty configuration + */ + public static Config empty(String originDescription) { + return ConfigImpl.emptyConfig(originDescription); + } + + /** + * Gets a Config containing the system properties from + * {@link java.lang.System#getProperties()}, parsed and converted as with + * {@link #parseProperties}. + *

+ * This method can return a global immutable singleton, so it's preferred + * over parsing system properties yourself. + *

+ * {@link #load} will include the system properties as overrides already, as + * will {@link #defaultReference} and {@link #defaultOverrides}. + * + *

+ * Because this returns a singleton, it will not notice changes to system + * properties made after the first time this method is called. Use + * {@link #invalidateCaches()} to force the singleton to reload if you + * modify system properties. + * + * @return system properties parsed into a Config + */ + public static Config systemProperties() { + return ConfigImpl.systemPropertiesAsConfig(); + } + + /** + * Gets a Config containing the system's environment variables. + * This method can return a global immutable singleton. + * + *

+ * Environment variables are used as fallbacks when resolving substitutions + * whether or not this object is included in the config being resolved, so + * you probably don't need to use this method for most purposes. It can be a + * nicer API for accessing environment variables than raw + * {@link java.lang.System#getenv(String)} though, since you can use methods + * such as {@link Config#getInt}. + * + * @return system environment variables parsed into a Config + */ + public static Config systemEnvironment() { + return ConfigImpl.envVariablesAsConfig(); + } + + /** + * Converts a Java {@link java.util.Properties} object to a + * {@link ConfigObject} using the rules documented in the HOCON + * spec. The keys in the Properties object are split on the + * period character '.' and treated as paths. The values will all end up as + * string values. If you have both "a=foo" and "a.b=bar" in your properties + * file, so "a" is both the object containing "b" and the string "foo", then + * the string value is dropped. + * + *

+ * If you want to have System.getProperties() as a + * ConfigObject, it's better to use the {@link #systemProperties()} method + * which returns a cached global singleton. + * + * @param properties + * a Java Properties object + * @param options + * the parse options + * @return the parsed configuration + */ + public static Config parseProperties(Properties properties, + ConfigParseOptions options) { + return Parseable.newProperties(properties, options).parse().toConfig(); + } + + /** + * Like {@link #parseProperties(Properties, ConfigParseOptions)} but uses default + * parse options. + * @param properties + * a Java Properties object + * @return the parsed configuration + */ + public static Config parseProperties(Properties properties) { + return parseProperties(properties, ConfigParseOptions.defaults()); + } + + /** + * Parses a Reader into a Config instance. Does not call + * {@link Config#resolve} or merge the parsed stream with any + * other configuration; this method parses a single stream and + * does nothing else. It does process "include" statements in + * the parsed stream, and may end up doing other IO due to those + * statements. + * + * @param reader + * the reader to parse + * @param options + * parse options to control how the reader is interpreted + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static Config parseReader(Reader reader, ConfigParseOptions options) { + return Parseable.newReader(reader, options).parse().toConfig(); + } + + /** + * Parses a reader into a Config instance as with + * {@link #parseReader(Reader,ConfigParseOptions)} but always uses the + * default parse options. + * + * @param reader + * the reader to parse + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static Config parseReader(Reader reader) { + return parseReader(reader, ConfigParseOptions.defaults()); + } + + /** + * Parses a URL into a Config instance. Does not call + * {@link Config#resolve} or merge the parsed stream with any + * other configuration; this method parses a single stream and + * does nothing else. It does process "include" statements in + * the parsed stream, and may end up doing other IO due to those + * statements. + * + * @param url + * the url to parse + * @param options + * parse options to control how the url is interpreted + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static Config parseURL(URL url, ConfigParseOptions options) { + return Parseable.newURL(url, options).parse().toConfig(); + } + + /** + * Parses a url into a Config instance as with + * {@link #parseURL(URL,ConfigParseOptions)} but always uses the + * default parse options. + * + * @param url + * the url to parse + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static Config parseURL(URL url) { + return parseURL(url, ConfigParseOptions.defaults()); + } + + /** + * Parses a file into a Config instance. Does not call + * {@link Config#resolve} or merge the file with any other + * configuration; this method parses a single file and does + * nothing else. It does process "include" statements in the + * parsed file, and may end up doing other IO due to those + * statements. + * + * @param file + * the file to parse + * @param options + * parse options to control how the file is interpreted + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static Config parseFile(File file, ConfigParseOptions options) { + return Parseable.newFile(file, options).parse().toConfig(); + } + + /** + * Parses a file into a Config instance as with + * {@link #parseFile(File,ConfigParseOptions)} but always uses the + * default parse options. + * + * @param file + * the file to parse + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static Config parseFile(File file) { + return parseFile(file, ConfigParseOptions.defaults()); + } + + /** + * Parses a file with a flexible extension. If the fileBasename + * already ends in a known extension, this method parses it according to + * that extension (the file's syntax must match its extension). If the + * fileBasename does not end in an extension, it parses files + * with all known extensions and merges whatever is found. + * + *

+ * In the current implementation, the extension ".conf" forces + * {@link ConfigSyntax#CONF}, ".json" forces {@link ConfigSyntax#JSON}, and + * ".properties" forces {@link ConfigSyntax#PROPERTIES}. When merging files, + * ".conf" falls back to ".json" falls back to ".properties". + * + *

+ * Future versions of the implementation may add additional syntaxes or + * additional extensions. However, the ordering (fallback priority) of the + * three current extensions will remain the same. + * + *

+ * If options forces a specific syntax, this method only parses + * files with an extension matching that syntax. + * + *

+ * If {@link ConfigParseOptions#getAllowMissing options.getAllowMissing()} + * is true, then no files have to exist; if false, then at least one file + * has to exist. + * + * @param fileBasename + * a filename with or without extension + * @param options + * parse options + * @return the parsed configuration + */ + public static Config parseFileAnySyntax(File fileBasename, + ConfigParseOptions options) { + return ConfigImpl.parseFileAnySyntax(fileBasename, options).toConfig(); + } + + /** + * Like {@link #parseFileAnySyntax(File,ConfigParseOptions)} but always uses + * default parse options. + * + * @param fileBasename + * a filename with or without extension + * @return the parsed configuration + */ + public static Config parseFileAnySyntax(File fileBasename) { + return parseFileAnySyntax(fileBasename, ConfigParseOptions.defaults()); + } + + /** + * Parses all resources on the classpath with the given name and merges them + * into a single Config. + * + *

+ * If the resource name does not begin with a "/", it will have the supplied + * class's package added to it, in the same way as + * {@link java.lang.Class#getResource}. + * + *

+ * Duplicate resources with the same name are merged such that ones returned + * earlier from {@link ClassLoader#getResources} fall back to (have higher + * priority than) the ones returned later. This implies that resources + * earlier in the classpath override those later in the classpath when they + * configure the same setting. However, in practice real applications may + * not be consistent about classpath ordering, so be careful. It may be best + * to avoid assuming too much. + * + * @param klass + * klass.getClassLoader() will be used to load + * resources, and non-absolute resource names will have this + * class's package added + * @param resource + * resource to look up, relative to klass's package + * or absolute starting with a "/" + * @param options + * parse options + * @return the parsed configuration + */ + public static Config parseResources(Class klass, String resource, + ConfigParseOptions options) { + return Parseable.newResources(klass, resource, options).parse() + .toConfig(); + } + + /** + * Like {@link #parseResources(Class,String,ConfigParseOptions)} but always uses + * default parse options. + * + * @param klass + * klass.getClassLoader() will be used to load + * resources, and non-absolute resource names will have this + * class's package added + * @param resource + * resource to look up, relative to klass's package + * or absolute starting with a "/" + * @return the parsed configuration + */ + public static Config parseResources(Class klass, String resource) { + return parseResources(klass, resource, ConfigParseOptions.defaults()); + } + + /** + * Parses classpath resources with a flexible extension. In general, this + * method has the same behavior as + * {@link #parseFileAnySyntax(File,ConfigParseOptions)} but for classpath + * resources instead, as in {@link #parseResources}. + * + *

+ * There is a thorny problem with this method, which is that + * {@link java.lang.ClassLoader#getResources} must be called separately for + * each possible extension. The implementation ends up with separate lists + * of resources called "basename.conf" and "basename.json" for example. As a + * result, the ideal ordering between two files with different extensions is + * unknown; there is no way to figure out how to merge the two lists in + * classpath order. To keep it simple, the lists are simply concatenated, + * with the same syntax priorities as + * {@link #parseFileAnySyntax(File,ConfigParseOptions) parseFileAnySyntax()} + * - all ".conf" resources are ahead of all ".json" resources which are + * ahead of all ".properties" resources. + * + * @param klass + * class which determines the ClassLoader and the + * package for relative resource names + * @param resourceBasename + * a resource name as in {@link java.lang.Class#getResource}, + * with or without extension + * @param options + * parse options (class loader is ignored in favor of the one + * from klass) + * @return the parsed configuration + */ + public static Config parseResourcesAnySyntax(Class klass, String resourceBasename, + ConfigParseOptions options) { + return ConfigImpl.parseResourcesAnySyntax(klass, resourceBasename, + options).toConfig(); + } + + /** + * Like {@link #parseResourcesAnySyntax(Class,String,ConfigParseOptions)} + * but always uses default parse options. + * + * @param klass + * klass.getClassLoader() will be used to load + * resources, and non-absolute resource names will have this + * class's package added + * @param resourceBasename + * a resource name as in {@link java.lang.Class#getResource}, + * with or without extension + * @return the parsed configuration + */ + public static Config parseResourcesAnySyntax(Class klass, String resourceBasename) { + return parseResourcesAnySyntax(klass, resourceBasename, ConfigParseOptions.defaults()); + } + + /** + * Parses all resources on the classpath with the given name and merges them + * into a single Config. + * + *

+ * This works like {@link java.lang.ClassLoader#getResource}, not like + * {@link java.lang.Class#getResource}, so the name never begins with a + * slash. + * + *

+ * See {@link #parseResources(Class,String,ConfigParseOptions)} for full + * details. + * + * @param loader + * will be used to load resources by setting this loader on the + * provided options + * @param resource + * resource to look up + * @param options + * parse options (class loader is ignored) + * @return the parsed configuration + */ + public static Config parseResources(ClassLoader loader, String resource, + ConfigParseOptions options) { + return parseResources(resource, options.setClassLoader(loader)); + } + + /** + * Like {@link #parseResources(ClassLoader,String,ConfigParseOptions)} but always uses + * default parse options. + * + * @param loader + * will be used to load resources + * @param resource + * resource to look up in the loader + * @return the parsed configuration + */ + public static Config parseResources(ClassLoader loader, String resource) { + return parseResources(loader, resource, ConfigParseOptions.defaults()); + } + + /** + * Parses classpath resources with a flexible extension. In general, this + * method has the same behavior as + * {@link #parseFileAnySyntax(File,ConfigParseOptions)} but for classpath + * resources instead, as in + * {@link #parseResources(ClassLoader,String,ConfigParseOptions)}. + * + *

+ * {@link #parseResourcesAnySyntax(Class,String,ConfigParseOptions)} differs + * in the syntax for the resource name, but otherwise see + * {@link #parseResourcesAnySyntax(Class,String,ConfigParseOptions)} for + * some details and caveats on this method. + * + * @param loader + * class loader to look up resources in, will be set on options + * @param resourceBasename + * a resource name as in + * {@link java.lang.ClassLoader#getResource}, with or without + * extension + * @param options + * parse options (class loader ignored) + * @return the parsed configuration + */ + public static Config parseResourcesAnySyntax(ClassLoader loader, String resourceBasename, + ConfigParseOptions options) { + return ConfigImpl.parseResourcesAnySyntax(resourceBasename, options.setClassLoader(loader)) + .toConfig(); + } + + /** + * Like {@link #parseResourcesAnySyntax(ClassLoader,String,ConfigParseOptions)} but always uses + * default parse options. + * + * @param loader + * will be used to load resources + * @param resourceBasename + * a resource name as in + * {@link java.lang.ClassLoader#getResource}, with or without + * extension + * @return the parsed configuration + */ + public static Config parseResourcesAnySyntax(ClassLoader loader, String resourceBasename) { + return parseResourcesAnySyntax(loader, resourceBasename, ConfigParseOptions.defaults()); + } + + /** + * Like {@link #parseResources(ClassLoader,String,ConfigParseOptions)} but + * uses thread's current context class loader if none is set in the + * ConfigParseOptions. + * @param resource the resource name + * @param options parse options + * @return the parsed configuration + */ + public static Config parseResources(String resource, ConfigParseOptions options) { + ConfigParseOptions withLoader = ensureClassLoader(options, "parseResources"); + return Parseable.newResources(resource, withLoader).parse().toConfig(); + } + + /** + * Like {@link #parseResources(ClassLoader,String)} but uses thread's + * current context class loader. + * @param resource the resource name + * @return the parsed configuration + */ + public static Config parseResources(String resource) { + return parseResources(resource, ConfigParseOptions.defaults()); + } + + /** + * Like + * {@link #parseResourcesAnySyntax(ClassLoader,String,ConfigParseOptions)} + * but uses thread's current context class loader. + * @param resourceBasename the resource basename (no file type suffix) + * @param options parse options + * @return the parsed configuration + */ + public static Config parseResourcesAnySyntax(String resourceBasename, ConfigParseOptions options) { + return ConfigImpl.parseResourcesAnySyntax(resourceBasename, options).toConfig(); + } + + /** + * Like {@link #parseResourcesAnySyntax(ClassLoader,String)} but uses + * thread's current context class loader. + * @param resourceBasename the resource basename (no file type suffix) + * @return the parsed configuration + */ + public static Config parseResourcesAnySyntax(String resourceBasename) { + return parseResourcesAnySyntax(resourceBasename, ConfigParseOptions.defaults()); + } + + /** + * Parses a string (which should be valid HOCON or JSON by default, or + * the syntax specified in the options otherwise). + * + * @param s string to parse + * @param options parse options + * @return the parsed configuration + */ + public static Config parseString(String s, ConfigParseOptions options) { + return Parseable.newString(s, options).parse().toConfig(); + } + + /** + * Parses a string (which should be valid HOCON or JSON). + * + * @param s string to parse + * @return the parsed configuration + */ + public static Config parseString(String s) { + return parseString(s, ConfigParseOptions.defaults()); + } + + /** + * Creates a {@code Config} based on a {@link java.util.Map} from paths to + * plain Java values. Similar to + * {@link ConfigValueFactory#fromMap(Map,String)}, except the keys in the + * map are path expressions, rather than keys; and correspondingly it + * returns a {@code Config} instead of a {@code ConfigObject}. This is more + * convenient if you are writing literal maps in code, and less convenient + * if you are getting your maps from some data source such as a parser. + * + *

+ * An exception will be thrown (and it is a bug in the caller of the method) + * if a path is both an object and a value, for example if you had both + * "a=foo" and "a.b=bar", then "a" is both the string "foo" and the parent + * object of "b". The caller of this method should ensure that doesn't + * happen. + * + * @param values map from paths to plain Java objects + * @param originDescription + * description of what this map represents, like a filename, or + * "default settings" (origin description is used in error + * messages) + * @return the map converted to a {@code Config} + */ + public static Config parseMap(Map values, + String originDescription) { + return ConfigImpl.fromPathMap(values, originDescription).toConfig(); + } + + /** + * See the other overload of {@link #parseMap(Map, String)} for details, + * this one just uses a default origin description. + * + * @param values map from paths to plain Java values + * @return the map converted to a {@code Config} + */ + public static Config parseMap(Map values) { + return parseMap(values, null); + } + + private static ConfigLoadingStrategy getConfigLoadingStrategy() { + String className = System.getProperties().getProperty(STRATEGY_PROPERTY_NAME); + + if (className != null) { + try { + return ConfigLoadingStrategy.class.cast(Class.forName(className).newInstance()); + } catch (Throwable e) { + throw new ConfigException.BugOrBroken("Failed to load strategy: " + className, e); + } + } else { + return new DefaultConfigLoadingStrategy(); + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncludeContext.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncludeContext.java new file mode 100644 index 0000000..42a5b87 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncludeContext.java @@ -0,0 +1,56 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + + +/** + * Context provided to a {@link ConfigIncluder}; this interface is only useful + * inside a {@code ConfigIncluder} implementation, and is not intended for apps + * to implement. + * + *

+ * Do not implement this interface; it should only be implemented by + * the config library. Arbitrary implementations will not work because the + * library internals assume a specific concrete implementation. Also, this + * interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface ConfigIncludeContext { + /** + * Tries to find a name relative to whatever is doing the including, for + * example in the same directory as the file doing the including. Returns + * null if it can't meaningfully create a relative name. The returned + * parseable may not exist; this function is not required to do any IO, just + * compute what the name would be. + * + * The passed-in filename has to be a complete name (with extension), not + * just a basename. (Include statements in config files are allowed to give + * just a basename.) + * + * @param filename + * the name to make relative to the resource doing the including + * @return parseable item relative to the resource doing the including, or + * null + */ + ConfigParseable relativeTo(String filename); + + /** + * Parse options to use (if you use another method to get a + * {@link ConfigParseable} then use {@link ConfigParseable#options()} + * instead though). + * + * @return the parse options + */ + ConfigParseOptions parseOptions(); + + + /** + * Copy this {@link ConfigIncludeContext} giving it a new value for its parseOptions. + * + * @param options new parse options to use + * + * @return the updated copy of this context + */ + ConfigIncludeContext setParseOptions(ConfigParseOptions options); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluder.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluder.java new file mode 100644 index 0000000..21db0dc --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluder.java @@ -0,0 +1,50 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * Implement this interface and provide an instance to + * {@link ConfigParseOptions#setIncluder ConfigParseOptions.setIncluder()} to + * customize handling of {@code include} statements in config files. You may + * also want to implement {@link ConfigIncluderClasspath}, + * {@link ConfigIncluderFile}, and {@link ConfigIncluderURL}, or not. + */ +public interface ConfigIncluder { + /** + * Returns a new includer that falls back to the given includer. This is how + * you can obtain the default includer; it will be provided as a fallback. + * It's up to your includer to chain to it if you want to. You might want to + * merge any files found by the fallback includer with any objects you load + * yourself. + * + * It's important to handle the case where you already have the fallback + * with a "return this", i.e. this method should not create a new object if + * the fallback is the same one you already have. The same fallback may be + * added repeatedly. + * + * @param fallback the previous includer for chaining + * @return a new includer + */ + ConfigIncluder withFallback(ConfigIncluder fallback); + + /** + * Parses another item to be included. The returned object typically would + * not have substitutions resolved. You can throw a ConfigException here to + * abort parsing, or return an empty object, but may not return null. + * + * This method is used for a "heuristic" include statement that does not + * specify file, URL, or classpath resource. If the include statement does + * specify, then the same class implementing {@link ConfigIncluder} must + * also implement {@link ConfigIncluderClasspath}, + * {@link ConfigIncluderFile}, or {@link ConfigIncluderURL} as needed, or a + * default includer will be used. + * + * @param context + * some info about the include context + * @param what + * the include statement's argument + * @return a non-null ConfigObject + */ + ConfigObject include(ConfigIncludeContext context, String what); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderClasspath.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderClasspath.java new file mode 100644 index 0000000..0903073 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderClasspath.java @@ -0,0 +1,25 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * Implement this in addition to {@link ConfigIncluder} if you want to + * support inclusion of files with the {@code include classpath("resource")} + * syntax. If you do not implement this but do implement {@link ConfigIncluder}, + * attempts to load classpath resources will use the default includer. + */ +public interface ConfigIncluderClasspath { + /** + * Parses another item to be included. The returned object typically would + * not have substitutions resolved. You can throw a ConfigException here to + * abort parsing, or return an empty object, but may not return null. + * + * @param context + * some info about the include context + * @param what + * the include statement's argument + * @return a non-null ConfigObject + */ + ConfigObject includeResources(ConfigIncludeContext context, String what); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderFile.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderFile.java new file mode 100644 index 0000000..57f85f6 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderFile.java @@ -0,0 +1,27 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.io.File; + +/** + * Implement this in addition to {@link ConfigIncluder} if you want to + * support inclusion of files with the {@code include file("filename")} syntax. + * If you do not implement this but do implement {@link ConfigIncluder}, + * attempts to load files will use the default includer. + */ +public interface ConfigIncluderFile { + /** + * Parses another item to be included. The returned object typically would + * not have substitutions resolved. You can throw a ConfigException here to + * abort parsing, or return an empty object, but may not return null. + * + * @param context + * some info about the include context + * @param what + * the include statement's argument + * @return a non-null ConfigObject + */ + ConfigObject includeFile(ConfigIncludeContext context, File what); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderURL.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderURL.java new file mode 100644 index 0000000..c5c40e4 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigIncluderURL.java @@ -0,0 +1,27 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.net.URL; + +/** + * Implement this in addition to {@link ConfigIncluder} if you want to + * support inclusion of files with the {@code include url("http://example.com")} + * syntax. If you do not implement this but do implement {@link ConfigIncluder}, + * attempts to load URLs will use the default includer. + */ +public interface ConfigIncluderURL { + /** + * Parses another item to be included. The returned object typically would + * not have substitutions resolved. You can throw a ConfigException here to + * abort parsing, or return an empty object, but may not return null. + * + * @param context + * some info about the include context + * @param what + * the include statement's argument + * @return a non-null ConfigObject + */ + ConfigObject includeURL(ConfigIncludeContext context, URL what); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigList.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigList.java new file mode 100644 index 0000000..dace555 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigList.java @@ -0,0 +1,48 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.util.List; + +/** + * Subtype of {@link ConfigValue} representing a list value, as in JSON's + * {@code [1,2,3]} syntax. + * + *

+ * {@code ConfigList} implements {@code java.util.List} so you can + * use it like a regular Java list. Or call {@link #unwrapped()} to unwrap the + * list elements into plain Java values. + * + *

+ * Like all {@link ConfigValue} subtypes, {@code ConfigList} is immutable. This + * makes it threadsafe and you never have to create "defensive copies." The + * mutator methods from {@link java.util.List} all throw + * {@link java.lang.UnsupportedOperationException}. + * + *

+ * The {@link ConfigValue#valueType} method on a list returns + * {@link ConfigValueType#LIST}. + * + *

+ * Do not implement {@code ConfigList}; it should only be implemented + * by the config library. Arbitrary implementations will not work because the + * library internals assume a specific concrete implementation. Also, this + * interface is likely to grow new methods over time, so third-party + * implementations will break. + * + */ +public interface ConfigList extends List, ConfigValue { + + /** + * Recursively unwraps the list, returning a list of plain Java values such + * as Integer or String or whatever is in the list. + * + * @return a {@link java.util.List} containing plain Java objects + */ + @Override + List unwrapped(); + + @Override + ConfigList withOrigin(ConfigOrigin origin); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigLoadingStrategy.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigLoadingStrategy.java new file mode 100644 index 0000000..226d533 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigLoadingStrategy.java @@ -0,0 +1,20 @@ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * This method allows you to alter default config loading strategy for all the code which + * calls {@link ConfigFactory#load}. + * + * Usually you don't have to implement this interface but it may be required + * when you fixing a improperly implemented library with unavailable source code. + * + * You have to define VM property {@code config.strategy} to replace default strategy with your own. + */ +public interface ConfigLoadingStrategy { + /** + * This method must load and parse application config. + * + * @param parseOptions {@link ConfigParseOptions} to use + * @return loaded config + */ + Config parseApplicationConfig(ConfigParseOptions parseOptions); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigMemorySize.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigMemorySize.java new file mode 100644 index 0000000..319196a --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigMemorySize.java @@ -0,0 +1,63 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * An immutable class representing an amount of memory. Use + * static factory methods such as {@link + * ConfigMemorySize#ofBytes(long)} to create instances. + * + * @since 1.3.0 + */ +public final class ConfigMemorySize { + private final long bytes; + + private ConfigMemorySize(long bytes) { + if (bytes < 0) + throw new IllegalArgumentException("Attempt to construct ConfigMemorySize with negative number: " + bytes); + this.bytes = bytes; + } + + /** + * Constructs a ConfigMemorySize representing the given + * number of bytes. + * @since 1.3.0 + * @param bytes a number of bytes + * @return an instance representing the number of bytes + */ + public static ConfigMemorySize ofBytes(long bytes) { + return new ConfigMemorySize(bytes); + } + + /** + * Gets the size in bytes. + * @since 1.3.0 + * @return how many bytes + */ + public long toBytes() { + return bytes; + } + + @Override + public String toString() { + return "ConfigMemorySize(" + bytes + ")"; + } + + @Override + public boolean equals(Object other) { + if (other instanceof ConfigMemorySize) { + return ((ConfigMemorySize)other).bytes == this.bytes; + } else { + return false; + } + } + + @Override + public int hashCode() { + // in Java 8 this can become Long.hashCode(bytes) + return Long.valueOf(bytes).hashCode(); + } + +} + diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigMergeable.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigMergeable.java new file mode 100644 index 0000000..7159b1a --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigMergeable.java @@ -0,0 +1,72 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * Marker for types whose instances can be merged, that is {@link Config} and + * {@link ConfigValue}. Instances of {@code Config} and {@code ConfigValue} can + * be combined into a single new instance using the + * {@link ConfigMergeable#withFallback withFallback()} method. + * + *

+ * Do not implement this interface; it should only be implemented by + * the config library. Arbitrary implementations will not work because the + * library internals assume a specific concrete implementation. Also, this + * interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface ConfigMergeable { + /** + * Returns a new value computed by merging this value with another, with + * keys in this value "winning" over the other one. + * + *

+ * This associative operation may be used to combine configurations from + * multiple sources (such as multiple configuration files). + * + *

+ * The semantics of merging are described in the spec + * for HOCON. Merging typically occurs when either the same object is + * created twice in the same file, or two config files are both loaded. For + * example: + * + *

+     *  foo = { a: 42 }
+     *  foo = { b: 43 }
+     * 
+ * + * Here, the two objects are merged as if you had written: + * + *
+     *  foo = { a: 42, b: 43 }
+     * 
+ * + *

+ * Only {@link ConfigObject} and {@link Config} instances do anything in + * this method (they need to merge the fallback keys into themselves). All + * other values just return the original value, since they automatically + * override any fallback. This means that objects do not merge "across" + * non-objects; if you write + * object.withFallback(nonObject).withFallback(otherObject), + * then otherObject will simply be ignored. This is an + * intentional part of how merging works, because non-objects such as + * strings and integers replace (rather than merging with) any prior value: + * + *

+     * foo = { a: 42 }
+     * foo = 10
+     * 
+ * + * Here, the number 10 "wins" and the value of foo would be + * simply 10. Again, for details see the spec. + * + * @param other + * an object whose keys should be used as fallbacks, if the keys + * are not present in this one + * @return a new object (or the original one, if the fallback doesn't get + * used) + */ + ConfigMergeable withFallback(ConfigMergeable other); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigObject.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigObject.java new file mode 100644 index 0000000..2bfcfab --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigObject.java @@ -0,0 +1,135 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.util.Map; + +/** + * Subtype of {@link ConfigValue} representing an object (AKA dictionary or map) + * value, as in JSON's curly brace { "a" : 42 } syntax. + * + *

+ * An object may also be viewed as a {@link Config} by calling + * {@link ConfigObject#toConfig()}. + * + *

+ * {@code ConfigObject} implements {@code java.util.Map} so + * you can use it like a regular Java map. Or call {@link #unwrapped()} to + * unwrap the map to a map with plain Java values rather than + * {@code ConfigValue}. + * + *

+ * Like all {@link ConfigValue} subtypes, {@code ConfigObject} is immutable. + * This makes it threadsafe and you never have to create "defensive copies." The + * mutator methods from {@link java.util.Map} all throw + * {@link java.lang.UnsupportedOperationException}. + * + *

+ * The {@link ConfigValue#valueType} method on an object returns + * {@link ConfigValueType#OBJECT}. + * + *

+ * In most cases you want to use the {@link Config} interface rather than this + * one. Call {@link #toConfig()} to convert a {@code ConfigObject} to a + * {@code Config}. + * + *

+ * The API for a {@code ConfigObject} is in terms of keys, while the API for a + * {@link Config} is in terms of path expressions. Conceptually, + * {@code ConfigObject} is a tree of maps from keys to values, while a + * {@code Config} is a one-level map from paths to values. + * + *

+ * Use {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath} to convert + * between path expressions and individual path elements (keys). + * + *

+ * A {@code ConfigObject} may contain null values, which will have + * {@link ConfigValue#valueType()} equal to {@link ConfigValueType#NULL}. If + * {@link ConfigObject#get(Object)} returns Java's null then the key was not + * present in the parsed file (or wherever this value tree came from). If + * {@code get("key")} returns a {@link ConfigValue} with type + * {@code ConfigValueType#NULL} then the key was set to null explicitly in the + * config file. + * + *

+ * Do not implement interface {@code ConfigObject}; it should only be + * implemented by the config library. Arbitrary implementations will not work + * because the library internals assume a specific concrete implementation. + * Also, this interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface ConfigObject extends ConfigValue, Map { + + /** + * Converts this object to a {@link Config} instance, enabling you to use + * path expressions to find values in the object. This is a constant-time + * operation (it is not proportional to the size of the object). + * + * @return a {@link Config} with this object as its root + */ + Config toConfig(); + + /** + * Recursively unwraps the object, returning a map from String to whatever + * plain Java values are unwrapped from the object's values. + * + * @return a {@link java.util.Map} containing plain Java objects + */ + @Override + Map unwrapped(); + + @Override + ConfigObject withFallback(ConfigMergeable other); + + /** + * Gets a {@link ConfigValue} at the given key, or returns null if there is + * no value. The returned {@link ConfigValue} may have + * {@link ConfigValueType#NULL} or any other type, and the passed-in key + * must be a key in this object (rather than a path expression). + * + * @param key + * key to look up + * + * @return the value at the key or null if none + */ + @Override + ConfigValue get(Object key); + + /** + * Clone the object with only the given key (and its children) retained; all + * sibling keys are removed. + * + * @param key + * key to keep + * @return a copy of the object minus all keys except the one specified + */ + ConfigObject withOnlyKey(String key); + + /** + * Clone the object with the given key removed. + * + * @param key + * key to remove + * @return a copy of the object minus the specified key + */ + ConfigObject withoutKey(String key); + + /** + * Returns a {@code ConfigObject} based on this one, but with the given key + * set to the given value. Does not modify this instance (since it's + * immutable). If the key already has a value, that value is replaced. To + * remove a value, use {@link ConfigObject#withoutKey(String)}. + * + * @param key + * key to add + * @param value + * value at the new key + * @return the new instance with the new map entry + */ + ConfigObject withValue(String key, ConfigValue value); + + @Override + ConfigObject withOrigin(ConfigOrigin origin); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigOrigin.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigOrigin.java new file mode 100644 index 0000000..9760992 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigOrigin.java @@ -0,0 +1,118 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.net.URL; +import java.util.List; + + +/** + * Represents the origin (such as filename and line number) of a + * {@link ConfigValue} for use in error messages. Obtain the origin of a value + * with {@link ConfigValue#origin}. Exceptions may have an origin, see + * {@link ConfigException#origin}, but be careful because + * ConfigException.origin() may return null. + * + *

+ * It's best to use this interface only for debugging; its accuracy is + * "best effort" rather than guaranteed, and a potentially-noticeable amount of + * memory could probably be saved if origins were not kept around, so in the + * future there might be some option to discard origins. + * + *

+ * Do not implement this interface; it should only be implemented by + * the config library. Arbitrary implementations will not work because the + * library internals assume a specific concrete implementation. Also, this + * interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface ConfigOrigin { + /** + * Returns a string describing the origin of a value or exception. This will + * never return null. + * + * @return string describing the origin + */ + public String description(); + + /** + * Returns a filename describing the origin. This will return null if the + * origin was not a file. + * + * @return filename of the origin or null + */ + public String filename(); + + /** + * Returns a URL describing the origin. This will return null if the origin + * has no meaningful URL. + * + * @return url of the origin or null + */ + public URL url(); + + /** + * Returns a classpath resource name describing the origin. This will return + * null if the origin was not a classpath resource. + * + * @return resource name of the origin or null + */ + public String resource(); + + /** + * Returns a line number where the value or exception originated. This will + * return -1 if there's no meaningful line number. + * + * @return line number or -1 if none is available + */ + public int lineNumber(); + + /** + * Returns any comments that appeared to "go with" this place in the file. + * Often an empty list, but never null. The details of this are subject to + * change, but at the moment comments that are immediately before an array + * element or object field, with no blank line after the comment, "go with" + * that element or field. + * + * @return any comments that seemed to "go with" this origin, empty list if + * none + */ + public List comments(); + + /** + * Returns a {@code ConfigOrigin} based on this one, but with the given + * comments. Does not modify this instance or any {@code ConfigValue}s with + * this origin (since they are immutable). To set the returned origin to a + * {@code ConfigValue}, use {@link ConfigValue#withOrigin}. + * + *

+ * Note that when the given comments are equal to the comments on this object, + * a new instance may not be created and {@code this} is returned directly. + * + * @since 1.3.0 + * + * @param comments the comments used on the returned origin + * @return the ConfigOrigin with the given comments + */ + public ConfigOrigin withComments(List comments); + + /** + * Returns a {@code ConfigOrigin} based on this one, but with the given + * line number. This origin must be a FILE, URL or RESOURCE. Does not modify + * this instance or any {@code ConfigValue}s with this origin (since they are + * immutable). To set the returned origin to a {@code ConfigValue}, use + * {@link ConfigValue#withOrigin}. + * + *

+ * Note that when the given lineNumber are equal to the lineNumber on this + * object, a new instance may not be created and {@code this} is returned + * directly. + * + * @since 1.3.0 + * + * @param lineNumber the new line number + * @return the created ConfigOrigin + */ + public ConfigOrigin withLineNumber(int lineNumber); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigOriginFactory.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigOriginFactory.java new file mode 100644 index 0000000..b1dd318 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigOriginFactory.java @@ -0,0 +1,68 @@ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.net.URL; + +import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImpl; + +/** + * This class contains some static factory methods for building a {@link + * ConfigOrigin}. {@code ConfigOrigin}s are automatically created when you + * call other API methods to get a {@code ConfigValue} or {@code Config}. + * But you can also set the origin of an existing {@code ConfigValue}, using + * {@link ConfigValue#withOrigin(ConfigOrigin)}. + * + * @since 1.3.0 + */ +public final class ConfigOriginFactory { + private ConfigOriginFactory() { + } + + /** + * Returns the default origin for values when no other information is + * provided. This is the origin used in {@link ConfigValueFactory + * #fromAnyRef(Object)}. + * + * @since 1.3.0 + * + * @return the default origin + */ + public static ConfigOrigin newSimple() { + return newSimple(null); + } + + /** + * Returns an origin with the given description. + * + * @since 1.3.0 + * + * @param description brief description of what the origin is + * @return a new origin + */ + public static ConfigOrigin newSimple(String description) { + return ConfigImpl.newSimpleOrigin(description); + } + + /** + * Creates a file origin with the given filename. + * + * @since 1.3.0 + * + * @param filename the filename of this origin + * @return a new origin + */ + public static ConfigOrigin newFile(String filename) { + return ConfigImpl.newFileOrigin(filename); + } + + /** + * Creates a url origin with the given URL object. + * + * @since 1.3.0 + * + * @param url the url of this origin + * @return a new origin + */ + public static ConfigOrigin newURL(URL url) { + return ConfigImpl.newURLOrigin(url); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigParseOptions.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigParseOptions.java new file mode 100644 index 0000000..6a08315 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigParseOptions.java @@ -0,0 +1,228 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + + +/** + * A set of options related to parsing. + * + *

+ * This object is immutable, so the "setters" return a new object. + * + *

+ * Here is an example of creating a custom {@code ConfigParseOptions}: + * + *

+ *     ConfigParseOptions options = ConfigParseOptions.defaults()
+ *         .setSyntax(ConfigSyntax.JSON)
+ *         .setAllowMissing(false)
+ * 
+ * + */ +public final class ConfigParseOptions { + final ConfigSyntax syntax; + final String originDescription; + final boolean allowMissing; + final ConfigIncluder includer; + final ClassLoader classLoader; + + private ConfigParseOptions(ConfigSyntax syntax, String originDescription, boolean allowMissing, + ConfigIncluder includer, ClassLoader classLoader) { + this.syntax = syntax; + this.originDescription = originDescription; + this.allowMissing = allowMissing; + this.includer = includer; + this.classLoader = classLoader; + } + + /** + * Gets an instance of ConfigParseOptions with all fields + * set to the default values. Start with this instance and make any + * changes you need. + * @return the default parse options + */ + public static ConfigParseOptions defaults() { + return new ConfigParseOptions(null, null, true, null, null); + } + + /** + * Set the file format. If set to null, try to guess from any available + * filename extension; if guessing fails, assume {@link ConfigSyntax#CONF}. + * + * @param syntax + * a syntax or {@code null} for best guess + * @return options with the syntax set + */ + public ConfigParseOptions setSyntax(ConfigSyntax syntax) { + if (this.syntax == syntax) + return this; + else + return new ConfigParseOptions(syntax, this.originDescription, this.allowMissing, + this.includer, this.classLoader); + } + + /** + * Gets the current syntax option, which may be null for "any". + * @return the current syntax or null + */ + public ConfigSyntax getSyntax() { + return syntax; + } + + /** + * Set a description for the thing being parsed. In most cases this will be + * set up for you to something like the filename, but if you provide just an + * input stream you might want to improve on it. Set to null to allow the + * library to come up with something automatically. This description is the + * basis for the {@link ConfigOrigin} of the parsed values. + * + * @param originDescription description to put in the {@link ConfigOrigin} + * @return options with the origin description set + */ + public ConfigParseOptions setOriginDescription(String originDescription) { + // findbugs complains about == here but is wrong, do not "fix" + if (this.originDescription == originDescription) + return this; + else if (this.originDescription != null && originDescription != null + && this.originDescription.equals(originDescription)) + return this; + else + return new ConfigParseOptions(this.syntax, originDescription, this.allowMissing, + this.includer, this.classLoader); + } + + /** + * Gets the current origin description, which may be null for "automatic". + * @return the current origin description or null + */ + public String getOriginDescription() { + return originDescription; + } + + /** this is package-private, not public API */ + ConfigParseOptions withFallbackOriginDescription(String originDescription) { + if (this.originDescription == null) + return setOriginDescription(originDescription); + else + return this; + } + + /** + * Set to false to throw an exception if the item being parsed (for example + * a file) is missing. Set to true to just return an empty document in that + * case. Note that this setting applies on only to fetching the root document, + * it has no effect on any nested includes. + * + * @param allowMissing true to silently ignore missing item + * @return options with the "allow missing" flag set + */ + public ConfigParseOptions setAllowMissing(boolean allowMissing) { + if (this.allowMissing == allowMissing) + return this; + else + return new ConfigParseOptions(this.syntax, this.originDescription, allowMissing, + this.includer, this.classLoader); + } + + /** + * Gets the current "allow missing" flag. + * @return whether we allow missing files + */ + public boolean getAllowMissing() { + return allowMissing; + } + + /** + * Set a {@link ConfigIncluder} which customizes how includes are handled. + * null means to use the default includer. + * + * @param includer the includer to use or null for default + * @return new version of the parse options with different includer + */ + public ConfigParseOptions setIncluder(ConfigIncluder includer) { + if (this.includer == includer) + return this; + else + return new ConfigParseOptions(this.syntax, this.originDescription, this.allowMissing, + includer, this.classLoader); + } + + /** + * Prepends a {@link ConfigIncluder} which customizes how + * includes are handled. To prepend your includer, the + * library calls {@link ConfigIncluder#withFallback} on your + * includer to append the existing includer to it. + * + * @param includer the includer to prepend (may not be null) + * @return new version of the parse options with different includer + */ + public ConfigParseOptions prependIncluder(ConfigIncluder includer) { + if (includer == null) + throw new NullPointerException("null includer passed to prependIncluder"); + if (this.includer == includer) + return this; + else if (this.includer != null) + return setIncluder(includer.withFallback(this.includer)); + else + return setIncluder(includer); + } + + /** + * Appends a {@link ConfigIncluder} which customizes how + * includes are handled. To append, the library calls {@link + * ConfigIncluder#withFallback} on the existing includer. + * + * @param includer the includer to append (may not be null) + * @return new version of the parse options with different includer + */ + public ConfigParseOptions appendIncluder(ConfigIncluder includer) { + if (includer == null) + throw new NullPointerException("null includer passed to appendIncluder"); + if (this.includer == includer) + return this; + else if (this.includer != null) + return setIncluder(this.includer.withFallback(includer)); + else + return setIncluder(includer); + } + + /** + * Gets the current includer (will be null for the default includer). + * @return current includer or null + */ + public ConfigIncluder getIncluder() { + return includer; + } + + /** + * Set the class loader. If set to null, + * Thread.currentThread().getContextClassLoader() will be used. + * + * @param loader + * a class loader or {@code null} to use thread context class + * loader + * @return options with the class loader set + */ + public ConfigParseOptions setClassLoader(ClassLoader loader) { + if (this.classLoader == loader) + return this; + else + return new ConfigParseOptions(this.syntax, this.originDescription, this.allowMissing, + this.includer, loader); + } + + /** + * Get the class loader; never returns {@code null}, if the class loader was + * unset, returns + * Thread.currentThread().getContextClassLoader(). + * + * @return class loader to use + */ + public ClassLoader getClassLoader() { + if (this.classLoader == null) + return Thread.currentThread().getContextClassLoader(); + else + return this.classLoader; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigParseable.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigParseable.java new file mode 100644 index 0000000..3f226c1 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigParseable.java @@ -0,0 +1,45 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + + +/** + * An opaque handle to something that can be parsed, obtained from + * {@link ConfigIncludeContext}. + * + *

+ * Do not implement this interface; it should only be implemented by + * the config library. Arbitrary implementations will not work because the + * library internals assume a specific concrete implementation. Also, this + * interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface ConfigParseable { + /** + * Parse whatever it is. The options should come from + * {@link ConfigParseable#options options()} but you could tweak them if you + * like. + * + * @param options + * parse options, should be based on the ones from + * {@link ConfigParseable#options options()} + * @return the parsed object + */ + ConfigObject parse(ConfigParseOptions options); + + /** + * Returns a {@link ConfigOrigin} describing the origin of the parseable + * item. + * @return the origin of the parseable item + */ + ConfigOrigin origin(); + + /** + * Get the initial options, which can be modified then passed to parse(). + * These options will have the right description, includer, and other + * parameters already set up. + * @return the initial options + */ + ConfigParseOptions options(); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigRenderOptions.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigRenderOptions.java new file mode 100644 index 0000000..90f4a83 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigRenderOptions.java @@ -0,0 +1,182 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + *

+ * A set of options related to rendering a {@link ConfigValue}. Passed to + * {@link ConfigValue#render(ConfigRenderOptions)}. + * + *

+ * Here is an example of creating a {@code ConfigRenderOptions}: + * + *

+ *     ConfigRenderOptions options =
+ *         ConfigRenderOptions.defaults().setComments(false)
+ * 
+ */ +public final class ConfigRenderOptions { + private final boolean originComments; + private final boolean comments; + private final boolean formatted; + private final boolean json; + + private ConfigRenderOptions(boolean originComments, boolean comments, boolean formatted, + boolean json) { + this.originComments = originComments; + this.comments = comments; + this.formatted = formatted; + this.json = json; + } + + /** + * Returns the default render options which are verbose (commented and + * formatted). See {@link ConfigRenderOptions#concise} for stripped-down + * options. This rendering will not be valid JSON since it has comments. + * + * @return the default render options + */ + public static ConfigRenderOptions defaults() { + return new ConfigRenderOptions(true, true, true, true); + } + + /** + * Returns concise render options (no whitespace or comments). For a + * resolved {@link Config}, the concise rendering will be valid JSON. + * + * @return the concise render options + */ + public static ConfigRenderOptions concise() { + return new ConfigRenderOptions(false, false, false, true); + } + + /** + * Returns options with comments toggled. This controls human-written + * comments but not the autogenerated "origin of this setting" comments, + * which are controlled by {@link ConfigRenderOptions#setOriginComments}. + * + * @param value + * true to include comments in the render + * @return options with requested setting for comments + */ + public ConfigRenderOptions setComments(boolean value) { + if (value == comments) + return this; + else + return new ConfigRenderOptions(originComments, value, formatted, json); + } + + /** + * Returns whether the options enable comments. This method is mostly used + * by the config lib internally, not by applications. + * + * @return true if comments should be rendered + */ + public boolean getComments() { + return comments; + } + + /** + * Returns options with origin comments toggled. If this is enabled, the + * library generates comments for each setting based on the + * {@link ConfigValue#origin} of that setting's value. For example these + * comments might tell you which file a setting comes from. + * + *

+ * {@code setOriginComments()} controls only these autogenerated + * "origin of this setting" comments, to toggle regular comments use + * {@link ConfigRenderOptions#setComments}. + * + * @param value + * true to include autogenerated setting-origin comments in the + * render + * @return options with origin comments toggled + */ + public ConfigRenderOptions setOriginComments(boolean value) { + if (value == originComments) + return this; + else + return new ConfigRenderOptions(value, comments, formatted, json); + } + + /** + * Returns whether the options enable automated origin comments. This method + * is mostly used by the config lib internally, not by applications. + * + * @return true if origin comments should be rendered + */ + public boolean getOriginComments() { + return originComments; + } + + /** + * Returns options with formatting toggled. Formatting means indentation and + * whitespace, enabling formatting makes things prettier but larger. + * + * @param value + * true to enable formatting + * @return options with requested setting for formatting + */ + public ConfigRenderOptions setFormatted(boolean value) { + if (value == formatted) + return this; + else + return new ConfigRenderOptions(originComments, comments, value, json); + } + + /** + * Returns whether the options enable formatting. This method is mostly used + * by the config lib internally, not by applications. + * + * @return true if the options enable formatting + */ + public boolean getFormatted() { + return formatted; + } + + /** + * Returns options with JSON toggled. JSON means that HOCON extensions + * (omitting commas, quotes for example) won't be used. However, whether to + * use comments is controlled by the separate {@link #setComments(boolean)} + * and {@link #setOriginComments(boolean)} options. So if you enable + * comments you will get invalid JSON despite setting this to true. + * + * @param value + * true to include non-JSON extensions in the render + * @return options with requested setting for JSON + */ + public ConfigRenderOptions setJson(boolean value) { + if (value == json) + return this; + else + return new ConfigRenderOptions(originComments, comments, formatted, value); + } + + /** + * Returns whether the options enable JSON. This method is mostly used by + * the config lib internally, not by applications. + * + * @return true if only JSON should be rendered + */ + public boolean getJson() { + return json; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("ConfigRenderOptions("); + if (originComments) + sb.append("originComments,"); + if (comments) + sb.append("comments,"); + if (formatted) + sb.append("formatted,"); + if (json) + sb.append("json,"); + if (sb.charAt(sb.length() - 1) == ',') + sb.setLength(sb.length() - 1); + sb.append(")"); + return sb.toString(); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigResolveOptions.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigResolveOptions.java new file mode 100644 index 0000000..34c4128 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigResolveOptions.java @@ -0,0 +1,176 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * A set of options related to resolving substitutions. Substitutions use the + * ${foo.bar} syntax and are documented in the HOCON + * spec. + *

+ * Typically this class would be used with the method + * {@link Config#resolve(ConfigResolveOptions)}. + *

+ * This object is immutable, so the "setters" return a new object. + *

+ * Here is an example of creating a custom {@code ConfigResolveOptions}: + * + *

+ *     ConfigResolveOptions options = ConfigResolveOptions.defaults()
+ *         .setUseSystemEnvironment(false)
+ * 
+ *

+ * In addition to {@link ConfigResolveOptions#defaults}, there's a prebuilt + * {@link ConfigResolveOptions#noSystem} which avoids looking at any system + * environment variables or other external system information. (Right now, + * environment variables are the only example.) + */ +public final class ConfigResolveOptions { + private final boolean useSystemEnvironment; + private final boolean allowUnresolved; + private final ConfigResolver resolver; + + private ConfigResolveOptions(boolean useSystemEnvironment, boolean allowUnresolved, + ConfigResolver resolver) { + this.useSystemEnvironment = useSystemEnvironment; + this.allowUnresolved = allowUnresolved; + this.resolver = resolver; + } + + /** + * Returns the default resolve options. By default the system environment + * will be used and unresolved substitutions are not allowed. + * + * @return the default resolve options + */ + public static ConfigResolveOptions defaults() { + return new ConfigResolveOptions(true, false, NULL_RESOLVER); + } + + /** + * Returns resolve options that disable any reference to "system" data + * (currently, this means environment variables). + * + * @return the resolve options with env variables disabled + */ + public static ConfigResolveOptions noSystem() { + return defaults().setUseSystemEnvironment(false); + } + + /** + * Returns options with use of environment variables set to the given value. + * + * @param value + * true to resolve substitutions falling back to environment + * variables. + * @return options with requested setting for use of environment variables + */ + public ConfigResolveOptions setUseSystemEnvironment(boolean value) { + return new ConfigResolveOptions(value, allowUnresolved, resolver); + } + + /** + * Returns whether the options enable use of system environment variables. + * This method is mostly used by the config lib internally, not by + * applications. + * + * @return true if environment variables should be used + */ + public boolean getUseSystemEnvironment() { + return useSystemEnvironment; + } + + /** + * Returns options with "allow unresolved" set to the given value. By + * default, unresolved substitutions are an error. If unresolved + * substitutions are allowed, then a future attempt to use the unresolved + * value may fail, but {@link Config#resolve(ConfigResolveOptions)} itself + * will not throw. + * + * @param value + * true to silently ignore unresolved substitutions. + * @return options with requested setting for whether to allow substitutions + * @since 1.2.0 + */ + public ConfigResolveOptions setAllowUnresolved(boolean value) { + return new ConfigResolveOptions(useSystemEnvironment, value, resolver); + } + + /** + * Returns options where the given resolver used as a fallback if a + * reference cannot be otherwise resolved. This resolver will only be called + * after resolution has failed to substitute with a value from within the + * config itself and with any other resolvers that have been appended before + * this one. Multiple resolvers can be added using, + * + *

+     *     ConfigResolveOptions options = ConfigResolveOptions.defaults()
+     *         .appendResolver(primary)
+     *         .appendResolver(secondary)
+     *         .appendResolver(tertiary);
+     * 
+ * + * With this config unresolved references will first be resolved with the + * primary resolver, if that fails then the secondary, and finally if that + * also fails the tertiary. + * + * If all fallbacks fail to return a substitution "allow unresolved" + * determines whether resolution fails or continues. + *` + * @param value the resolver to fall back to + * @return options that use the given resolver as a fallback + * @since 1.3.2 + */ + public ConfigResolveOptions appendResolver(ConfigResolver value) { + if (value == null) { + throw new ConfigException.BugOrBroken("null resolver passed to appendResolver"); + } else if (value == this.resolver) { + return this; + } else { + return new ConfigResolveOptions(useSystemEnvironment, allowUnresolved, + this.resolver.withFallback(value)); + } + } + + /** + * Returns the resolver to use as a fallback if a substitution cannot be + * otherwise resolved. Never returns null. This method is mostly used by the + * config lib internally, not by applications. + * + * @return the non-null fallback resolver + * @since 1.3.2 + */ + public ConfigResolver getResolver() { + return this.resolver; + } + + /** + * Returns whether the options allow unresolved substitutions. This method + * is mostly used by the config lib internally, not by applications. + * + * @return true if unresolved substitutions are allowed + * @since 1.2.0 + */ + public boolean getAllowUnresolved() { + return allowUnresolved; + } + + /** + * Singleton resolver that never resolves paths. + */ + private static final ConfigResolver NULL_RESOLVER = new ConfigResolver() { + + @Override + public ConfigValue lookup(String path) { + return null; + } + + @Override + public ConfigResolver withFallback(ConfigResolver fallback) { + return fallback; + } + + }; + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigResolver.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigResolver.java new file mode 100644 index 0000000..0db30e7 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigResolver.java @@ -0,0 +1,38 @@ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * Implement this interface and provide an instance to + * {@link ConfigResolveOptions#appendResolver ConfigResolveOptions.appendResolver()} + * to provide custom behavior when unresolved substitutions are encountered + * during resolution. + * @since 1.3.2 + */ +public interface ConfigResolver { + + /** + * Returns the value to substitute for the given unresolved path. To get the + * components of the path use {@link ConfigUtil#splitPath(String)}. If a + * non-null value is returned that value will be substituted, otherwise + * resolution will continue to consider the substitution as still + * unresolved. + * + * @param path the unresolved path + * @return the value to use as a substitution or null + */ + public ConfigValue lookup(String path); + + /** + * Returns a new resolver that falls back to the given resolver if this + * one doesn't provide a substitution itself. + * + * It's important to handle the case where you already have the fallback + * with a "return this", i.e. this method should not create a new object if + * the fallback is the same one you already have. The same fallback may be + * added repeatedly. + * + * @param fallback the previous includer for chaining + * @return a new resolver + */ + public ConfigResolver withFallback(ConfigResolver fallback); + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigSyntax.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigSyntax.java new file mode 100644 index 0000000..03de86c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigSyntax.java @@ -0,0 +1,36 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * The syntax of a character stream (JSON, HOCON + * aka ".conf", or Java properties). + * + */ +public enum ConfigSyntax { + /** + * Pedantically strict JSON format; no + * comments, no unexpected commas, no duplicate keys in the same object. + * Associated with the .json file extension and + * application/json Content-Type. + */ + JSON, + /** + * The JSON-superset HOCON format. Associated with the .conf file extension + * and application/hocon Content-Type. + */ + CONF, + /** + * Standard Java properties format. Associated with the .properties + * file extension and text/x-java-properties Content-Type. + */ + PROPERTIES; +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigUtil.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigUtil.java new file mode 100644 index 0000000..48c44c6 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigUtil.java @@ -0,0 +1,83 @@ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.util.List; + +import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImplUtil; + +/** + * Contains static utility methods. + * + */ +public final class ConfigUtil { + private ConfigUtil() { + + } + + /** + * Quotes and escapes a string, as in the JSON specification. + * + * @param s + * a string + * @return the string quoted and escaped + */ + public static String quoteString(String s) { + return ConfigImplUtil.renderJsonString(s); + } + + /** + * Converts a list of keys to a path expression, by quoting the path + * elements as needed and then joining them separated by a period. A path + * expression is usable with a {@link Config}, while individual path + * elements are usable with a {@link ConfigObject}. + *

+ * See the overview documentation for {@link Config} for more detail on path + * expressions vs. keys. + * + * @param elements + * the keys in the path + * @return a path expression + * @throws ConfigException + * if there are no elements + */ + public static String joinPath(String... elements) { + return ConfigImplUtil.joinPath(elements); + } + + /** + * Converts a list of strings to a path expression, by quoting the path + * elements as needed and then joining them separated by a period. A path + * expression is usable with a {@link Config}, while individual path + * elements are usable with a {@link ConfigObject}. + *

+ * See the overview documentation for {@link Config} for more detail on path + * expressions vs. keys. + * + * @param elements + * the keys in the path + * @return a path expression + * @throws ConfigException + * if the list is empty + */ + public static String joinPath(List elements) { + return ConfigImplUtil.joinPath(elements); + } + + /** + * Converts a path expression into a list of keys, by splitting on period + * and unquoting the individual path elements. A path expression is usable + * with a {@link Config}, while individual path elements are usable with a + * {@link ConfigObject}. + *

+ * See the overview documentation for {@link Config} for more detail on path + * expressions vs. keys. + * + * @param path + * a path expression + * @return the individual keys in the path + * @throws ConfigException + * if the path expression is invalid + */ + public static List splitPath(String path) { + return ConfigImplUtil.splitPath(path); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValue.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValue.java new file mode 100644 index 0000000..72ecf63 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValue.java @@ -0,0 +1,122 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * An immutable value, following the JSON type + * schema. + * + *

+ * Because this object is immutable, it is safe to use from multiple threads and + * there's no need for "defensive copies." + * + *

+ * Do not implement interface {@code ConfigValue}; it should only be + * implemented by the config library. Arbitrary implementations will not work + * because the library internals assume a specific concrete implementation. + * Also, this interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface ConfigValue extends ConfigMergeable { + /** + * The origin of the value (file, line number, etc.), for debugging and + * error messages. + * + * @return where the value came from + */ + ConfigOrigin origin(); + + /** + * The {@link ConfigValueType} of the value; matches the JSON type schema. + * + * @return value's type + */ + ConfigValueType valueType(); + + /** + * Returns the value as a plain Java boxed value, that is, a {@code String}, + * {@code Number}, {@code Boolean}, {@code Map}, + * {@code List}, or {@code null}, matching the {@link #valueType()} + * of this {@code ConfigValue}. If the value is a {@link ConfigObject} or + * {@link ConfigList}, it is recursively unwrapped. + * @return a plain Java value corresponding to this ConfigValue + */ + Object unwrapped(); + + /** + * Renders the config value as a HOCON string. This method is primarily + * intended for debugging, so it tries to add helpful comments and + * whitespace. + * + *

+ * If the config value has not been resolved (see {@link Config#resolve}), + * it's possible that it can't be rendered as valid HOCON. In that case the + * rendering should still be useful for debugging but you might not be able + * to parse it. If the value has been resolved, it will always be parseable. + * + *

+ * This method is equivalent to + * {@code render(ConfigRenderOptions.defaults())}. + * + * @return the rendered value + */ + String render(); + + /** + * Renders the config value to a string, using the provided options. + * + *

+ * If the config value has not been resolved (see {@link Config#resolve}), + * it's possible that it can't be rendered as valid HOCON. In that case the + * rendering should still be useful for debugging but you might not be able + * to parse it. If the value has been resolved, it will always be parseable. + * + *

+ * If the config value has been resolved and the options disable all + * HOCON-specific features (such as comments), the rendering will be valid + * JSON. If you enable HOCON-only features such as comments, the rendering + * will not be valid JSON. + * + * @param options + * the rendering options + * @return the rendered value + */ + String render(ConfigRenderOptions options); + + @Override + ConfigValue withFallback(ConfigMergeable other); + + /** + * Places the value inside a {@link Config} at the given path. See also + * {@link ConfigValue#atKey(String)}. + * + * @param path + * path to store this value at. + * @return a {@code Config} instance containing this value at the given + * path. + */ + Config atPath(String path); + + /** + * Places the value inside a {@link Config} at the given key. See also + * {@link ConfigValue#atPath(String)}. + * + * @param key + * key to store this value at. + * @return a {@code Config} instance containing this value at the given key. + */ + Config atKey(String key); + + /** + * Returns a {@code ConfigValue} based on this one, but with the given + * origin. This is useful when you are parsing a new format of file or setting + * comments for a single ConfigValue. + * + * @since 1.3.0 + * + * @param origin the origin set on the returned value + * @return the new ConfigValue with the given origin + */ + ConfigValue withOrigin(ConfigOrigin origin); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValueFactory.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValueFactory.java new file mode 100644 index 0000000..4f8d8ee --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValueFactory.java @@ -0,0 +1,153 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.util.Map; + +import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImpl; + +/** + * This class holds some static factory methods for building {@link ConfigValue} + * instances. See also {@link ConfigFactory} which has methods for parsing files + * and certain in-memory data structures. + */ +public final class ConfigValueFactory { + private ConfigValueFactory() { + } + + /** + * Creates a {@link ConfigValue} from a plain Java boxed value, which may be + * a Boolean, Number, String, + * Map, Iterable, or null. A + * Map must be a Map from String to more values + * that can be supplied to fromAnyRef(). An + * Iterable must iterate over more values that can be supplied + * to fromAnyRef(). A Map will become a + * {@link ConfigObject} and an Iterable will become a + * {@link ConfigList}. If the Iterable is not an ordered + * collection, results could be strange, since ConfigList is + * ordered. + * + *

+ * In a Map passed to fromAnyRef(), the map's keys + * are plain keys, not path expressions. So if your Map has a + * key "foo.bar" then you will get one object with a key called "foo.bar", + * rather than an object with a key "foo" containing another object with a + * key "bar". + * + *

+ * The originDescription will be used to set the origin() field on the + * ConfigValue. It should normally be the name of the file the values came + * from, or something short describing the value such as "default settings". + * The originDescription is prefixed to error messages so users can tell + * where problematic values are coming from. + * + *

+ * Supplying the result of ConfigValue.unwrapped() to this function is + * guaranteed to work and should give you back a ConfigValue that matches + * the one you unwrapped. The re-wrapped ConfigValue will lose some + * information that was present in the original such as its origin, but it + * will have matching values. + * + *

+ * If you pass in a ConfigValue to this + * function, it will be returned unmodified. (The + * originDescription will be ignored in this + * case.) + * + *

+ * This function throws if you supply a value that cannot be converted to a + * ConfigValue, but supplying such a value is a bug in your program, so you + * should never handle the exception. Just fix your program (or report a bug + * against this library). + * + * @param object + * object to convert to ConfigValue + * @param originDescription + * name of origin file or brief description of what the value is + * @return a new value + */ + public static ConfigValue fromAnyRef(Object object, String originDescription) { + return ConfigImpl.fromAnyRef(object, originDescription); + } + + /** + * See the {@link #fromAnyRef(Object,String)} documentation for details. + * This is a typesafe wrapper that only works on {@link java.util.Map} and + * returns {@link ConfigObject} rather than {@link ConfigValue}. + * + *

+ * If your Map has a key "foo.bar" then you will get one object + * with a key called "foo.bar", rather than an object with a key "foo" + * containing another object with a key "bar". The keys in the map are keys; + * not path expressions. That is, the Map corresponds exactly + * to a single {@code ConfigObject}. The keys will not be parsed or + * modified, and the values are wrapped in ConfigValue. To get nested + * {@code ConfigObject}, some of the values in the map would have to be more + * maps. + * + *

+ * See also {@link ConfigFactory#parseMap(Map,String)} which interprets the + * keys in the map as path expressions. + * + * @param values map from keys to plain Java values + * @param originDescription description to use in {@link ConfigOrigin} of created values + * @return a new {@link ConfigObject} value + */ + public static ConfigObject fromMap(Map values, + String originDescription) { + return (ConfigObject) fromAnyRef(values, originDescription); + } + + /** + * See the {@link #fromAnyRef(Object,String)} documentation for details. + * This is a typesafe wrapper that only works on {@link java.lang.Iterable} + * and returns {@link ConfigList} rather than {@link ConfigValue}. + * + * @param values list of plain Java values + * @param originDescription description to use in {@link ConfigOrigin} of created values + * @return a new {@link ConfigList} value + */ + public static ConfigList fromIterable(Iterable values, + String originDescription) { + return (ConfigList) fromAnyRef(values, originDescription); + } + + /** + * See the other overload {@link #fromAnyRef(Object,String)} for details, + * this one just uses a default origin description. + * + * @param object a plain Java value + * @return a new {@link ConfigValue} + */ + public static ConfigValue fromAnyRef(Object object) { + return fromAnyRef(object, null); + } + + /** + * See the other overload {@link #fromMap(Map,String)} for details, this one + * just uses a default origin description. + * + *

+ * See also {@link ConfigFactory#parseMap(Map)} which interprets the keys in + * the map as path expressions. + * + * @param values map from keys to plain Java values + * @return a new {@link ConfigObject} + */ + public static ConfigObject fromMap(Map values) { + return fromMap(values, null); + } + + /** + * See the other overload of {@link #fromIterable(Iterable, String)} for + * details, this one just uses a default origin description. + * + * @param values list of plain Java values + * @return a new {@link ConfigList} + */ + public static ConfigList fromIterable(Iterable values) { + return fromIterable(values, null); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValueType.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValueType.java new file mode 100644 index 0000000..1de6a1e --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/ConfigValueType.java @@ -0,0 +1,12 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config; + +/** + * The type of a configuration value (following the JSON type schema). + */ +public enum ConfigValueType { + OBJECT, LIST, NUMBER, BOOLEAN, NULL, STRING +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/DefaultConfigLoadingStrategy.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/DefaultConfigLoadingStrategy.java new file mode 100644 index 0000000..e46765e --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/DefaultConfigLoadingStrategy.java @@ -0,0 +1,62 @@ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; + +/** + * Default config loading strategy. Able to load resource, file or URL. + * Behavior may be altered by defining one of VM properties + * {@code config.resource}, {@code config.file} or {@code config.url} + */ +public class DefaultConfigLoadingStrategy implements ConfigLoadingStrategy { + @Override + public Config parseApplicationConfig(ConfigParseOptions parseOptions) { + ClassLoader loader = parseOptions.getClassLoader(); + if (loader == null) + throw new ConfigException.BugOrBroken( + "ClassLoader should have been set here; bug in ConfigFactory. " + + "(You can probably work around this bug by passing in a class loader or calling currentThread().setContextClassLoader() though.)"); + + int specified = 0; + + // override application.conf with config.file, config.resource, + // config.url if requested. + String resource = System.getProperty("config.resource"); + if (resource != null) + specified += 1; + String file = System.getProperty("config.file"); + if (file != null) + specified += 1; + String url = System.getProperty("config.url"); + if (url != null) + specified += 1; + + if (specified == 0) { + return ConfigFactory.parseResourcesAnySyntax("application", parseOptions); + } else if (specified > 1) { + throw new ConfigException.Generic("You set more than one of config.file='" + file + + "', config.url='" + url + "', config.resource='" + resource + + "'; don't know which one to use!"); + } else { + // the override file/url/resource MUST be present or it's an error + ConfigParseOptions overrideOptions = parseOptions.setAllowMissing(false); + if (resource != null) { + if (resource.startsWith("/")) + resource = resource.substring(1); + // this deliberately does not parseResourcesAnySyntax; if + // people want that they can use an include statement. + return ConfigFactory.parseResources(loader, resource, overrideOptions); + } else if (file != null) { + return ConfigFactory.parseFile(new File(file), overrideOptions); + } else { + try { + return ConfigFactory.parseURL(new URL(url), overrideOptions); + } catch (MalformedURLException e) { + throw new ConfigException.Generic("Bad URL in config.url system property: '" + + url + "': " + e.getMessage(), e); + } + } + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/Optional.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/Optional.java new file mode 100644 index 0000000..9223525 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/Optional.java @@ -0,0 +1,14 @@ +package com.drtshock.playervaults.lib.com.typesafe.config; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Allows an config property to be {@code null}. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +public @interface Optional { + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigNode.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigNode.java new file mode 100644 index 0000000..1de6857 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigNode.java @@ -0,0 +1,29 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.parser.ConfigNode; +import java.util.Collection; + +abstract class AbstractConfigNode implements ConfigNode { + abstract Collection tokens(); + final public String render() { + StringBuilder origText = new StringBuilder(); + Iterable tokens = tokens(); + for (Token t : tokens) { + origText.append(t.tokenText()); + } + return origText.toString(); + } + + @Override + final public boolean equals(Object other) { + return other instanceof AbstractConfigNode && render().equals(((AbstractConfigNode)other).render()); + } + + @Override + final public int hashCode() { + return render().hashCode(); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigNodeValue.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigNodeValue.java new file mode 100644 index 0000000..81d1cf1 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigNodeValue.java @@ -0,0 +1,11 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +// This is required if we want +// to be referencing the AbstractConfigNode class in implementation rather than the +// ConfigNode interface, as we can't cast an AbstractConfigNode to an interface +abstract class AbstractConfigNodeValue extends AbstractConfigNode { + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigObject.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigObject.java new file mode 100644 index 0000000..948f2b6 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigObject.java @@ -0,0 +1,221 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +abstract class AbstractConfigObject extends AbstractConfigValue implements ConfigObject, Container { + final private SimpleConfig config; + + protected AbstractConfigObject(ConfigOrigin origin) { + super(origin); + this.config = new SimpleConfig(this); + } + + @Override + public SimpleConfig toConfig() { + return config; + } + + @Override + public AbstractConfigObject toFallbackValue() { + return this; + } + + @Override + abstract public AbstractConfigObject withOnlyKey(String key); + + @Override + abstract public AbstractConfigObject withoutKey(String key); + + @Override + abstract public AbstractConfigObject withValue(String key, ConfigValue value); + + abstract protected AbstractConfigObject withOnlyPathOrNull(Path path); + + abstract AbstractConfigObject withOnlyPath(Path path); + + abstract AbstractConfigObject withoutPath(Path path); + + abstract AbstractConfigObject withValue(Path path, ConfigValue value); + + /** + * This looks up the key with no transformation or type conversion of any + * kind, and returns null if the key is not present. The object must be + * resolved along the nodes needed to get the key or + * ConfigException.NotResolved will be thrown. + * + * @param key + * @return the unmodified raw value or null + */ + protected final AbstractConfigValue peekAssumingResolved(String key, Path originalPath) { + try { + return attemptPeekWithPartialResolve(key); + } catch (ConfigException.NotResolved e) { + throw ConfigImpl.improveNotResolved(originalPath, e); + } + } + + /** + * Look up the key on an only-partially-resolved object, with no + * transformation or type conversion of any kind; if 'this' is not resolved + * then try to look up the key anyway if possible. + * + * @param key + * key to look up + * @return the value of the key, or null if known not to exist + * @throws ConfigException.NotResolved + * if can't figure out key's value (or existence) without more + * resolving + */ + abstract AbstractConfigValue attemptPeekWithPartialResolve(String key); + + /** + * Looks up the path with no transformation or type conversion. Returns null + * if the path is not found; throws ConfigException.NotResolved if we need + * to go through an unresolved node to look up the path. + */ + protected AbstractConfigValue peekPath(Path path) { + return peekPath(this, path); + } + + private static AbstractConfigValue peekPath(AbstractConfigObject self, Path path) { + try { + // we'll fail if anything along the path can't + // be looked at without resolving. + Path next = path.remainder(); + AbstractConfigValue v = self.attemptPeekWithPartialResolve(path.first()); + + if (next == null) { + return v; + } else { + if (v instanceof AbstractConfigObject) { + return peekPath((AbstractConfigObject) v, next); + } else { + return null; + } + } + } catch (ConfigException.NotResolved e) { + throw ConfigImpl.improveNotResolved(path, e); + } + } + + @Override + public ConfigValueType valueType() { + return ConfigValueType.OBJECT; + } + + protected abstract AbstractConfigObject newCopy(ResolveStatus status, ConfigOrigin origin); + + @Override + protected AbstractConfigObject newCopy(ConfigOrigin origin) { + return newCopy(resolveStatus(), origin); + } + + @Override + protected AbstractConfigObject constructDelayedMerge(ConfigOrigin origin, + List stack) { + return new ConfigDelayedMergeObject(origin, stack); + } + + @Override + protected abstract AbstractConfigObject mergedWithObject(AbstractConfigObject fallback); + + @Override + public AbstractConfigObject withFallback(ConfigMergeable mergeable) { + return (AbstractConfigObject) super.withFallback(mergeable); + } + + static ConfigOrigin mergeOrigins( + Collection stack) { + if (stack.isEmpty()) + throw new ConfigException.BugOrBroken( + "can't merge origins on empty list"); + List origins = new ArrayList(); + ConfigOrigin firstOrigin = null; + int numMerged = 0; + for (AbstractConfigValue v : stack) { + if (firstOrigin == null) + firstOrigin = v.origin(); + + if (v instanceof AbstractConfigObject + && ((AbstractConfigObject) v).resolveStatus() == ResolveStatus.RESOLVED + && ((ConfigObject) v).isEmpty()) { + // don't include empty files or the .empty() + // config in the description, since they are + // likely to be "implementation details" + } else { + origins.add(v.origin()); + numMerged += 1; + } + } + + if (numMerged == 0) { + // the configs were all empty, so just use the first one + origins.add(firstOrigin); + } + + return SimpleConfigOrigin.mergeOrigins(origins); + } + + static ConfigOrigin mergeOrigins(AbstractConfigObject... stack) { + return mergeOrigins(Arrays.asList(stack)); + } + + @Override + abstract ResolveResult resolveSubstitutions(ResolveContext context, + ResolveSource source) + throws NotPossibleToResolve; + + @Override + abstract AbstractConfigObject relativized(final Path prefix); + + @Override + public abstract AbstractConfigValue get(Object key); + + @Override + protected abstract void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options); + + private static UnsupportedOperationException weAreImmutable(String method) { + return new UnsupportedOperationException("ConfigObject is immutable, you can't call Map." + + method); + } + + @Override + public void clear() { + throw weAreImmutable("clear"); + } + + @Override + public ConfigValue put(String arg0, ConfigValue arg1) { + throw weAreImmutable("put"); + } + + @Override + public void putAll(Map arg0) { + throw weAreImmutable("putAll"); + } + + @Override + public ConfigValue remove(Object arg0) { + throw weAreImmutable("remove"); + } + + @Override + public AbstractConfigObject withOrigin(ConfigOrigin origin) { + return (AbstractConfigObject) super.withOrigin(origin); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigValue.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigValue.java new file mode 100644 index 0000000..a63f50d --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/AbstractConfigValue.java @@ -0,0 +1,411 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; + +/** + * + * Trying very hard to avoid a parent reference in config values; when you have + * a tree like this, the availability of parent() tends to result in a lot of + * improperly-factored and non-modular code. Please don't add parent(). + * + */ +abstract class AbstractConfigValue implements ConfigValue, MergeableValue { + + final private SimpleConfigOrigin origin; + + AbstractConfigValue(ConfigOrigin origin) { + this.origin = (SimpleConfigOrigin) origin; + } + + @Override + public SimpleConfigOrigin origin() { + return this.origin; + } + + /** + * This exception means that a value is inherently not resolveable, at the + * moment the only known cause is a cycle of substitutions. This is a + * checked exception since it's internal to the library and we want to be + * sure we handle it before passing it out to public API. This is only + * supposed to be thrown by the target of a cyclic reference and it's + * supposed to be caught by the ConfigReference looking up that reference, + * so it should be impossible for an outermost resolve() to throw this. + * + * Contrast with ConfigException.NotResolved which just means nobody called + * resolve(). + */ + static class NotPossibleToResolve extends Exception { + private static final long serialVersionUID = 1L; + + final private String traceString; + + NotPossibleToResolve(ResolveContext context) { + super("was not possible to resolve"); + this.traceString = context.traceString(); + } + + String traceString() { + return traceString; + } + } + + /** + * Called only by ResolveContext.resolve(). + * + * @param context + * state of the current resolve + * @param source + * where to look up values + * @return a new value if there were changes, or this if no changes + */ + ResolveResult resolveSubstitutions(ResolveContext context, ResolveSource source) + throws NotPossibleToResolve { + return ResolveResult.make(context, this); + } + + ResolveStatus resolveStatus() { + return ResolveStatus.RESOLVED; + } + + protected static List replaceChildInList(List list, + AbstractConfigValue child, AbstractConfigValue replacement) { + int i = 0; + while (i < list.size() && list.get(i) != child) + ++i; + if (i == list.size()) + throw new ConfigException.BugOrBroken("tried to replace " + child + " which is not in " + list); + List newStack = new ArrayList(list); + if (replacement != null) + newStack.set(i, replacement); + else + newStack.remove(i); + + if (newStack.isEmpty()) + return null; + else + return newStack; + } + + protected static boolean hasDescendantInList(List list, AbstractConfigValue descendant) { + for (AbstractConfigValue v : list) { + if (v == descendant) + return true; + } + // now the expensive traversal + for (AbstractConfigValue v : list) { + if (v instanceof Container && ((Container) v).hasDescendant(descendant)) + return true; + } + return false; + } + + /** + * This is used when including one file in another; the included file is + * relativized to the path it's included into in the parent file. The point + * is that if you include a file at foo.bar in the parent, and the included + * file as a substitution ${a.b.c}, the included substitution now needs to + * be ${foo.bar.a.b.c} because we resolve substitutions globally only after + * parsing everything. + * + * @param prefix + * @return value relativized to the given path or the same value if nothing + * to do + */ + AbstractConfigValue relativized(Path prefix) { + return this; + } + + protected interface Modifier { + // keyOrNull is null for non-objects + AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v) + throws Exception; + } + + protected abstract class NoExceptionsModifier implements Modifier { + @Override + public final AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v) + throws Exception { + try { + return modifyChild(keyOrNull, v); + } catch (RuntimeException e) { + throw e; + } catch(Exception e) { + throw new ConfigException.BugOrBroken("Unexpected exception", e); + } + } + + abstract AbstractConfigValue modifyChild(String keyOrNull, AbstractConfigValue v); + } + + @Override + public AbstractConfigValue toFallbackValue() { + return this; + } + + protected abstract AbstractConfigValue newCopy(ConfigOrigin origin); + + // this is virtualized rather than a field because only some subclasses + // really need to store the boolean, and they may be able to pack it + // with another boolean to save space. + protected boolean ignoresFallbacks() { + // if we are not resolved, then somewhere in this value there's + // a substitution that may need to look at the fallbacks. + return resolveStatus() == ResolveStatus.RESOLVED; + } + + protected AbstractConfigValue withFallbacksIgnored() { + if (ignoresFallbacks()) + return this; + else + throw new ConfigException.BugOrBroken( + "value class doesn't implement forced fallback-ignoring " + this); + } + + // the withFallback() implementation is supposed to avoid calling + // mergedWith* if we're ignoring fallbacks. + protected final void requireNotIgnoringFallbacks() { + if (ignoresFallbacks()) + throw new ConfigException.BugOrBroken( + "method should not have been called with ignoresFallbacks=true " + + getClass().getSimpleName()); + } + + protected AbstractConfigValue constructDelayedMerge(ConfigOrigin origin, + List stack) { + return new ConfigDelayedMerge(origin, stack); + } + + protected final AbstractConfigValue mergedWithTheUnmergeable( + Collection stack, Unmergeable fallback) { + requireNotIgnoringFallbacks(); + + // if we turn out to be an object, and the fallback also does, + // then a merge may be required; delay until we resolve. + List newStack = new ArrayList(); + newStack.addAll(stack); + newStack.addAll(fallback.unmergedValues()); + return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack); + } + + private final AbstractConfigValue delayMerge(Collection stack, + AbstractConfigValue fallback) { + // if we turn out to be an object, and the fallback also does, + // then a merge may be required. + // if we contain a substitution, resolving it may need to look + // back to the fallback. + List newStack = new ArrayList(); + newStack.addAll(stack); + newStack.add(fallback); + return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack); + } + + protected final AbstractConfigValue mergedWithObject(Collection stack, + AbstractConfigObject fallback) { + requireNotIgnoringFallbacks(); + + if (this instanceof AbstractConfigObject) + throw new ConfigException.BugOrBroken("Objects must reimplement mergedWithObject"); + + return mergedWithNonObject(stack, fallback); + } + + protected final AbstractConfigValue mergedWithNonObject(Collection stack, + AbstractConfigValue fallback) { + requireNotIgnoringFallbacks(); + + if (resolveStatus() == ResolveStatus.RESOLVED) { + // falling back to a non-object doesn't merge anything, and also + // prohibits merging any objects that we fall back to later. + // so we have to switch to ignoresFallbacks mode. + return withFallbacksIgnored(); + } else { + // if unresolved, we may have to look back to fallbacks as part of + // the resolution process, so always delay + return delayMerge(stack, fallback); + } + } + + protected AbstractConfigValue mergedWithTheUnmergeable(Unmergeable fallback) { + requireNotIgnoringFallbacks(); + + return mergedWithTheUnmergeable(Collections.singletonList(this), fallback); + } + + protected AbstractConfigValue mergedWithObject(AbstractConfigObject fallback) { + requireNotIgnoringFallbacks(); + + return mergedWithObject(Collections.singletonList(this), fallback); + } + + protected AbstractConfigValue mergedWithNonObject(AbstractConfigValue fallback) { + requireNotIgnoringFallbacks(); + + return mergedWithNonObject(Collections.singletonList(this), fallback); + } + + @Override + public AbstractConfigValue withOrigin(ConfigOrigin origin) { + if (this.origin == origin) + return this; + else + return newCopy(origin); + } + + // this is only overridden to change the return type + @Override + public AbstractConfigValue withFallback(ConfigMergeable mergeable) { + if (ignoresFallbacks()) { + return this; + } else { + ConfigValue other = ((MergeableValue) mergeable).toFallbackValue(); + + if (other instanceof Unmergeable) { + return mergedWithTheUnmergeable((Unmergeable) other); + } else if (other instanceof AbstractConfigObject) { + return mergedWithObject((AbstractConfigObject) other); + } else { + return mergedWithNonObject((AbstractConfigValue) other); + } + } + } + + protected boolean canEqual(Object other) { + return other instanceof ConfigValue; + } + + @Override + public boolean equals(Object other) { + // note that "origin" is deliberately NOT part of equality + if (other instanceof ConfigValue) { + return canEqual(other) + && (this.valueType() == + ((ConfigValue) other).valueType()) + && ConfigImplUtil.equalsHandlingNull(this.unwrapped(), + ((ConfigValue) other).unwrapped()); + } else { + return false; + } + } + + @Override + public int hashCode() { + // note that "origin" is deliberately NOT part of equality + Object o = this.unwrapped(); + if (o == null) + return 0; + else + return o.hashCode(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + render(sb, 0, true /* atRoot */, null /* atKey */, ConfigRenderOptions.concise()); + return getClass().getSimpleName() + "(" + sb.toString() + ")"; + } + + protected static void indent(StringBuilder sb, int indent, ConfigRenderOptions options) { + if (options.getFormatted()) { + int remaining = indent; + while (remaining > 0) { + sb.append(" "); + --remaining; + } + } + } + + protected void render(StringBuilder sb, int indent, boolean atRoot, String atKey, ConfigRenderOptions options) { + if (atKey != null) { + String renderedKey; + if (options.getJson()) + renderedKey = ConfigImplUtil.renderJsonString(atKey); + else + renderedKey = ConfigImplUtil.renderStringUnquotedIfPossible(atKey); + + sb.append(renderedKey); + + if (options.getJson()) { + if (options.getFormatted()) + sb.append(" : "); + else + sb.append(":"); + } else { + // in non-JSON we can omit the colon or equals before an object + if (this instanceof ConfigObject) { + if (options.getFormatted()) + sb.append(' '); + } else { + sb.append("="); + } + } + } + render(sb, indent, atRoot, options); + } + + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + Object u = unwrapped(); + sb.append(u.toString()); + } + + @Override + public final String render() { + return render(ConfigRenderOptions.defaults()); + } + + @Override + public final String render(ConfigRenderOptions options) { + StringBuilder sb = new StringBuilder(); + render(sb, 0, true, null, options); + return sb.toString(); + } + + // toString() is a debugging-oriented string but this is defined + // to create a string that would parse back to the value in JSON. + // It only works for primitive values (that would be a single token) + // which are auto-converted to strings when concatenating with + // other strings or by the DefaultTransformer. + String transformToString() { + return null; + } + + SimpleConfig atKey(ConfigOrigin origin, String key) { + Map m = Collections.singletonMap(key, this); + return (new SimpleConfigObject(origin, m)).toConfig(); + } + + @Override + public SimpleConfig atKey(String key) { + return atKey(SimpleConfigOrigin.newSimple("atKey(" + key + ")"), key); + } + + SimpleConfig atPath(ConfigOrigin origin, Path path) { + Path parent = path.parent(); + SimpleConfig result = atKey(origin, path.last()); + while (parent != null) { + String key = parent.last(); + result = result.atKey(origin, key); + parent = parent.parent(); + } + return result; + } + + @Override + public SimpleConfig atPath(String pathExpression) { + SimpleConfigOrigin origin = SimpleConfigOrigin.newSimple("atPath(" + pathExpression + ")"); + return atPath(origin, Path.newPath(pathExpression)); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigBeanImpl.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigBeanImpl.java new file mode 100644 index 0000000..3a8c353 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigBeanImpl.java @@ -0,0 +1,305 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.time.Duration; +import java.util.Set; + +import com.drtshock.playervaults.lib.com.typesafe.config.Config; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigList; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMemorySize; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; +import com.drtshock.playervaults.lib.com.typesafe.config.Optional; + +/** + * Internal implementation detail, not ABI stable, do not touch. + * For use only by the {@link com.typesafe.config} package. + */ +public class ConfigBeanImpl { + + /** + * This is public ONLY for use by the "config" package, DO NOT USE this ABI + * may change. + * @param type of the bean + * @param config config to use + * @param clazz class of the bean + * @return the bean instance + */ + public static T createInternal(Config config, Class clazz) { + if (((SimpleConfig)config).root().resolveStatus() != ResolveStatus.RESOLVED) + throw new ConfigException.NotResolved( + "need to Config#resolve() a config before using it to initialize a bean, see the API docs for Config#resolve()"); + + Map configProps = new HashMap(); + Map originalNames = new HashMap(); + for (Map.Entry configProp : config.root().entrySet()) { + String originalName = configProp.getKey(); + String camelName = ConfigImplUtil.toCamelCase(originalName); + // if a setting is in there both as some hyphen name and the camel name, + // the camel one wins + if (originalNames.containsKey(camelName) && !originalName.equals(camelName)) { + // if we aren't a camel name to start with, we lose. + // if we are or we are the first matching key, we win. + } else { + configProps.put(camelName, (AbstractConfigValue) configProp.getValue()); + originalNames.put(camelName, originalName); + } + } + + BeanInfo beanInfo = null; + try { + beanInfo = Introspector.getBeanInfo(clazz); + } catch (IntrospectionException e) { + throw new ConfigException.BadBean("Could not get bean information for class " + clazz.getName(), e); + } + + try { + List beanProps = new ArrayList(); + for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) { + if (beanProp.getReadMethod() == null || beanProp.getWriteMethod() == null) { + continue; + } + beanProps.add(beanProp); + } + + // Try to throw all validation issues at once (this does not comprehensively + // find every issue, but it should find common ones). + List problems = new ArrayList(); + for (PropertyDescriptor beanProp : beanProps) { + Method setter = beanProp.getWriteMethod(); + Class parameterClass = setter.getParameterTypes()[0]; + + ConfigValueType expectedType = getValueTypeOrNull(parameterClass); + if (expectedType != null) { + String name = originalNames.get(beanProp.getName()); + if (name == null) + name = beanProp.getName(); + Path path = Path.newKey(name); + AbstractConfigValue configValue = configProps.get(beanProp.getName()); + if (configValue != null) { + SimpleConfig.checkValid(path, expectedType, configValue, problems); + } else { + if (!isOptionalProperty(clazz, beanProp)) { + SimpleConfig.addMissing(problems, expectedType, path, config.origin()); + } + } + } + } + + if (!problems.isEmpty()) { + throw new ConfigException.ValidationFailed(problems); + } + + // Fill in the bean instance + T bean = clazz.newInstance(); + for (PropertyDescriptor beanProp : beanProps) { + Method setter = beanProp.getWriteMethod(); + Type parameterType = setter.getGenericParameterTypes()[0]; + Class parameterClass = setter.getParameterTypes()[0]; + String configPropName = originalNames.get(beanProp.getName()); + // Is the property key missing in the config? + if (configPropName == null) { + // If so, continue if the field is marked as @{link Optional} + if (isOptionalProperty(clazz, beanProp)) { + continue; + } + // Otherwise, raise a {@link Missing} exception right here + throw new ConfigException.Missing(beanProp.getName()); + } + Object unwrapped = getValue(clazz, parameterType, parameterClass, config, configPropName); + setter.invoke(bean, unwrapped); + } + return bean; + } catch (InstantiationException e) { + throw new ConfigException.BadBean(clazz.getName() + " needs a public no-args constructor to be used as a bean", e); + } catch (IllegalAccessException e) { + throw new ConfigException.BadBean(clazz.getName() + " getters and setters are not accessible, they must be for use as a bean", e); + } catch (InvocationTargetException e) { + throw new ConfigException.BadBean("Calling bean method on " + clazz.getName() + " caused an exception", e); + } + } + + // we could magically make this work in many cases by doing + // getAnyRef() (or getValue().unwrapped()), but anytime we + // rely on that, we aren't doing the type conversions Config + // usually does, and we will throw ClassCastException instead + // of a nicer error message giving the name of the bad + // setting. So, instead, we only support a limited number of + // types plus you can always use Object, ConfigValue, Config, + // ConfigObject, etc. as an escape hatch. + private static Object getValue(Class beanClass, Type parameterType, Class parameterClass, Config config, + String configPropName) { + if (parameterClass == Boolean.class || parameterClass == boolean.class) { + return config.getBoolean(configPropName); + } else if (parameterClass == Integer.class || parameterClass == int.class) { + return config.getInt(configPropName); + } else if (parameterClass == Double.class || parameterClass == double.class) { + return config.getDouble(configPropName); + } else if (parameterClass == Long.class || parameterClass == long.class) { + return config.getLong(configPropName); + } else if (parameterClass == String.class) { + return config.getString(configPropName); + } else if (parameterClass == Duration.class) { + return config.getDuration(configPropName); + } else if (parameterClass == ConfigMemorySize.class) { + return config.getMemorySize(configPropName); + } else if (parameterClass == Object.class) { + return config.getAnyRef(configPropName); + } else if (parameterClass == List.class) { + return getListValue(beanClass, parameterType, parameterClass, config, configPropName); + } else if (parameterClass == Set.class) { + return getSetValue(beanClass, parameterType, parameterClass, config, configPropName); + } else if (parameterClass == Map.class) { + // we could do better here, but right now we don't. + Type[] typeArgs = ((ParameterizedType)parameterType).getActualTypeArguments(); + if (typeArgs[0] != String.class || typeArgs[1] != Object.class) { + throw new ConfigException.BadBean("Bean property '" + configPropName + "' of class " + beanClass.getName() + " has unsupported Map<" + typeArgs[0] + "," + typeArgs[1] + ">, only Map is supported right now"); + } + return config.getObject(configPropName).unwrapped(); + } else if (parameterClass == Config.class) { + return config.getConfig(configPropName); + } else if (parameterClass == ConfigObject.class) { + return config.getObject(configPropName); + } else if (parameterClass == ConfigValue.class) { + return config.getValue(configPropName); + } else if (parameterClass == ConfigList.class) { + return config.getList(configPropName); + } else if (parameterClass.isEnum()) { + @SuppressWarnings("unchecked") + Enum enumValue = config.getEnum((Class) parameterClass, configPropName); + return enumValue; + } else if (hasAtLeastOneBeanProperty(parameterClass)) { + return createInternal(config.getConfig(configPropName), parameterClass); + } else { + throw new ConfigException.BadBean("Bean property " + configPropName + " of class " + beanClass.getName() + " has unsupported type " + parameterType); + } + } + + private static Object getSetValue(Class beanClass, Type parameterType, Class parameterClass, Config config, String configPropName) { + return new HashSet((List) getListValue(beanClass, parameterType, parameterClass, config, configPropName)); + } + + private static Object getListValue(Class beanClass, Type parameterType, Class parameterClass, Config config, String configPropName) { + Type elementType = ((ParameterizedType)parameterType).getActualTypeArguments()[0]; + + if (elementType == Boolean.class) { + return config.getBooleanList(configPropName); + } else if (elementType == Integer.class) { + return config.getIntList(configPropName); + } else if (elementType == Double.class) { + return config.getDoubleList(configPropName); + } else if (elementType == Long.class) { + return config.getLongList(configPropName); + } else if (elementType == String.class) { + return config.getStringList(configPropName); + } else if (elementType == Duration.class) { + return config.getDurationList(configPropName); + } else if (elementType == ConfigMemorySize.class) { + return config.getMemorySizeList(configPropName); + } else if (elementType == Object.class) { + return config.getAnyRefList(configPropName); + } else if (elementType == Config.class) { + return config.getConfigList(configPropName); + } else if (elementType == ConfigObject.class) { + return config.getObjectList(configPropName); + } else if (elementType == ConfigValue.class) { + return config.getList(configPropName); + } else if (((Class) elementType).isEnum()) { + @SuppressWarnings("unchecked") + List enumValues = config.getEnumList((Class) elementType, configPropName); + return enumValues; + } else if (hasAtLeastOneBeanProperty((Class) elementType)) { + List beanList = new ArrayList(); + List configList = config.getConfigList(configPropName); + for (Config listMember : configList) { + beanList.add(createInternal(listMember, (Class) elementType)); + } + return beanList; + } else { + throw new ConfigException.BadBean("Bean property '" + configPropName + "' of class " + beanClass.getName() + " has unsupported list element type " + elementType); + } + } + + // null if we can't easily say; this is heuristic/best-effort + private static ConfigValueType getValueTypeOrNull(Class parameterClass) { + if (parameterClass == Boolean.class || parameterClass == boolean.class) { + return ConfigValueType.BOOLEAN; + } else if (parameterClass == Integer.class || parameterClass == int.class) { + return ConfigValueType.NUMBER; + } else if (parameterClass == Double.class || parameterClass == double.class) { + return ConfigValueType.NUMBER; + } else if (parameterClass == Long.class || parameterClass == long.class) { + return ConfigValueType.NUMBER; + } else if (parameterClass == String.class) { + return ConfigValueType.STRING; + } else if (parameterClass == Duration.class) { + return null; + } else if (parameterClass == ConfigMemorySize.class) { + return null; + } else if (parameterClass == List.class) { + return ConfigValueType.LIST; + } else if (parameterClass == Map.class) { + return ConfigValueType.OBJECT; + } else if (parameterClass == Config.class) { + return ConfigValueType.OBJECT; + } else if (parameterClass == ConfigObject.class) { + return ConfigValueType.OBJECT; + } else if (parameterClass == ConfigList.class) { + return ConfigValueType.LIST; + } else { + return null; + } + } + + private static boolean hasAtLeastOneBeanProperty(Class clazz) { + BeanInfo beanInfo = null; + try { + beanInfo = Introspector.getBeanInfo(clazz); + } catch (IntrospectionException e) { + return false; + } + + for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) { + if (beanProp.getReadMethod() != null && beanProp.getWriteMethod() != null) { + return true; + } + } + + return false; + } + + private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { + Field field = getField(beanClass, beanProp.getName()); + return field != null && (field.getAnnotationsByType(Optional.class).length > 0); + } + + private static Field getField(Class beanClass, String fieldName) { + try { + Field field = beanClass.getDeclaredField(fieldName); + field.setAccessible(true); + return field; + } catch (NoSuchFieldException e) { + // Don't give up yet. Try to look for field in super class, if any. + } + beanClass = beanClass.getSuperclass(); + if (beanClass == null) { + return null; + } + return getField(beanClass, fieldName); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigBoolean.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigBoolean.java new file mode 100644 index 0000000..b121f45 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigBoolean.java @@ -0,0 +1,47 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +final class ConfigBoolean extends AbstractConfigValue implements Serializable { + + private static final long serialVersionUID = 2L; + + final private boolean value; + + ConfigBoolean(ConfigOrigin origin, boolean value) { + super(origin); + this.value = value; + } + + @Override + public ConfigValueType valueType() { + return ConfigValueType.BOOLEAN; + } + + @Override + public Boolean unwrapped() { + return value; + } + + @Override + String transformToString() { + return value ? "true" : "false"; + } + + @Override + protected ConfigBoolean newCopy(ConfigOrigin origin) { + return new ConfigBoolean(origin, value); + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigConcatenation.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigConcatenation.java new file mode 100644 index 0000000..82c4785 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigConcatenation.java @@ -0,0 +1,293 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +/** + * A ConfigConcatenation represents a list of values to be concatenated (see the + * spec). It only has to exist if at least one value is an unresolved + * substitution, otherwise we could go ahead and collapse the list into a single + * value. + * + * Right now this is always a list of strings and ${} references, but in the + * future should support a list of ConfigList. We may also support + * concatenations of objects, but ConfigDelayedMerge should be used for that + * since a concat of objects really will merge, not concatenate. + */ +final class ConfigConcatenation extends AbstractConfigValue implements Unmergeable, Container { + + final private List pieces; + + ConfigConcatenation(ConfigOrigin origin, List pieces) { + super(origin); + this.pieces = pieces; + + if (pieces.size() < 2) + throw new ConfigException.BugOrBroken("Created concatenation with less than 2 items: " + + this); + + boolean hadUnmergeable = false; + for (AbstractConfigValue p : pieces) { + if (p instanceof ConfigConcatenation) + throw new ConfigException.BugOrBroken( + "ConfigConcatenation should never be nested: " + this); + if (p instanceof Unmergeable) + hadUnmergeable = true; + } + if (!hadUnmergeable) + throw new ConfigException.BugOrBroken( + "Created concatenation without an unmergeable in it: " + this); + } + + private ConfigException.NotResolved notResolved() { + return new ConfigException.NotResolved( + "need to Config#resolve(), see the API docs for Config#resolve(); substitution not resolved: " + + this); + } + + @Override + public ConfigValueType valueType() { + throw notResolved(); + } + + @Override + public Object unwrapped() { + throw notResolved(); + } + + @Override + protected ConfigConcatenation newCopy(ConfigOrigin newOrigin) { + return new ConfigConcatenation(newOrigin, pieces); + } + + @Override + protected boolean ignoresFallbacks() { + // we can never ignore fallbacks because if a child ConfigReference + // is self-referential we have to look lower in the merge stack + // for its value. + return false; + } + + @Override + public Collection unmergedValues() { + return Collections.singleton(this); + } + + private static boolean isIgnoredWhitespace(AbstractConfigValue value) { + return (value instanceof ConfigString) && !((ConfigString)value).wasQuoted(); + } + + /** + * Add left and right, or their merger, to builder. + */ + private static void join(ArrayList builder, AbstractConfigValue origRight) { + AbstractConfigValue left = builder.get(builder.size() - 1); + AbstractConfigValue right = origRight; + + // check for an object which can be converted to a list + // (this will be an object with numeric keys, like foo.0, foo.1) + if (left instanceof ConfigObject && right instanceof SimpleConfigList) { + left = DefaultTransformer.transform(left, ConfigValueType.LIST); + } else if (left instanceof SimpleConfigList && right instanceof ConfigObject) { + right = DefaultTransformer.transform(right, ConfigValueType.LIST); + } + + // Since this depends on the type of two instances, I couldn't think + // of much alternative to an instanceof chain. Visitors are sometimes + // used for multiple dispatch but seems like overkill. + AbstractConfigValue joined = null; + if (left instanceof ConfigObject && right instanceof ConfigObject) { + joined = right.withFallback(left); + } else if (left instanceof SimpleConfigList && right instanceof SimpleConfigList) { + joined = ((SimpleConfigList)left).concatenate((SimpleConfigList)right); + } else if ((left instanceof SimpleConfigList || left instanceof ConfigObject) && + isIgnoredWhitespace(right)) { + joined = left; + // it should be impossible that left is whitespace and right is a list or object + } else if (left instanceof ConfigConcatenation || right instanceof ConfigConcatenation) { + throw new ConfigException.BugOrBroken("unflattened ConfigConcatenation"); + } else if (left instanceof Unmergeable || right instanceof Unmergeable) { + // leave joined=null, cannot join + } else { + // handle primitive type or primitive type mixed with object or list + String s1 = left.transformToString(); + String s2 = right.transformToString(); + if (s1 == null || s2 == null) { + throw new ConfigException.WrongType(left.origin(), + "Cannot concatenate object or list with a non-object-or-list, " + left + + " and " + right + " are not compatible"); + } else { + ConfigOrigin joinedOrigin = SimpleConfigOrigin.mergeOrigins(left.origin(), + right.origin()); + joined = new ConfigString.Quoted(joinedOrigin, s1 + s2); + } + } + + if (joined == null) { + builder.add(right); + } else { + builder.remove(builder.size() - 1); + builder.add(joined); + } + } + + static List consolidate(List pieces) { + if (pieces.size() < 2) { + return pieces; + } else { + List flattened = new ArrayList(pieces.size()); + for (AbstractConfigValue v : pieces) { + if (v instanceof ConfigConcatenation) { + flattened.addAll(((ConfigConcatenation) v).pieces); + } else { + flattened.add(v); + } + } + + ArrayList consolidated = new ArrayList( + flattened.size()); + for (AbstractConfigValue v : flattened) { + if (consolidated.isEmpty()) + consolidated.add(v); + else + join(consolidated, v); + } + + return consolidated; + } + } + + static AbstractConfigValue concatenate(List pieces) { + List consolidated = consolidate(pieces); + if (consolidated.isEmpty()) { + return null; + } else if (consolidated.size() == 1) { + return consolidated.get(0); + } else { + ConfigOrigin mergedOrigin = SimpleConfigOrigin.mergeOrigins(consolidated); + return new ConfigConcatenation(mergedOrigin, consolidated); + } + } + + @Override + ResolveResult resolveSubstitutions(ResolveContext context, ResolveSource source) + throws NotPossibleToResolve { + if (ConfigImpl.traceSubstitutionsEnabled()) { + int indent = context.depth() + 2; + ConfigImpl.trace(indent - 1, "concatenation has " + pieces.size() + " pieces:"); + int count = 0; + for (AbstractConfigValue v : pieces) { + ConfigImpl.trace(indent, count + ": " + v); + count += 1; + } + } + + // Right now there's no reason to pushParent here because the + // content of ConfigConcatenation should not need to replaceChild, + // but if it did we'd have to do this. + ResolveSource sourceWithParent = source; // .pushParent(this); + ResolveContext newContext = context; + + List resolved = new ArrayList(pieces.size()); + for (AbstractConfigValue p : pieces) { + // to concat into a string we have to do a full resolve, + // so unrestrict the context, then put restriction back afterward + Path restriction = newContext.restrictToChild(); + ResolveResult result = newContext.unrestricted() + .resolve(p, sourceWithParent); + AbstractConfigValue r = result.value; + newContext = result.context.restrict(restriction); + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(context.depth(), "resolved concat piece to " + r); + if (r == null) { + // it was optional... omit + } else { + resolved.add(r); + } + } + + // now need to concat everything + List joined = consolidate(resolved); + // if unresolved is allowed we can just become another + // ConfigConcatenation + if (joined.size() > 1 && context.options().getAllowUnresolved()) + return ResolveResult.make(newContext, new ConfigConcatenation(this.origin(), joined)); + else if (joined.isEmpty()) + // we had just a list of optional references using ${?} + return ResolveResult.make(newContext, null); + else if (joined.size() == 1) + return ResolveResult.make(newContext, joined.get(0)); + else + throw new ConfigException.BugOrBroken("Bug in the library; resolved list was joined to too many values: " + + joined); + } + + @Override + ResolveStatus resolveStatus() { + return ResolveStatus.UNRESOLVED; + } + + @Override + public ConfigConcatenation replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) { + List newPieces = replaceChildInList(pieces, child, replacement); + if (newPieces == null) + return null; + else + return new ConfigConcatenation(origin(), newPieces); + } + + @Override + public boolean hasDescendant(AbstractConfigValue descendant) { + return hasDescendantInList(pieces, descendant); + } + + // when you graft a substitution into another object, + // you have to prefix it with the location in that object + // where you grafted it; but save prefixLength so + // system property and env variable lookups don't get + // broken. + @Override + ConfigConcatenation relativized(Path prefix) { + List newPieces = new ArrayList(); + for (AbstractConfigValue p : pieces) { + newPieces.add(p.relativized(prefix)); + } + return new ConfigConcatenation(origin(), newPieces); + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof ConfigConcatenation; + } + + @Override + public boolean equals(Object other) { + // note that "origin" is deliberately NOT part of equality + if (other instanceof ConfigConcatenation) { + return canEqual(other) && this.pieces.equals(((ConfigConcatenation) other).pieces); + } else { + return false; + } + } + + @Override + public int hashCode() { + // note that "origin" is deliberately NOT part of equality + return pieces.hashCode(); + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + for (AbstractConfigValue p : pieces) { + p.render(sb, indent, atRoot, options); + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDelayedMerge.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDelayedMerge.java new file mode 100644 index 0000000..19bbfb7 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDelayedMerge.java @@ -0,0 +1,342 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +/** + * The issue here is that we want to first merge our stack of config files, and + * then we want to evaluate substitutions. But if two substitutions both expand + * to an object, we might need to merge those two objects. Thus, we can't ever + * "override" a substitution when we do a merge; instead we have to save the + * stack of values that should be merged, and resolve the merge when we evaluate + * substitutions. + */ +final class ConfigDelayedMerge extends AbstractConfigValue implements Unmergeable, + ReplaceableMergeStack { + + // earlier items in the stack win + final private List stack; + + ConfigDelayedMerge(ConfigOrigin origin, List stack) { + super(origin); + this.stack = stack; + if (stack.isEmpty()) + throw new ConfigException.BugOrBroken( + "creating empty delayed merge value"); + + for (AbstractConfigValue v : stack) { + if (v instanceof ConfigDelayedMerge || v instanceof ConfigDelayedMergeObject) + throw new ConfigException.BugOrBroken( + "placed nested DelayedMerge in a ConfigDelayedMerge, should have consolidated stack"); + } + } + + @Override + public ConfigValueType valueType() { + throw new ConfigException.NotResolved( + "called valueType() on value with unresolved substitutions, need to Config#resolve() first, see API docs"); + } + + @Override + public Object unwrapped() { + throw new ConfigException.NotResolved( + "called unwrapped() on value with unresolved substitutions, need to Config#resolve() first, see API docs"); + } + + @Override + ResolveResult resolveSubstitutions(ResolveContext context, ResolveSource source) + throws NotPossibleToResolve { + return resolveSubstitutions(this, stack, context, source); + } + + // static method also used by ConfigDelayedMergeObject + static ResolveResult resolveSubstitutions(ReplaceableMergeStack replaceable, + List stack, + ResolveContext context, ResolveSource source) throws NotPossibleToResolve { + if (ConfigImpl.traceSubstitutionsEnabled()) { + ConfigImpl.trace(context.depth(), "delayed merge stack has " + stack.size() + " items:"); + int count = 0; + for (AbstractConfigValue v : stack) { + ConfigImpl.trace(context.depth() + 1, count + ": " + v); + count += 1; + } + } + + // to resolve substitutions, we need to recursively resolve + // the stack of stuff to merge, and merge the stack so + // we won't be a delayed merge anymore. If restrictToChildOrNull + // is non-null, or resolve options allow partial resolves, + // we may remain a delayed merge though. + + ResolveContext newContext = context; + int count = 0; + AbstractConfigValue merged = null; + for (AbstractConfigValue end : stack) { + // the end value may or may not be resolved already + + ResolveSource sourceForEnd; + + if (end instanceof ReplaceableMergeStack) + throw new ConfigException.BugOrBroken("A delayed merge should not contain another one: " + replaceable); + else if (end instanceof Unmergeable) { + // the remainder could be any kind of value, including another + // ConfigDelayedMerge + AbstractConfigValue remainder = replaceable.makeReplacement(context, count + 1); + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), "remainder portion: " + remainder); + + // If, while resolving 'end' we come back to the same + // merge stack, we only want to look _below_ 'end' + // in the stack. So we arrange to replace the + // ConfigDelayedMerge with a value that is only + // the remainder of the stack below this one. + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), "building sourceForEnd"); + + // we resetParents() here because we'll be resolving "end" + // against a root which does NOT contain "end" + sourceForEnd = source.replaceWithinCurrentParent((AbstractConfigValue) replaceable, remainder); + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), " sourceForEnd before reset parents but after replace: " + + sourceForEnd); + + sourceForEnd = sourceForEnd.resetParents(); + } else { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), + "will resolve end against the original source with parent pushed"); + + sourceForEnd = source.pushParent(replaceable); + } + + if (ConfigImpl.traceSubstitutionsEnabled()) { + ConfigImpl.trace(newContext.depth(), "sourceForEnd =" + sourceForEnd); + } + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), "Resolving highest-priority item in delayed merge " + end + + " against " + sourceForEnd + " endWasRemoved=" + (source != sourceForEnd)); + ResolveResult result = newContext.resolve(end, sourceForEnd); + AbstractConfigValue resolvedEnd = result.value; + newContext = result.context; + + if (resolvedEnd != null) { + if (merged == null) { + merged = resolvedEnd; + } else { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth() + 1, "merging " + merged + " with fallback " + resolvedEnd); + merged = merged.withFallback(resolvedEnd); + } + } + + count += 1; + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), "stack merged, yielding: " + merged); + } + + return ResolveResult.make(newContext, merged); + } + + @Override + public AbstractConfigValue makeReplacement(ResolveContext context, int skipping) { + return ConfigDelayedMerge.makeReplacement(context, stack, skipping); + } + + // static method also used by ConfigDelayedMergeObject; end may be null + static AbstractConfigValue makeReplacement(ResolveContext context, List stack, int skipping) { + List subStack = stack.subList(skipping, stack.size()); + + if (subStack.isEmpty()) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(context.depth(), "Nothing else in the merge stack, replacing with null"); + return null; + } else { + // generate a new merge stack from only the remaining items + AbstractConfigValue merged = null; + for (AbstractConfigValue v : subStack) { + if (merged == null) + merged = v; + else + merged = merged.withFallback(v); + } + return merged; + } + } + + @Override + ResolveStatus resolveStatus() { + return ResolveStatus.UNRESOLVED; + } + + @Override + public AbstractConfigValue replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) { + List newStack = replaceChildInList(stack, child, replacement); + if (newStack == null) + return null; + else + return new ConfigDelayedMerge(origin(), newStack); + } + + @Override + public boolean hasDescendant(AbstractConfigValue descendant) { + return hasDescendantInList(stack, descendant); + } + + @Override + ConfigDelayedMerge relativized(Path prefix) { + List newStack = new ArrayList(); + for (AbstractConfigValue o : stack) { + newStack.add(o.relativized(prefix)); + } + return new ConfigDelayedMerge(origin(), newStack); + } + + // static utility shared with ConfigDelayedMergeObject + static boolean stackIgnoresFallbacks(List stack) { + AbstractConfigValue last = stack.get(stack.size() - 1); + return last.ignoresFallbacks(); + } + + @Override + protected boolean ignoresFallbacks() { + return stackIgnoresFallbacks(stack); + } + + @Override + protected AbstractConfigValue newCopy(ConfigOrigin newOrigin) { + return new ConfigDelayedMerge(newOrigin, stack); + } + + @Override + protected final ConfigDelayedMerge mergedWithTheUnmergeable(Unmergeable fallback) { + return (ConfigDelayedMerge) mergedWithTheUnmergeable(stack, fallback); + } + + @Override + protected final ConfigDelayedMerge mergedWithObject(AbstractConfigObject fallback) { + return (ConfigDelayedMerge) mergedWithObject(stack, fallback); + } + + @Override + protected ConfigDelayedMerge mergedWithNonObject(AbstractConfigValue fallback) { + return (ConfigDelayedMerge) mergedWithNonObject(stack, fallback); + } + + @Override + public Collection unmergedValues() { + return stack; + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof ConfigDelayedMerge; + } + + @Override + public boolean equals(Object other) { + // note that "origin" is deliberately NOT part of equality + if (other instanceof ConfigDelayedMerge) { + return canEqual(other) + && (this.stack == ((ConfigDelayedMerge) other).stack || this.stack + .equals(((ConfigDelayedMerge) other).stack)); + } else { + return false; + } + } + + @Override + public int hashCode() { + // note that "origin" is deliberately NOT part of equality + return stack.hashCode(); + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, String atKey, ConfigRenderOptions options) { + render(stack, sb, indent, atRoot, atKey, options); + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + render(sb, indent, atRoot, null, options); + } + + // static method also used by ConfigDelayedMergeObject. + static void render(List stack, StringBuilder sb, int indent, boolean atRoot, String atKey, + ConfigRenderOptions options) { + boolean commentMerge = options.getComments(); + if (commentMerge) { + sb.append("# unresolved merge of " + stack.size() + " values follows (\n"); + if (atKey == null) { + indent(sb, indent, options); + sb.append("# this unresolved merge will not be parseable because it's at the root of the object\n"); + indent(sb, indent, options); + sb.append("# the HOCON format has no way to list multiple root objects in a single file\n"); + } + } + + List reversed = new ArrayList(); + reversed.addAll(stack); + Collections.reverse(reversed); + + int i = 0; + for (AbstractConfigValue v : reversed) { + if (commentMerge) { + indent(sb, indent, options); + if (atKey != null) { + sb.append("# unmerged value " + i + " for key " + + ConfigImplUtil.renderJsonString(atKey) + " from "); + } else { + sb.append("# unmerged value " + i + " from "); + } + i += 1; + sb.append(v.origin().description()); + sb.append("\n"); + + for (String comment : v.origin().comments()) { + indent(sb, indent, options); + sb.append("# "); + sb.append(comment); + sb.append("\n"); + } + } + indent(sb, indent, options); + + if (atKey != null) { + sb.append(ConfigImplUtil.renderJsonString(atKey)); + if (options.getFormatted()) + sb.append(" : "); + else + sb.append(":"); + } + v.render(sb, indent, atRoot, options); + sb.append(","); + if (options.getFormatted()) + sb.append('\n'); + } + // chop comma or newline + sb.setLength(sb.length() - 1); + if (options.getFormatted()) { + sb.setLength(sb.length() - 1); // also chop comma + sb.append("\n"); // put a newline back + } + if (commentMerge) { + indent(sb, indent, options); + sb.append("# ) end of unresolved merge\n"); + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDelayedMergeObject.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDelayedMergeObject.java new file mode 100644 index 0000000..fb50805 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDelayedMergeObject.java @@ -0,0 +1,326 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigList; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; + +// This is just like ConfigDelayedMerge except we know statically +// that it will turn out to be an object. +final class ConfigDelayedMergeObject extends AbstractConfigObject implements Unmergeable, + ReplaceableMergeStack { + + final private List stack; + + ConfigDelayedMergeObject(ConfigOrigin origin, List stack) { + super(origin); + this.stack = stack; + + if (stack.isEmpty()) + throw new ConfigException.BugOrBroken( + "creating empty delayed merge object"); + if (!(stack.get(0) instanceof AbstractConfigObject)) + throw new ConfigException.BugOrBroken( + "created a delayed merge object not guaranteed to be an object"); + + for (AbstractConfigValue v : stack) { + if (v instanceof ConfigDelayedMerge || v instanceof ConfigDelayedMergeObject) + throw new ConfigException.BugOrBroken( + "placed nested DelayedMerge in a ConfigDelayedMergeObject, should have consolidated stack"); + } + } + + @Override + protected ConfigDelayedMergeObject newCopy(ResolveStatus status, ConfigOrigin origin) { + if (status != resolveStatus()) + throw new ConfigException.BugOrBroken( + "attempt to create resolved ConfigDelayedMergeObject"); + return new ConfigDelayedMergeObject(origin, stack); + } + + @Override + ResolveResult resolveSubstitutions(ResolveContext context, ResolveSource source) + throws NotPossibleToResolve { + ResolveResult merged = ConfigDelayedMerge.resolveSubstitutions(this, stack, + context, source); + return merged.asObjectResult(); + } + + @Override + public AbstractConfigValue makeReplacement(ResolveContext context, int skipping) { + return ConfigDelayedMerge.makeReplacement(context, stack, skipping); + } + + @Override + ResolveStatus resolveStatus() { + return ResolveStatus.UNRESOLVED; + } + + @Override + public AbstractConfigValue replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) { + List newStack = replaceChildInList(stack, child, replacement); + if (newStack == null) + return null; + else + return new ConfigDelayedMergeObject(origin(), newStack); + } + + @Override + public boolean hasDescendant(AbstractConfigValue descendant) { + return hasDescendantInList(stack, descendant); + } + + @Override + ConfigDelayedMergeObject relativized(Path prefix) { + List newStack = new ArrayList(); + for (AbstractConfigValue o : stack) { + newStack.add(o.relativized(prefix)); + } + return new ConfigDelayedMergeObject(origin(), newStack); + } + + @Override + protected boolean ignoresFallbacks() { + return ConfigDelayedMerge.stackIgnoresFallbacks(stack); + } + + @Override + protected final ConfigDelayedMergeObject mergedWithTheUnmergeable(Unmergeable fallback) { + requireNotIgnoringFallbacks(); + + return (ConfigDelayedMergeObject) mergedWithTheUnmergeable(stack, fallback); + } + + @Override + protected final ConfigDelayedMergeObject mergedWithObject(AbstractConfigObject fallback) { + return mergedWithNonObject(fallback); + } + + @Override + protected final ConfigDelayedMergeObject mergedWithNonObject(AbstractConfigValue fallback) { + requireNotIgnoringFallbacks(); + + return (ConfigDelayedMergeObject) mergedWithNonObject(stack, fallback); + } + + @Override + public ConfigDelayedMergeObject withFallback(ConfigMergeable mergeable) { + return (ConfigDelayedMergeObject) super.withFallback(mergeable); + } + + @Override + public ConfigDelayedMergeObject withOnlyKey(String key) { + throw notResolved(); + } + + @Override + public ConfigDelayedMergeObject withoutKey(String key) { + throw notResolved(); + } + + @Override + protected AbstractConfigObject withOnlyPathOrNull(Path path) { + throw notResolved(); + } + + @Override + AbstractConfigObject withOnlyPath(Path path) { + throw notResolved(); + } + + @Override + AbstractConfigObject withoutPath(Path path) { + throw notResolved(); + } + + @Override + public ConfigDelayedMergeObject withValue(String key, ConfigValue value) { + throw notResolved(); + } + + @Override + ConfigDelayedMergeObject withValue(Path path, ConfigValue value) { + throw notResolved(); + } + + @Override + public Collection unmergedValues() { + return stack; + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof ConfigDelayedMergeObject; + } + + @Override + public boolean equals(Object other) { + // note that "origin" is deliberately NOT part of equality + if (other instanceof ConfigDelayedMergeObject) { + return canEqual(other) + && (this.stack == ((ConfigDelayedMergeObject) other).stack || this.stack + .equals(((ConfigDelayedMergeObject) other).stack)); + } else { + return false; + } + } + + @Override + public int hashCode() { + // note that "origin" is deliberately NOT part of equality + return stack.hashCode(); + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, String atKey, ConfigRenderOptions options) { + ConfigDelayedMerge.render(stack, sb, indent, atRoot, atKey, options); + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + render(sb, indent, atRoot, null, options); + } + + private static ConfigException notResolved() { + return new ConfigException.NotResolved( + "need to Config#resolve() before using this object, see the API docs for Config#resolve()"); + } + + @Override + public Map unwrapped() { + throw notResolved(); + } + + @Override + public AbstractConfigValue get(Object key) { + throw notResolved(); + } + + @Override + public boolean containsKey(Object key) { + throw notResolved(); + } + + @Override + public boolean containsValue(Object value) { + throw notResolved(); + } + + @Override + public Set> entrySet() { + throw notResolved(); + } + + @Override + public boolean isEmpty() { + throw notResolved(); + } + + @Override + public Set keySet() { + throw notResolved(); + } + + @Override + public int size() { + throw notResolved(); + } + + @Override + public Collection values() { + throw notResolved(); + } + + @Override + protected AbstractConfigValue attemptPeekWithPartialResolve(String key) { + // a partial resolve of a ConfigDelayedMergeObject always results in a + // SimpleConfigObject because all the substitutions in the stack get + // resolved in order to look up the partial. + // So we know here that we have not been resolved at all even + // partially. + // Given that, all this code is probably gratuitous, since the app code + // is likely broken. But in general we only throw NotResolved if you try + // to touch the exact key that isn't resolved, so this is in that + // spirit. + + // we'll be able to return a key if we have a value that ignores + // fallbacks, prior to any unmergeable values. + for (AbstractConfigValue layer : stack) { + if (layer instanceof AbstractConfigObject) { + AbstractConfigObject objectLayer = (AbstractConfigObject) layer; + AbstractConfigValue v = objectLayer.attemptPeekWithPartialResolve(key); + if (v != null) { + if (v.ignoresFallbacks()) { + // we know we won't need to merge anything in to this + // value + return v; + } else { + // we can't return this value because we know there are + // unmergeable values later in the stack that may + // contain values that need to be merged with this + // value. we'll throw the exception when we get to those + // unmergeable values, so continue here. + continue; + } + } else if (layer instanceof Unmergeable) { + // an unmergeable object (which would be another + // ConfigDelayedMergeObject) can't know that a key is + // missing, so it can't return null; it can only return a + // value or throw NotPossibleToResolve + throw new ConfigException.BugOrBroken( + "should not be reached: unmergeable object returned null value"); + } else { + // a non-unmergeable AbstractConfigObject that returned null + // for the key in question is not relevant, we can keep + // looking for a value. + continue; + } + } else if (layer instanceof Unmergeable) { + throw new ConfigException.NotResolved("Key '" + key + "' is not available at '" + + origin().description() + "' because value at '" + + layer.origin().description() + + "' has not been resolved and may turn out to contain or hide '" + key + + "'." + + " Be sure to Config#resolve() before using a config object."); + } else if (layer.resolveStatus() == ResolveStatus.UNRESOLVED) { + // if the layer is not an object, and not a substitution or + // merge, + // then it's something that's unresolved because it _contains_ + // an unresolved object... i.e. it's an array + if (!(layer instanceof ConfigList)) + throw new ConfigException.BugOrBroken("Expecting a list here, not " + layer); + // all later objects will be hidden so we can say we won't find + // the key + return null; + } else { + // non-object, but resolved, like an integer or something. + // has no children so the one we're after won't be in it. + // we would only have this in the stack in case something + // else "looks back" to it due to a cycle. + // anyway at this point we know we can't find the key anymore. + if (!layer.ignoresFallbacks()) { + throw new ConfigException.BugOrBroken( + "resolved non-object should ignore fallbacks"); + } + return null; + } + } + // If we get here, then we never found anything unresolved which means + // the ConfigDelayedMergeObject should not have existed. some + // invariant was violated. + throw new ConfigException.BugOrBroken( + "Delayed merge stack does not contain any unmergeable values"); + + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDocumentParser.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDocumentParser.java new file mode 100644 index 0000000..3862796 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDocumentParser.java @@ -0,0 +1,716 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.*; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +final class ConfigDocumentParser { + static ConfigNodeRoot parse(Iterator tokens, ConfigOrigin origin, ConfigParseOptions options) { + ConfigSyntax syntax = options.getSyntax() == null ? ConfigSyntax.CONF : options.getSyntax(); + ParseContext context = new ParseContext(syntax, origin, tokens); + return context.parse(); + } + + static AbstractConfigNodeValue parseValue(Iterator tokens, ConfigOrigin origin, ConfigParseOptions options) { + ConfigSyntax syntax = options.getSyntax() == null ? ConfigSyntax.CONF : options.getSyntax(); + ParseContext context = new ParseContext(syntax, origin, tokens); + return context.parseSingleValue(); + } + + static private final class ParseContext { + private int lineNumber; + final private Stack buffer; + final private Iterator tokens; + final private ConfigSyntax flavor; + final private ConfigOrigin baseOrigin; + // this is the number of "equals" we are inside, + // used to modify the error message to reflect that + // someone may think this is .properties format. + int equalsCount; + + ParseContext(ConfigSyntax flavor, ConfigOrigin origin, Iterator tokens) { + lineNumber = 1; + buffer = new Stack(); + this.tokens = tokens; + this.flavor = flavor; + this.equalsCount = 0; + this.baseOrigin = origin; + } + + private Token popToken() { + if (buffer.isEmpty()) { + return tokens.next(); + } + return buffer.pop(); + } + + private Token nextToken() { + Token t = popToken(); + if (flavor == ConfigSyntax.JSON) { + if (Tokens.isUnquotedText(t) && !isUnquotedWhitespace(t)) { + throw parseError("Token not allowed in valid JSON: '" + + Tokens.getUnquotedText(t) + "'"); + } else if (Tokens.isSubstitution(t)) { + throw parseError("Substitutions (${} syntax) not allowed in JSON"); + } + } + return t; + } + + private Token nextTokenCollectingWhitespace(Collection nodes) { + while (true) { + Token t = nextToken(); + if (Tokens.isIgnoredWhitespace(t) || Tokens.isNewline(t) || isUnquotedWhitespace(t)) { + nodes.add(new ConfigNodeSingleToken(t)); + if (Tokens.isNewline(t)) { + lineNumber = t.lineNumber() + 1; + } + } else if (Tokens.isComment(t)) { + nodes.add(new ConfigNodeComment(t)); + } else { + int newNumber = t.lineNumber(); + if (newNumber >= 0) + lineNumber = newNumber; + return t; + } + } + } + + private void putBack(Token token) { + buffer.push(token); + } + + // In arrays and objects, comma can be omitted + // as long as there's at least one newline instead. + // this skips any newlines in front of a comma, + // skips the comma, and returns true if it found + // either a newline or a comma. The iterator + // is left just after the comma or the newline. + private boolean checkElementSeparator(Collection nodes) { + if (flavor == ConfigSyntax.JSON) { + Token t = nextTokenCollectingWhitespace(nodes); + if (t == Tokens.COMMA) { + nodes.add(new ConfigNodeSingleToken(t)); + return true; + } else { + putBack(t); + return false; + } + } else { + boolean sawSeparatorOrNewline = false; + Token t = nextToken(); + while (true) { + if (Tokens.isIgnoredWhitespace(t) || isUnquotedWhitespace(t)) { + nodes.add(new ConfigNodeSingleToken(t)); + } else if (Tokens.isComment(t)) { + nodes.add(new ConfigNodeComment(t)); + } else if (Tokens.isNewline(t)) { + sawSeparatorOrNewline = true; + lineNumber++; + nodes.add(new ConfigNodeSingleToken(t)); + // we want to continue to also eat + // a comma if there is one. + } else if (t == Tokens.COMMA) { + nodes.add(new ConfigNodeSingleToken(t)); + return true; + } else { + // non-newline-or-comma + putBack(t); + return sawSeparatorOrNewline; + } + t = nextToken(); + } + } + } + + // parse a concatenation. If there is no concatenation, return the next value + private AbstractConfigNodeValue consolidateValues(Collection nodes) { + // this trick is not done in JSON + if (flavor == ConfigSyntax.JSON) + return null; + + // create only if we have value tokens + ArrayList values = new ArrayList(); + int valueCount = 0; + + // ignore a newline up front + Token t = nextTokenCollectingWhitespace(nodes); + while (true) { + AbstractConfigNodeValue v = null; + if (Tokens.isIgnoredWhitespace(t)) { + values.add(new ConfigNodeSingleToken(t)); + t = nextToken(); + continue; + } + else if (Tokens.isValue(t) || Tokens.isUnquotedText(t) + || Tokens.isSubstitution(t) || t == Tokens.OPEN_CURLY + || t == Tokens.OPEN_SQUARE) { + // there may be newlines _within_ the objects and arrays + v = parseValue(t); + valueCount++; + } else { + break; + } + + if (v == null) + throw new ConfigException.BugOrBroken("no value"); + + values.add(v); + + t = nextToken(); // but don't consolidate across a newline + } + + putBack(t); + + // No concatenation was seen, but a single value may have been parsed, so return it, and put back + // all succeeding tokens + if (valueCount < 2) { + AbstractConfigNodeValue value = null; + for (AbstractConfigNode node : values) { + if (node instanceof AbstractConfigNodeValue) + value = (AbstractConfigNodeValue)node; + else if (value == null) + nodes.add(node); + else + putBack((new ArrayList(node.tokens())).get(0)); + } + return value; + } + + // Put back any trailing whitespace, as the parent object is responsible for tracking + // any leading/trailing whitespace + for (int i = values.size() - 1; i >= 0; i--) { + if (values.get(i) instanceof ConfigNodeSingleToken) { + putBack(((ConfigNodeSingleToken) values.get(i)).token()); + values.remove(i); + } else { + break; + } + } + return new ConfigNodeConcatenation(values); + } + + private ConfigException parseError(String message) { + return parseError(message, null); + } + + private ConfigException parseError(String message, Throwable cause) { + return new ConfigException.Parse(baseOrigin.withLineNumber(lineNumber), message, cause); + } + + private String addQuoteSuggestion(String badToken, String message) { + return addQuoteSuggestion(null, equalsCount > 0, badToken, message); + } + + private String addQuoteSuggestion(Path lastPath, boolean insideEquals, String badToken, + String message) { + String previousFieldName = lastPath != null ? lastPath.render() : null; + + String part; + if (badToken.equals(Tokens.END.toString())) { + // EOF requires special handling for the error to make sense. + if (previousFieldName != null) + part = message + " (if you intended '" + previousFieldName + + "' to be part of a value, instead of a key, " + + "try adding double quotes around the whole value"; + else + return message; + } else { + if (previousFieldName != null) { + part = message + " (if you intended " + badToken + + " to be part of the value for '" + previousFieldName + "', " + + "try enclosing the value in double quotes"; + } else { + part = message + " (if you intended " + badToken + + " to be part of a key or string value, " + + "try enclosing the key or value in double quotes"; + } + } + + if (insideEquals) + return part + + ", or you may be able to rename the file .properties rather than .conf)"; + else + return part + ")"; + } + + private AbstractConfigNodeValue parseValue(Token t) { + AbstractConfigNodeValue v = null; + int startingEqualsCount = equalsCount; + + if (Tokens.isValue(t) || Tokens.isUnquotedText(t) || Tokens.isSubstitution(t)) { + v = new ConfigNodeSimpleValue(t); + } else if (t == Tokens.OPEN_CURLY) { + v = parseObject(true); + } else if (t== Tokens.OPEN_SQUARE) { + v = parseArray(); + } else { + throw parseError(addQuoteSuggestion(t.toString(), + "Expecting a value but got wrong token: " + t)); + } + + if (equalsCount != startingEqualsCount) + throw new ConfigException.BugOrBroken("Bug in config parser: unbalanced equals count"); + + return v; + } + + private ConfigNodePath parseKey(Token token) { + if (flavor == ConfigSyntax.JSON) { + if (Tokens.isValueWithType(token, ConfigValueType.STRING)) { + return PathParser.parsePathNodeExpression(Collections.singletonList(token).iterator(), + baseOrigin.withLineNumber(lineNumber)); + } else { + throw parseError("Expecting close brace } or a field name here, got " + + token); + } + } else { + List expression = new ArrayList(); + Token t = token; + while (Tokens.isValue(t) || Tokens.isUnquotedText(t)) { + expression.add(t); + t = nextToken(); // note: don't cross a newline + } + + if (expression.isEmpty()) { + throw parseError(ExpectingClosingParenthesisError + t); + } + + putBack(t); // put back the token we ended with + return PathParser.parsePathNodeExpression(expression.iterator(), + baseOrigin.withLineNumber(lineNumber)); + } + } + + private static boolean isIncludeKeyword(Token t) { + return Tokens.isUnquotedText(t) + && Tokens.getUnquotedText(t).equals("include"); + } + + private static boolean isUnquotedWhitespace(Token t) { + if (!Tokens.isUnquotedText(t)) + return false; + + String s = Tokens.getUnquotedText(t); + + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (!ConfigImplUtil.isWhitespace(c)) + return false; + } + return true; + } + + private boolean isKeyValueSeparatorToken(Token t) { + if (flavor == ConfigSyntax.JSON) { + return t == Tokens.COLON; + } else { + return t == Tokens.COLON || t == Tokens.EQUALS || t == Tokens.PLUS_EQUALS; + } + } + + private final String ExpectingClosingParenthesisError = "expecting a close parentheses ')' here, not: "; + + private ConfigNodeInclude parseInclude(ArrayList children) { + + Token t = nextTokenCollectingWhitespace(children); + + // we either have a 'required()' or a quoted string or the "file()" syntax + if (Tokens.isUnquotedText(t)) { + String kindText = Tokens.getUnquotedText(t); + + if (kindText.startsWith("required(")) { + String r = kindText.replaceFirst("required\\(",""); + if (r.length()>0) { + putBack(Tokens.newUnquotedText(t.origin(),r)); + } + + children.add(new ConfigNodeSingleToken(t)); + //children.add(new ConfigNodeSingleToken(tOpen)); + + ConfigNodeInclude res = parseIncludeResource(children, true); + + t = nextTokenCollectingWhitespace(children); + + if (Tokens.isUnquotedText(t) && Tokens.getUnquotedText(t).equals(")")) { + // OK, close paren + } else { + throw parseError(ExpectingClosingParenthesisError + t); + } + + return res; + } else { + putBack(t); + return parseIncludeResource(children, false); + } + } + else { + putBack(t); + return parseIncludeResource(children, false); + } + } + + private ConfigNodeInclude parseIncludeResource(ArrayList children, boolean isRequired) { + Token t = nextTokenCollectingWhitespace(children); + + // we either have a quoted string or the "file()" syntax + if (Tokens.isUnquotedText(t)) { + // get foo( + String kindText = Tokens.getUnquotedText(t); + ConfigIncludeKind kind; + String prefix; + + if (kindText.startsWith("url(")) { + kind = ConfigIncludeKind.URL; + prefix = "url("; + } else if (kindText.startsWith("file(")) { + kind = ConfigIncludeKind.FILE; + prefix = "file("; + } else if (kindText.startsWith("classpath(")) { + kind = ConfigIncludeKind.CLASSPATH; + prefix = "classpath("; + } else { + throw parseError("expecting include parameter to be quoted filename, file(), classpath(), or url(). No spaces are allowed before the open paren. Not expecting: " + + t); + } + String r = kindText.replaceFirst("[^(]*\\(",""); + if (r.length()>0) { + putBack(Tokens.newUnquotedText(t.origin(),r)); + } + + children.add(new ConfigNodeSingleToken(t)); + + // skip space inside parens + t = nextTokenCollectingWhitespace(children); + + // quoted string + if (!Tokens.isValueWithType(t, ConfigValueType.STRING)) { + throw parseError("expecting include " + prefix + ") parameter to be a quoted string, rather than: " + t); + } + children.add(new ConfigNodeSimpleValue(t)); + // skip space after string, inside parens + t = nextTokenCollectingWhitespace(children); + + if (Tokens.isUnquotedText(t) && Tokens.getUnquotedText(t).startsWith(")")) { + String rest = Tokens.getUnquotedText(t).substring(1); + if (rest.length()>0) { + putBack(Tokens.newUnquotedText(t.origin(),rest)); + } + // OK, close paren + } else { + throw parseError(ExpectingClosingParenthesisError + t); + } + + return new ConfigNodeInclude(children, kind, isRequired); + } else if (Tokens.isValueWithType(t, ConfigValueType.STRING)) { + children.add(new ConfigNodeSimpleValue(t)); + return new ConfigNodeInclude(children, ConfigIncludeKind.HEURISTIC, isRequired); + } else { + throw parseError("include keyword is not followed by a quoted string, but by: " + t); + } + } + + private ConfigNodeComplexValue parseObject(boolean hadOpenCurly) { + // invoked just after the OPEN_CURLY (or START, if !hadOpenCurly) + boolean afterComma = false; + Path lastPath = null; + boolean lastInsideEquals = false; + ArrayList objectNodes = new ArrayList(); + ArrayList keyValueNodes; + HashMap keys = new HashMap(); + if (hadOpenCurly) + objectNodes.add(new ConfigNodeSingleToken(Tokens.OPEN_CURLY)); + + while (true) { + Token t = nextTokenCollectingWhitespace(objectNodes); + if (t == Tokens.CLOSE_CURLY) { + if (flavor == ConfigSyntax.JSON && afterComma) { + throw parseError(addQuoteSuggestion(t.toString(), + "expecting a field name after a comma, got a close brace } instead")); + } else if (!hadOpenCurly) { + throw parseError(addQuoteSuggestion(t.toString(), + "unbalanced close brace '}' with no open brace")); + } + objectNodes.add(new ConfigNodeSingleToken(Tokens.CLOSE_CURLY)); + break; + } else if (t == Tokens.END && !hadOpenCurly) { + putBack(t); + break; + } else if (flavor != ConfigSyntax.JSON && isIncludeKeyword(t)) { + ArrayList includeNodes = new ArrayList(); + includeNodes.add(new ConfigNodeSingleToken(t)); + objectNodes.add(parseInclude(includeNodes)); + afterComma = false; + } else { + keyValueNodes = new ArrayList(); + Token keyToken = t; + ConfigNodePath path = parseKey(keyToken); + keyValueNodes.add(path); + Token afterKey = nextTokenCollectingWhitespace(keyValueNodes); + boolean insideEquals = false; + + AbstractConfigNodeValue nextValue; + if (flavor == ConfigSyntax.CONF && afterKey == Tokens.OPEN_CURLY) { + // can omit the ':' or '=' before an object value + nextValue = parseValue(afterKey); + } else { + if (!isKeyValueSeparatorToken(afterKey)) { + throw parseError(addQuoteSuggestion(afterKey.toString(), + "Key '" + path.render() + "' may not be followed by token: " + + afterKey)); + } + + keyValueNodes.add(new ConfigNodeSingleToken(afterKey)); + + if (afterKey == Tokens.EQUALS) { + insideEquals = true; + equalsCount += 1; + } + + nextValue = consolidateValues(keyValueNodes); + if (nextValue == null) { + nextValue = parseValue(nextTokenCollectingWhitespace(keyValueNodes)); + } + } + + keyValueNodes.add(nextValue); + if (insideEquals) { + equalsCount -= 1; + } + lastInsideEquals = insideEquals; + + String key = path.value().first(); + Path remaining = path.value().remainder(); + + if (remaining == null) { + Boolean existing = keys.get(key); + if (existing != null) { + // In strict JSON, dups should be an error; while in + // our custom config language, they should be merged + // if the value is an object (or substitution that + // could become an object). + + if (flavor == ConfigSyntax.JSON) { + throw parseError("JSON does not allow duplicate fields: '" + + key + + "' was already seen"); + } + } + keys.put(key, true); + } else { + if (flavor == ConfigSyntax.JSON) { + throw new ConfigException.BugOrBroken( + "somehow got multi-element path in JSON mode"); + } + keys.put(key, true); + } + + afterComma = false; + objectNodes.add(new ConfigNodeField(keyValueNodes)); + } + + if (checkElementSeparator(objectNodes)) { + // continue looping + afterComma = true; + } else { + t = nextTokenCollectingWhitespace(objectNodes); + if (t == Tokens.CLOSE_CURLY) { + if (!hadOpenCurly) { + throw parseError(addQuoteSuggestion(lastPath, lastInsideEquals, + t.toString(), "unbalanced close brace '}' with no open brace")); + } + objectNodes.add(new ConfigNodeSingleToken(t)); + break; + } else if (hadOpenCurly) { + throw parseError(addQuoteSuggestion(lastPath, lastInsideEquals, + t.toString(), "Expecting close brace } or a comma, got " + t)); + } else { + if (t == Tokens.END) { + putBack(t); + break; + } else { + throw parseError(addQuoteSuggestion(lastPath, lastInsideEquals, + t.toString(), "Expecting end of input or a comma, got " + t)); + } + } + } + } + + return new ConfigNodeObject(objectNodes); + } + + private ConfigNodeComplexValue parseArray() { + ArrayList children = new ArrayList(); + children.add(new ConfigNodeSingleToken(Tokens.OPEN_SQUARE)); + // invoked just after the OPEN_SQUARE + Token t; + + AbstractConfigNodeValue nextValue = consolidateValues(children); + if (nextValue != null) { + children.add(nextValue); + } else { + t = nextTokenCollectingWhitespace(children); + + // special-case the first element + if (t == Tokens.CLOSE_SQUARE) { + children.add(new ConfigNodeSingleToken(t)); + return new ConfigNodeArray(children); + } else if (Tokens.isValue(t) || t == Tokens.OPEN_CURLY + || t == Tokens.OPEN_SQUARE || Tokens.isUnquotedText(t) + || Tokens.isSubstitution(t)) { + nextValue = parseValue(t); + children.add(nextValue); + } else { + throw parseError("List should have ] or a first element after the open [, instead had token: " + + t + + " (if you want " + + t + + " to be part of a string value, then double-quote it)"); + } + } + + // now remaining elements + while (true) { + // just after a value + if (checkElementSeparator(children)) { + // comma (or newline equivalent) consumed + } else { + t = nextTokenCollectingWhitespace(children); + if (t == Tokens.CLOSE_SQUARE) { + children.add(new ConfigNodeSingleToken(t)); + return new ConfigNodeArray(children); + } else { + throw parseError("List should have ended with ] or had a comma, instead had token: " + + t + + " (if you want " + + t + + " to be part of a string value, then double-quote it)"); + } + } + + // now just after a comma + nextValue = consolidateValues(children); + if (nextValue != null) { + children.add(nextValue); + } else { + t = nextTokenCollectingWhitespace(children); + if (Tokens.isValue(t) || t == Tokens.OPEN_CURLY + || t == Tokens.OPEN_SQUARE || Tokens.isUnquotedText(t) + || Tokens.isSubstitution(t)) { + nextValue = parseValue(t); + children.add(nextValue); + } else if (flavor != ConfigSyntax.JSON && t == Tokens.CLOSE_SQUARE) { + // we allow one trailing comma + putBack(t); + } else { + throw parseError("List should have had new element after a comma, instead had token: " + + t + + " (if you want the comma or " + + t + + " to be part of a string value, then double-quote it)"); + } + } + } + } + + ConfigNodeRoot parse() { + ArrayList children = new ArrayList(); + Token t = nextToken(); + if (t == Tokens.START) { + // OK + } else { + throw new ConfigException.BugOrBroken( + "token stream did not begin with START, had " + t); + } + + t = nextTokenCollectingWhitespace(children); + AbstractConfigNode result = null; + boolean missingCurly = false; + if (t == Tokens.OPEN_CURLY || t == Tokens.OPEN_SQUARE) { + result = parseValue(t); + } else { + if (flavor == ConfigSyntax.JSON) { + if (t == Tokens.END) { + throw parseError("Empty document"); + } else { + throw parseError("Document must have an object or array at root, unexpected token: " + + t); + } + } else { + // the root object can omit the surrounding braces. + // this token should be the first field's key, or part + // of it, so put it back. + putBack(t); + missingCurly = true; + result = parseObject(false); + } + } + // Need to pull the children out of the resulting node so we can keep leading + // and trailing whitespace if this was a no-brace object. Otherwise, we need to add + // the result into the list of children. + if (result instanceof ConfigNodeObject && missingCurly) { + children.addAll(((ConfigNodeComplexValue) result).children()); + } else { + children.add(result); + } + t = nextTokenCollectingWhitespace(children); + if (t == Tokens.END) { + if (missingCurly) { + // If there were no braces, the entire document should be treated as a single object + return new ConfigNodeRoot(Collections.singletonList((AbstractConfigNode)new ConfigNodeObject(children)), baseOrigin); + } else { + return new ConfigNodeRoot(children, baseOrigin); + } + } else { + throw parseError("Document has trailing tokens after first object or array: " + + t); + } + } + + // Parse a given input stream into a single value node. Used when doing a replace inside a ConfigDocument. + AbstractConfigNodeValue parseSingleValue() { + Token t = nextToken(); + if (t == Tokens.START) { + // OK + } else { + throw new ConfigException.BugOrBroken( + "token stream did not begin with START, had " + t); + } + + t = nextToken(); + if (Tokens.isIgnoredWhitespace(t) || Tokens.isNewline(t) || isUnquotedWhitespace(t) || Tokens.isComment(t)) { + throw parseError("The value from withValueText cannot have leading or trailing newlines, whitespace, or comments"); + } + if (t == Tokens.END) { + throw parseError("Empty value"); + } + if (flavor == ConfigSyntax.JSON) { + AbstractConfigNodeValue node = parseValue(t); + t = nextToken(); + if (t == Tokens.END) { + return node; + } else { + throw parseError("Parsing JSON and the value set in withValueText was either a concatenation or " + + "had trailing whitespace, newlines, or comments"); + } + } else { + putBack(t); + ArrayList nodes = new ArrayList(); + AbstractConfigNodeValue node = consolidateValues(nodes); + t = nextToken(); + if (t == Tokens.END) { + return node; + } else { + throw parseError("The value from withValueText cannot have leading or trailing newlines, whitespace, or comments"); + } + } + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDouble.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDouble.java new file mode 100644 index 0000000..523106a --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigDouble.java @@ -0,0 +1,61 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +final class ConfigDouble extends ConfigNumber implements Serializable { + + private static final long serialVersionUID = 2L; + + final private double value; + + ConfigDouble(ConfigOrigin origin, double value, String originalText) { + super(origin, originalText); + this.value = value; + } + + @Override + public ConfigValueType valueType() { + return ConfigValueType.NUMBER; + } + + @Override + public Double unwrapped() { + return value; + } + + @Override + String transformToString() { + String s = super.transformToString(); + if (s == null) + return Double.toString(value); + else + return s; + } + + @Override + protected long longValue() { + return (long) value; + } + + @Override + protected double doubleValue() { + return value; + } + + @Override + protected ConfigDouble newCopy(ConfigOrigin origin) { + return new ConfigDouble(origin, value, originalText); + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigImpl.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigImpl.java new file mode 100644 index 0000000..291b476 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigImpl.java @@ -0,0 +1,477 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.File; +import java.lang.ref.WeakReference; +import java.net.URL; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Callable; + +import com.drtshock.playervaults.lib.com.typesafe.config.Config; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluder; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMemorySize; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseable; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.impl.SimpleIncluder.NameSource; + +/** + * Internal implementation detail, not ABI stable, do not touch. + * For use only by the {@link com.typesafe.config} package. + */ +public class ConfigImpl { + + private static class LoaderCache { + private Config currentSystemProperties; + private WeakReference currentLoader; + private Map cache; + + LoaderCache() { + this.currentSystemProperties = null; + this.currentLoader = new WeakReference(null); + this.cache = new HashMap(); + } + + // for now, caching as long as the loader remains the same, + // drop entire cache if it changes. + synchronized Config getOrElseUpdate(ClassLoader loader, String key, Callable updater) { + if (loader != currentLoader.get()) { + // reset the cache if we start using a different loader + cache.clear(); + currentLoader = new WeakReference(loader); + } + + Config systemProperties = systemPropertiesAsConfig(); + if (systemProperties != currentSystemProperties) { + cache.clear(); + currentSystemProperties = systemProperties; + } + + Config config = cache.get(key); + if (config == null) { + try { + config = updater.call(); + } catch (RuntimeException e) { + throw e; // this will include ConfigException + } catch (Exception e) { + throw new ConfigException.Generic(e.getMessage(), e); + } + if (config == null) + throw new ConfigException.BugOrBroken("null config from cache updater"); + cache.put(key, config); + } + + return config; + } + } + + private static class LoaderCacheHolder { + static final LoaderCache cache = new LoaderCache(); + } + + public static Config computeCachedConfig(ClassLoader loader, String key, + Callable updater) { + LoaderCache cache; + try { + cache = LoaderCacheHolder.cache; + } catch (ExceptionInInitializerError e) { + throw ConfigImplUtil.extractInitializerError(e); + } + return cache.getOrElseUpdate(loader, key, updater); + } + + + static class FileNameSource implements SimpleIncluder.NameSource { + @Override + public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) { + return Parseable.newFile(new File(name), parseOptions); + } + }; + + static class ClasspathNameSource implements SimpleIncluder.NameSource { + @Override + public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) { + return Parseable.newResources(name, parseOptions); + } + }; + + static class ClasspathNameSourceWithClass implements SimpleIncluder.NameSource { + final private Class klass; + + public ClasspathNameSourceWithClass(Class klass) { + this.klass = klass; + } + + @Override + public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) { + return Parseable.newResources(klass, name, parseOptions); + } + }; + + public static ConfigObject parseResourcesAnySyntax(Class klass, String resourceBasename, + ConfigParseOptions baseOptions) { + NameSource source = new ClasspathNameSourceWithClass(klass); + return SimpleIncluder.fromBasename(source, resourceBasename, baseOptions); + } + + public static ConfigObject parseResourcesAnySyntax(String resourceBasename, + ConfigParseOptions baseOptions) { + NameSource source = new ClasspathNameSource(); + return SimpleIncluder.fromBasename(source, resourceBasename, baseOptions); + } + + public static ConfigObject parseFileAnySyntax(File basename, ConfigParseOptions baseOptions) { + NameSource source = new FileNameSource(); + return SimpleIncluder.fromBasename(source, basename.getPath(), baseOptions); + } + + static AbstractConfigObject emptyObject(String originDescription) { + ConfigOrigin origin = originDescription != null ? SimpleConfigOrigin + .newSimple(originDescription) : null; + return emptyObject(origin); + } + + public static Config emptyConfig(String originDescription) { + return emptyObject(originDescription).toConfig(); + } + + static AbstractConfigObject empty(ConfigOrigin origin) { + return emptyObject(origin); + } + + // default origin for values created with fromAnyRef and no origin specified + final private static ConfigOrigin defaultValueOrigin = SimpleConfigOrigin + .newSimple("hardcoded value"); + final private static ConfigBoolean defaultTrueValue = new ConfigBoolean( + defaultValueOrigin, true); + final private static ConfigBoolean defaultFalseValue = new ConfigBoolean( + defaultValueOrigin, false); + final private static ConfigNull defaultNullValue = new ConfigNull( + defaultValueOrigin); + final private static SimpleConfigList defaultEmptyList = new SimpleConfigList( + defaultValueOrigin, Collections. emptyList()); + final private static SimpleConfigObject defaultEmptyObject = SimpleConfigObject + .empty(defaultValueOrigin); + + private static SimpleConfigList emptyList(ConfigOrigin origin) { + if (origin == null || origin == defaultValueOrigin) + return defaultEmptyList; + else + return new SimpleConfigList(origin, + Collections. emptyList()); + } + + private static AbstractConfigObject emptyObject(ConfigOrigin origin) { + // we want null origin to go to SimpleConfigObject.empty() to get the + // origin "empty config" rather than "hardcoded value" + if (origin == defaultValueOrigin) + return defaultEmptyObject; + else + return SimpleConfigObject.empty(origin); + } + + private static ConfigOrigin valueOrigin(String originDescription) { + if (originDescription == null) + return defaultValueOrigin; + else + return SimpleConfigOrigin.newSimple(originDescription); + } + + public static ConfigValue fromAnyRef(Object object, String originDescription) { + ConfigOrigin origin = valueOrigin(originDescription); + return fromAnyRef(object, origin, FromMapMode.KEYS_ARE_KEYS); + } + + public static ConfigObject fromPathMap( + Map pathMap, String originDescription) { + ConfigOrigin origin = valueOrigin(originDescription); + return (ConfigObject) fromAnyRef(pathMap, origin, + FromMapMode.KEYS_ARE_PATHS); + } + + static AbstractConfigValue fromAnyRef(Object object, ConfigOrigin origin, + FromMapMode mapMode) { + if (origin == null) + throw new ConfigException.BugOrBroken( + "origin not supposed to be null"); + + if (object == null) { + if (origin != defaultValueOrigin) + return new ConfigNull(origin); + else + return defaultNullValue; + } else if(object instanceof AbstractConfigValue) { + return (AbstractConfigValue) object; + } else if (object instanceof Boolean) { + if (origin != defaultValueOrigin) { + return new ConfigBoolean(origin, (Boolean) object); + } else if ((Boolean) object) { + return defaultTrueValue; + } else { + return defaultFalseValue; + } + } else if (object instanceof String) { + return new ConfigString.Quoted(origin, (String) object); + } else if (object instanceof Number) { + // here we always keep the same type that was passed to us, + // rather than figuring out if a Long would fit in an Int + // or a Double has no fractional part. i.e. deliberately + // not using ConfigNumber.newNumber() when we have a + // Double, Integer, or Long. + if (object instanceof Double) { + return new ConfigDouble(origin, (Double) object, null); + } else if (object instanceof Integer) { + return new ConfigInt(origin, (Integer) object, null); + } else if (object instanceof Long) { + return new ConfigLong(origin, (Long) object, null); + } else { + return ConfigNumber.newNumber(origin, + ((Number) object).doubleValue(), null); + } + } else if (object instanceof Duration) { + return new ConfigLong(origin, ((Duration) object).toMillis(), null); + } else if (object instanceof Map) { + if (((Map) object).isEmpty()) + return emptyObject(origin); + + if (mapMode == FromMapMode.KEYS_ARE_KEYS) { + Map values = new HashMap(); + for (Map.Entry entry : ((Map) object).entrySet()) { + Object key = entry.getKey(); + if (!(key instanceof String)) + throw new ConfigException.BugOrBroken( + "bug in method caller: not valid to create ConfigObject from map with non-String key: " + + key); + AbstractConfigValue value = fromAnyRef(entry.getValue(), + origin, mapMode); + values.put((String) key, value); + } + + return new SimpleConfigObject(origin, values); + } else { + return PropertiesParser.fromPathMap(origin, (Map) object); + } + } else if (object instanceof Iterable) { + Iterator i = ((Iterable) object).iterator(); + if (!i.hasNext()) + return emptyList(origin); + + List values = new ArrayList(); + while (i.hasNext()) { + AbstractConfigValue v = fromAnyRef(i.next(), origin, mapMode); + values.add(v); + } + + return new SimpleConfigList(origin, values); + } else if (object instanceof ConfigMemorySize) { + return new ConfigLong(origin, ((ConfigMemorySize) object).toBytes(), null); + } else { + throw new ConfigException.BugOrBroken( + "bug in method caller: not valid to create ConfigValue from: " + + object); + } + } + + private static class DefaultIncluderHolder { + static final ConfigIncluder defaultIncluder = new SimpleIncluder(null); + } + + static ConfigIncluder defaultIncluder() { + try { + return DefaultIncluderHolder.defaultIncluder; + } catch (ExceptionInInitializerError e) { + throw ConfigImplUtil.extractInitializerError(e); + } + } + + private static Properties getSystemProperties() { + // Avoid ConcurrentModificationException due to parallel setting of system properties by copying properties + final Properties systemProperties = System.getProperties(); + final Properties systemPropertiesCopy = new Properties(); + synchronized (systemProperties) { + systemPropertiesCopy.putAll(systemProperties); + } + return systemPropertiesCopy; + } + + private static AbstractConfigObject loadSystemProperties() { + return (AbstractConfigObject) Parseable.newProperties(getSystemProperties(), + ConfigParseOptions.defaults().setOriginDescription("system properties")).parse(); + } + + private static class SystemPropertiesHolder { + // this isn't final due to the reloadSystemPropertiesConfig() hack below + static volatile AbstractConfigObject systemProperties = loadSystemProperties(); + } + + static AbstractConfigObject systemPropertiesAsConfigObject() { + try { + return SystemPropertiesHolder.systemProperties; + } catch (ExceptionInInitializerError e) { + throw ConfigImplUtil.extractInitializerError(e); + } + } + + public static Config systemPropertiesAsConfig() { + return systemPropertiesAsConfigObject().toConfig(); + } + + public static void reloadSystemPropertiesConfig() { + // ConfigFactory.invalidateCaches() relies on this having the side + // effect that it drops all caches + SystemPropertiesHolder.systemProperties = loadSystemProperties(); + } + + private static AbstractConfigObject loadEnvVariables() { + return PropertiesParser.fromStringMap(newSimpleOrigin("env variables"), System.getenv()); + } + + private static class EnvVariablesHolder { + static volatile AbstractConfigObject envVariables = loadEnvVariables(); + } + + static AbstractConfigObject envVariablesAsConfigObject() { + try { + return EnvVariablesHolder.envVariables; + } catch (ExceptionInInitializerError e) { + throw ConfigImplUtil.extractInitializerError(e); + } + } + + public static Config envVariablesAsConfig() { + return envVariablesAsConfigObject().toConfig(); + } + + public static void reloadEnvVariablesConfig() { + // ConfigFactory.invalidateCaches() relies on this having the side + // effect that it drops all caches + EnvVariablesHolder.envVariables = loadEnvVariables(); + } + + public static Config defaultReference(final ClassLoader loader) { + return computeCachedConfig(loader, "defaultReference", new Callable() { + @Override + public Config call() { + Config unresolvedResources = Parseable + .newResources("reference.conf", + ConfigParseOptions.defaults().setClassLoader(loader)) + .parse().toConfig(); + return systemPropertiesAsConfig().withFallback(unresolvedResources).resolve(); + } + }); + } + + private static class DebugHolder { + private static String LOADS = "loads"; + private static String SUBSTITUTIONS = "substitutions"; + + private static Map loadDiagnostics() { + Map result = new HashMap(); + result.put(LOADS, false); + result.put(SUBSTITUTIONS, false); + + // People do -Dconfig.trace=foo,bar to enable tracing of different things + String s = System.getProperty("config.trace"); + if (s == null) { + return result; + } else { + String[] keys = s.split(","); + for (String k : keys) { + if (k.equals(LOADS)) { + result.put(LOADS, true); + } else if (k.equals(SUBSTITUTIONS)) { + result.put(SUBSTITUTIONS, true); + } else { + System.err.println("config.trace property contains unknown trace topic '" + + k + "'"); + } + } + return result; + } + } + + private static final Map diagnostics = loadDiagnostics(); + + private static final boolean traceLoadsEnabled = diagnostics.get(LOADS); + private static final boolean traceSubstitutionsEnabled = diagnostics.get(SUBSTITUTIONS); + + static boolean traceLoadsEnabled() { + return traceLoadsEnabled; + } + + static boolean traceSubstitutionsEnabled() { + return traceSubstitutionsEnabled; + } + } + + public static boolean traceLoadsEnabled() { + try { + return DebugHolder.traceLoadsEnabled(); + } catch (ExceptionInInitializerError e) { + throw ConfigImplUtil.extractInitializerError(e); + } + } + + public static boolean traceSubstitutionsEnabled() { + try { + return DebugHolder.traceSubstitutionsEnabled(); + } catch (ExceptionInInitializerError e) { + throw ConfigImplUtil.extractInitializerError(e); + } + } + + public static void trace(String message) { + System.err.println(message); + } + + public static void trace(int indentLevel, String message) { + while (indentLevel > 0) { + System.err.print(" "); + indentLevel -= 1; + } + System.err.println(message); + } + + // the basic idea here is to add the "what" and have a canonical + // toplevel error message. the "original" exception may however have extra + // detail about what happened. call this if you have a better "what" than + // further down on the stack. + static ConfigException.NotResolved improveNotResolved(Path what, + ConfigException.NotResolved original) { + String newMessage = what.render() + + " has not been resolved, you need to call Config#resolve()," + + " see API docs for Config#resolve()"; + if (newMessage.equals(original.getMessage())) + return original; + else + return new ConfigException.NotResolved(newMessage, original); + } + + public static ConfigOrigin newSimpleOrigin(String description) { + if (description == null) { + return defaultValueOrigin; + } else { + return SimpleConfigOrigin.newSimple(description); + } + } + + public static ConfigOrigin newFileOrigin(String filename) { + return SimpleConfigOrigin.newFile(filename); + } + + public static ConfigOrigin newURLOrigin(URL url) { + return SimpleConfigOrigin.newURL(url); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigImplUtil.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigImplUtil.java new file mode 100644 index 0000000..139254b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigImplUtil.java @@ -0,0 +1,236 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; + +/** + * Internal implementation detail, not ABI stable, do not touch. + * For use only by the {@link com.typesafe.config} package. + */ +final public class ConfigImplUtil { + static boolean equalsHandlingNull(Object a, Object b) { + if (a == null && b != null) + return false; + else if (a != null && b == null) + return false; + else if (a == b) // catches null == null plus optimizes identity case + return true; + else + return a.equals(b); + } + + static boolean isC0Control(int codepoint) { + return (codepoint >= 0x0000 && codepoint <= 0x001F); + } + + public static String renderJsonString(String s) { + StringBuilder sb = new StringBuilder(); + sb.append('"'); + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + switch (c) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\n': + sb.append("\\n"); + break; + case '\b': + sb.append("\\b"); + break; + case '\f': + sb.append("\\f"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + default: + if (isC0Control(c)) + sb.append(String.format("\\u%04x", (int) c)); + else + sb.append(c); + } + } + sb.append('"'); + return sb.toString(); + } + + static String renderStringUnquotedIfPossible(String s) { + // this can quote unnecessarily as long as it never fails to quote when + // necessary + if (s.length() == 0) + return renderJsonString(s); + + // if it starts with a hyphen or number, we have to quote + // to ensure we end up with a string and not a number + int first = s.codePointAt(0); + if (Character.isDigit(first) || first == '-') + return renderJsonString(s); + + if (s.startsWith("include") || s.startsWith("true") || s.startsWith("false") + || s.startsWith("null") || s.contains("//")) + return renderJsonString(s); + + // only unquote if it's pure alphanumeric + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (!(Character.isLetter(c) || Character.isDigit(c) || c == '-')) + return renderJsonString(s); + } + + return s; + } + + static boolean isWhitespace(int codepoint) { + switch (codepoint) { + // try to hit the most common ASCII ones first, then the nonbreaking + // spaces that Java brokenly leaves out of isWhitespace. + case ' ': + case '\n': + case '\u00A0': + case '\u2007': + case '\u202F': + // this one is the BOM, see + // http://www.unicode.org/faq/utf_bom.html#BOM + // we just accept it as a zero-width nonbreaking space. + case '\uFEFF': + return true; + default: + return Character.isWhitespace(codepoint); + } + } + + public static String unicodeTrim(String s) { + // this is dumb because it looks like there aren't any whitespace + // characters that need surrogate encoding. But, points for + // pedantic correctness! It's future-proof or something. + // String.trim() actually is broken, since there are plenty of + // non-ASCII whitespace characters. + final int length = s.length(); + if (length == 0) + return s; + + int start = 0; + while (start < length) { + char c = s.charAt(start); + if (c == ' ' || c == '\n') { + start += 1; + } else { + int cp = s.codePointAt(start); + if (isWhitespace(cp)) + start += Character.charCount(cp); + else + break; + } + } + + int end = length; + while (end > start) { + char c = s.charAt(end - 1); + if (c == ' ' || c == '\n') { + --end; + } else { + int cp; + int delta; + if (Character.isLowSurrogate(c)) { + cp = s.codePointAt(end - 2); + delta = 2; + } else { + cp = s.codePointAt(end - 1); + delta = 1; + } + if (isWhitespace(cp)) + end -= delta; + else + break; + } + } + return s.substring(start, end); + } + + + public static ConfigException extractInitializerError(ExceptionInInitializerError e) { + Throwable cause = e.getCause(); + if (cause != null && cause instanceof ConfigException) { + return (ConfigException) cause; + } else { + throw e; + } + } + + static File urlToFile(URL url) { + // this isn't really right, clearly, but not sure what to do. + try { + // this will properly handle hex escapes, etc. + return new File(url.toURI()); + } catch (URISyntaxException e) { + // this handles some stuff like file:///c:/Whatever/ + // apparently but mangles handling of hex escapes + return new File(url.getPath()); + } catch (IllegalArgumentException e) { + // file://foo with double slash causes + // IllegalArgumentException "url has an authority component" + return new File(url.getPath()); + } + } + + public static String joinPath(String... elements) { + return (new Path(elements)).render(); + } + + public static String joinPath(List elements) { + return joinPath(elements.toArray(new String[0])); + } + + public static List splitPath(String path) { + Path p = Path.newPath(path); + List elements = new ArrayList(); + while (p != null) { + elements.add(p.first()); + p = p.remainder(); + } + return elements; + } + + public static ConfigOrigin readOrigin(ObjectInputStream in) throws IOException { + return SerializedConfigValue.readOrigin(in, null); + } + + public static void writeOrigin(ObjectOutputStream out, ConfigOrigin origin) throws IOException { + SerializedConfigValue.writeOrigin(new DataOutputStream(out), (SimpleConfigOrigin) origin, + null); + } + + static String toCamelCase(String originalName) { + String[] words = originalName.split("-+"); + StringBuilder nameBuilder = new StringBuilder(originalName.length()); + for (String word : words) { + if (nameBuilder.length() == 0) { + nameBuilder.append(word); + } else { + nameBuilder.append(word.substring(0, 1).toUpperCase()); + nameBuilder.append(word.substring(1)); + } + } + return nameBuilder.toString(); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigIncludeKind.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigIncludeKind.java new file mode 100644 index 0000000..127d200 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigIncludeKind.java @@ -0,0 +1,5 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +enum ConfigIncludeKind { + URL, FILE, CLASSPATH, HEURISTIC +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigInt.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigInt.java new file mode 100644 index 0000000..ae3c69c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigInt.java @@ -0,0 +1,61 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +final class ConfigInt extends ConfigNumber implements Serializable { + + private static final long serialVersionUID = 2L; + + final private int value; + + ConfigInt(ConfigOrigin origin, int value, String originalText) { + super(origin, originalText); + this.value = value; + } + + @Override + public ConfigValueType valueType() { + return ConfigValueType.NUMBER; + } + + @Override + public Integer unwrapped() { + return value; + } + + @Override + String transformToString() { + String s = super.transformToString(); + if (s == null) + return Integer.toString(value); + else + return s; + } + + @Override + protected long longValue() { + return value; + } + + @Override + protected double doubleValue() { + return value; + } + + @Override + protected ConfigInt newCopy(ConfigOrigin origin) { + return new ConfigInt(origin, value, originalText); + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigLong.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigLong.java new file mode 100644 index 0000000..40736c2 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigLong.java @@ -0,0 +1,61 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +final class ConfigLong extends ConfigNumber implements Serializable { + + private static final long serialVersionUID = 2L; + + final private long value; + + ConfigLong(ConfigOrigin origin, long value, String originalText) { + super(origin, originalText); + this.value = value; + } + + @Override + public ConfigValueType valueType() { + return ConfigValueType.NUMBER; + } + + @Override + public Long unwrapped() { + return value; + } + + @Override + String transformToString() { + String s = super.transformToString(); + if (s == null) + return Long.toString(value); + else + return s; + } + + @Override + protected long longValue() { + return value; + } + + @Override + protected double doubleValue() { + return value; + } + + @Override + protected ConfigLong newCopy(ConfigOrigin origin) { + return new ConfigLong(origin, value, originalText); + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeArray.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeArray.java new file mode 100644 index 0000000..ae7398b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeArray.java @@ -0,0 +1,14 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.Collection; + +final class ConfigNodeArray extends ConfigNodeComplexValue { + ConfigNodeArray(Collection children) { + super(children); + } + + @Override + protected ConfigNodeArray newNode(Collection nodes) { + return new ConfigNodeArray(nodes); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeComment.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeComment.java new file mode 100644 index 0000000..76213fb --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeComment.java @@ -0,0 +1,17 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; + +final class ConfigNodeComment extends ConfigNodeSingleToken { + ConfigNodeComment(Token comment) { + super(comment); + if (!Tokens.isComment(super.token)) { + throw new ConfigException.BugOrBroken("Tried to create a ConfigNodeComment from a non-comment token"); + } + } + + protected String commentText() { + return Tokens.getCommentText(super.token); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeComplexValue.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeComplexValue.java new file mode 100644 index 0000000..7191333 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeComplexValue.java @@ -0,0 +1,52 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.*; + +abstract class ConfigNodeComplexValue extends AbstractConfigNodeValue { + final protected ArrayList children; + + ConfigNodeComplexValue(Collection children) { + this.children = new ArrayList(children); + } + + final public Collection children() { + return children; + } + + @Override + protected Collection tokens() { + ArrayList tokens = new ArrayList(); + for (AbstractConfigNode child : children) { + tokens.addAll(child.tokens()); + } + return tokens; + } + + protected ConfigNodeComplexValue indentText(AbstractConfigNode indentation) { + ArrayList childrenCopy = new ArrayList(children); + for (int i = 0; i < childrenCopy.size(); i++) { + AbstractConfigNode child = childrenCopy.get(i); + if (child instanceof ConfigNodeSingleToken && + Tokens.isNewline(((ConfigNodeSingleToken) child).token())) { + childrenCopy.add(i + 1, indentation); + i++; + } else if (child instanceof ConfigNodeField) { + AbstractConfigNode value = ((ConfigNodeField) child).value(); + if (value instanceof ConfigNodeComplexValue) { + childrenCopy.set(i, ((ConfigNodeField) child).replaceValue(((ConfigNodeComplexValue) value).indentText(indentation))); + } + } else if (child instanceof ConfigNodeComplexValue) { + childrenCopy.set(i, ((ConfigNodeComplexValue) child).indentText(indentation)); + } + } + return newNode(childrenCopy); + } + + // This method will just call into the object's constructor, but it's needed + // for use in the indentText() method so we can avoid a gross if/else statement + // checking the type of this + abstract ConfigNodeComplexValue newNode(Collection nodes); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeConcatenation.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeConcatenation.java new file mode 100644 index 0000000..962ac9b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeConcatenation.java @@ -0,0 +1,14 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.Collection; + +final class ConfigNodeConcatenation extends ConfigNodeComplexValue { + ConfigNodeConcatenation(Collection children) { + super(children); + } + + @Override + protected ConfigNodeConcatenation newNode(Collection nodes) { + return new ConfigNodeConcatenation(nodes); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeField.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeField.java new file mode 100644 index 0000000..4a4d7e3 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeField.java @@ -0,0 +1,78 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +final class ConfigNodeField extends AbstractConfigNode { + final private ArrayList children; + + public ConfigNodeField(Collection children) { + this.children = new ArrayList(children); + } + + @Override + protected Collection tokens() { + ArrayList tokens = new ArrayList(); + for (AbstractConfigNode child : children) { + tokens.addAll(child.tokens()); + } + return tokens; + } + + public ConfigNodeField replaceValue(AbstractConfigNodeValue newValue) { + ArrayList childrenCopy = new ArrayList(children); + for (int i = 0; i < childrenCopy.size(); i++) { + if (childrenCopy.get(i) instanceof AbstractConfigNodeValue) { + childrenCopy.set(i, newValue); + return new ConfigNodeField(childrenCopy); + } + } + throw new ConfigException.BugOrBroken("Field node doesn't have a value"); + } + + public AbstractConfigNodeValue value() { + for (int i = 0; i < children.size(); i++) { + if (children.get(i) instanceof AbstractConfigNodeValue) { + return (AbstractConfigNodeValue)children.get(i); + } + } + throw new ConfigException.BugOrBroken("Field node doesn't have a value"); + } + + public ConfigNodePath path() { + for (int i = 0; i < children.size(); i++) { + if (children.get(i) instanceof ConfigNodePath) { + return (ConfigNodePath)children.get(i); + } + } + throw new ConfigException.BugOrBroken("Field node doesn't have a path"); + } + + protected Token separator() { + for (AbstractConfigNode child : children) { + if (child instanceof ConfigNodeSingleToken) { + Token t = ((ConfigNodeSingleToken) child).token(); + if (t == Tokens.PLUS_EQUALS || t == Tokens.COLON || t == Tokens.EQUALS) { + return t; + } + } + } + return null; + } + + protected List comments() { + List comments = new ArrayList(); + for (AbstractConfigNode child : children) { + if (child instanceof ConfigNodeComment) { + comments.add(((ConfigNodeComment) child).commentText()); + } + } + return comments; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeInclude.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeInclude.java new file mode 100644 index 0000000..25712b3 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeInclude.java @@ -0,0 +1,46 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.ArrayList; +import java.util.Collection; + +final class ConfigNodeInclude extends AbstractConfigNode { + final private ArrayList children; + final private ConfigIncludeKind kind; + final private boolean isRequired; + + ConfigNodeInclude(Collection children, ConfigIncludeKind kind, boolean isRequired) { + this.children = new ArrayList(children); + this.kind = kind; + this.isRequired = isRequired; + } + + final public Collection children() { + return children; + } + + @Override + protected Collection tokens() { + ArrayList tokens = new ArrayList(); + for (AbstractConfigNode child : children) { + tokens.addAll(child.tokens()); + } + return tokens; + } + + protected ConfigIncludeKind kind() { + return kind; + } + + protected boolean isRequired() { + return isRequired; + } + + protected String name() { + for (AbstractConfigNode n : children) { + if (n instanceof ConfigNodeSimpleValue) { + return (String)Tokens.getValue(((ConfigNodeSimpleValue) n).token()).unwrapped(); + } + } + return null; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeObject.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeObject.java new file mode 100644 index 0000000..3948950 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeObject.java @@ -0,0 +1,281 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax; + +import java.util.ArrayList; +import java.util.Collection; + +final class ConfigNodeObject extends ConfigNodeComplexValue { + ConfigNodeObject(Collection children) { + super(children); + } + + @Override + protected ConfigNodeObject newNode(Collection nodes) { + return new ConfigNodeObject(nodes); + } + + public boolean hasValue(Path desiredPath) { + for (AbstractConfigNode node : children) { + if (node instanceof ConfigNodeField) { + ConfigNodeField field = (ConfigNodeField) node; + Path key = field.path().value(); + if (key.equals(desiredPath) || key.startsWith(desiredPath)) { + return true; + } else if (desiredPath.startsWith(key)) { + if (field.value() instanceof ConfigNodeObject) { + ConfigNodeObject obj = (ConfigNodeObject) field.value(); + Path remainingPath = desiredPath.subPath(key.length()); + if (obj.hasValue(remainingPath)) { + return true; + } + } + } + } + } + return false; + } + + protected ConfigNodeObject changeValueOnPath(Path desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) { + ArrayList childrenCopy = new ArrayList(super.children); + boolean seenNonMatching = false; + // Copy the value so we can change it to null but not modify the original parameter + AbstractConfigNodeValue valueCopy = value; + for (int i = childrenCopy.size() - 1; i >= 0; i--) { + if (childrenCopy.get(i) instanceof ConfigNodeSingleToken) { + Token t = ((ConfigNodeSingleToken) childrenCopy.get(i)).token(); + // Ensure that, when we are removing settings in JSON, we don't end up with a trailing comma + if (flavor == ConfigSyntax.JSON && !seenNonMatching && t == Tokens.COMMA) { + childrenCopy.remove(i); + } + continue; + } else if (!(childrenCopy.get(i) instanceof ConfigNodeField)) { + continue; + } + ConfigNodeField node = (ConfigNodeField) childrenCopy.get(i); + Path key = node.path().value(); + + // Delete all multi-element paths that start with the desired path, since technically they are duplicates + if ((valueCopy == null && key.equals(desiredPath))|| (key.startsWith(desiredPath) && !key.equals(desiredPath))) { + childrenCopy.remove(i); + // Remove any whitespace or commas after the deleted setting + for (int j = i; j < childrenCopy.size(); j++) { + if (childrenCopy.get(j) instanceof ConfigNodeSingleToken) { + Token t = ((ConfigNodeSingleToken) childrenCopy.get(j)).token(); + if (Tokens.isIgnoredWhitespace(t) || t == Tokens.COMMA) { + childrenCopy.remove(j); + j--; + } else { + break; + } + } else { + break; + } + } + } else if (key.equals(desiredPath)) { + seenNonMatching = true; + AbstractConfigNodeValue indentedValue; + AbstractConfigNode before = i - 1 > 0 ? childrenCopy.get(i - 1) : null; + if (value instanceof ConfigNodeComplexValue && + before instanceof ConfigNodeSingleToken && + Tokens.isIgnoredWhitespace(((ConfigNodeSingleToken) before).token())) + indentedValue = ((ConfigNodeComplexValue) value).indentText(before); + else + indentedValue = value; + childrenCopy.set(i, node.replaceValue(indentedValue)); + valueCopy = null; + } else if (desiredPath.startsWith(key)) { + seenNonMatching = true; + if (node.value() instanceof ConfigNodeObject) { + Path remainingPath = desiredPath.subPath(key.length()); + childrenCopy.set(i, node.replaceValue(((ConfigNodeObject) node.value()).changeValueOnPath(remainingPath, valueCopy, flavor))); + if (valueCopy != null && !node.equals(super.children.get(i))) + valueCopy = null; + } + } else { + seenNonMatching = true; + } + } + return new ConfigNodeObject(childrenCopy); + } + + public ConfigNodeObject setValueOnPath(String desiredPath, AbstractConfigNodeValue value) { + return setValueOnPath(desiredPath, value, ConfigSyntax.CONF); + } + + public ConfigNodeObject setValueOnPath(String desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) { + ConfigNodePath path = PathParser.parsePathNode(desiredPath, flavor); + return setValueOnPath(path, value, flavor); + } + + private ConfigNodeObject setValueOnPath(ConfigNodePath desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) { + ConfigNodeObject node = changeValueOnPath(desiredPath.value(), value, flavor); + + // If the desired Path did not exist, add it + if (!node.hasValue(desiredPath.value())) { + return node.addValueOnPath(desiredPath, value, flavor); + } + return node; + } + + private Collection indentation() { + boolean seenNewLine = false; + ArrayList indentation = new ArrayList(); + if (children.isEmpty()) { + return indentation; + } + for (int i = 0; i < children.size(); i++) { + if (!seenNewLine) { + if (children.get(i) instanceof ConfigNodeSingleToken && + Tokens.isNewline(((ConfigNodeSingleToken) children.get(i)).token())) { + seenNewLine = true; + indentation.add(new ConfigNodeSingleToken(Tokens.newLine(null))); + } + } else { + if (children.get(i) instanceof ConfigNodeSingleToken && + Tokens.isIgnoredWhitespace(((ConfigNodeSingleToken) children.get(i)).token()) && + i + 1 < children.size() && (children.get(i+1) instanceof ConfigNodeField || + children.get(i+1) instanceof ConfigNodeInclude)) { + // Return the indentation of the first setting on its own line + indentation.add(children.get(i)); + return indentation; + } + } + } + if (indentation.isEmpty()) { + indentation.add(new ConfigNodeSingleToken(Tokens.newIgnoredWhitespace(null, " "))); + } else { + // Calculate the indentation of the ending curly-brace to get the indentation of the root object + AbstractConfigNode last = children.get(children.size() - 1); + if (last instanceof ConfigNodeSingleToken && ((ConfigNodeSingleToken) last).token() == Tokens.CLOSE_CURLY) { + AbstractConfigNode beforeLast = children.get(children.size() - 2); + String indent = ""; + if (beforeLast instanceof ConfigNodeSingleToken && + Tokens.isIgnoredWhitespace(((ConfigNodeSingleToken) beforeLast).token())) + indent = ((ConfigNodeSingleToken) beforeLast).token().tokenText(); + indent += " "; + indentation.add(new ConfigNodeSingleToken(Tokens.newIgnoredWhitespace(null, indent))); + return indentation; + } + } + + // The object has no curly braces and is at the root level, so don't indent + return indentation; + } + + protected ConfigNodeObject addValueOnPath(ConfigNodePath desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) { + Path path = desiredPath.value(); + ArrayList childrenCopy = new ArrayList(super.children); + ArrayList indentation = new ArrayList(indentation()); + + // If the value we're inserting is a complex value, we'll need to indent it for insertion + AbstractConfigNodeValue indentedValue; + if (value instanceof ConfigNodeComplexValue && !indentation.isEmpty()) { + indentedValue = ((ConfigNodeComplexValue) value).indentText(indentation.get(indentation.size() - 1)); + } else { + indentedValue = value; + } + boolean sameLine = !(indentation.size() > 0 && indentation.get(0) instanceof ConfigNodeSingleToken && + Tokens.isNewline(((ConfigNodeSingleToken) indentation.get(0)).token())); + + // If the path is of length greater than one, see if the value needs to be added further down + if (path.length() > 1) { + for (int i = super.children.size() - 1; i >= 0; i--) { + if (!(super.children.get(i) instanceof ConfigNodeField)) { + continue; + } + ConfigNodeField node = (ConfigNodeField) super.children.get(i); + Path key = node.path().value(); + if (path.startsWith(key) && node.value() instanceof ConfigNodeObject) { + ConfigNodePath remainingPath = desiredPath.subPath(key.length()); + ConfigNodeObject newValue = (ConfigNodeObject) node.value(); + childrenCopy.set(i, node.replaceValue(newValue.addValueOnPath(remainingPath, value, flavor))); + return new ConfigNodeObject(childrenCopy); + } + } + } + + // Otherwise, construct the new setting + boolean startsWithBrace = !super.children.isEmpty() && super.children.get(0) instanceof ConfigNodeSingleToken && + ((ConfigNodeSingleToken) super.children.get(0)).token() == Tokens.OPEN_CURLY; + ArrayList newNodes = new ArrayList(); + newNodes.addAll(indentation); + newNodes.add(desiredPath.first()); + newNodes.add(new ConfigNodeSingleToken(Tokens.newIgnoredWhitespace(null, " "))); + newNodes.add(new ConfigNodeSingleToken(Tokens.COLON)); + newNodes.add(new ConfigNodeSingleToken(Tokens.newIgnoredWhitespace(null, " "))); + + if (path.length() == 1) { + newNodes.add(indentedValue); + } else { + // If the path is of length greater than one add the required new objects along the path + ArrayList newObjectNodes = new ArrayList(); + newObjectNodes.add(new ConfigNodeSingleToken(Tokens.OPEN_CURLY)); + if (indentation.isEmpty()) { + newObjectNodes.add(new ConfigNodeSingleToken(Tokens.newLine(null))); + } + newObjectNodes.addAll(indentation); + newObjectNodes.add(new ConfigNodeSingleToken(Tokens.CLOSE_CURLY)); + ConfigNodeObject newObject = new ConfigNodeObject(newObjectNodes); + newNodes.add(newObject.addValueOnPath(desiredPath.subPath(1), indentedValue, flavor)); + } + + // Combine these two cases so that we only have to iterate once + if (flavor == ConfigSyntax.JSON || startsWithBrace || sameLine) { + for (int i = childrenCopy.size() - 1; i >= 0; i--) { + + // If we are in JSON or are adding a setting on the same line, we need to add a comma to the + // last setting + if ((flavor == ConfigSyntax.JSON || sameLine) && childrenCopy.get(i) instanceof ConfigNodeField) { + if (i+1 >= childrenCopy.size() || + !(childrenCopy.get(i+1) instanceof ConfigNodeSingleToken + && ((ConfigNodeSingleToken) childrenCopy.get(i+1)).token() == Tokens.COMMA)) + childrenCopy.add(i+1, new ConfigNodeSingleToken(Tokens.COMMA)); + break; + } + + // Add the value into the copy of the children map, keeping any whitespace/newlines + // before the close curly brace + if (startsWithBrace && childrenCopy.get(i) instanceof ConfigNodeSingleToken && + ((ConfigNodeSingleToken) childrenCopy.get(i)).token == Tokens.CLOSE_CURLY) { + AbstractConfigNode previous = childrenCopy.get(i - 1); + if (previous instanceof ConfigNodeSingleToken && + Tokens.isNewline(((ConfigNodeSingleToken) previous).token())) { + childrenCopy.add(i - 1, new ConfigNodeField(newNodes)); + i--; + } else if (previous instanceof ConfigNodeSingleToken && + Tokens.isIgnoredWhitespace(((ConfigNodeSingleToken) previous).token())) { + AbstractConfigNode beforePrevious = childrenCopy.get(i - 2); + if (sameLine) { + childrenCopy.add(i - 1, new ConfigNodeField(newNodes)); + i--; + } + else if (beforePrevious instanceof ConfigNodeSingleToken && + Tokens.isNewline(((ConfigNodeSingleToken) beforePrevious).token())) { + childrenCopy.add(i - 2, new ConfigNodeField(newNodes)); + i -= 2; + } else { + childrenCopy.add(i, new ConfigNodeField(newNodes)); + } + + } + else + childrenCopy.add(i, new ConfigNodeField(newNodes)); + } + } + } + if (!startsWithBrace) { + if (!childrenCopy.isEmpty() && childrenCopy.get(childrenCopy.size() - 1) instanceof ConfigNodeSingleToken && + Tokens.isNewline(((ConfigNodeSingleToken) childrenCopy.get(childrenCopy.size() - 1)).token())) + childrenCopy.add(childrenCopy.size() - 1, new ConfigNodeField(newNodes)); + else + childrenCopy.add(new ConfigNodeField(newNodes)); + } + return new ConfigNodeObject(childrenCopy); + } + + public ConfigNodeObject removeValueOnPath(String desiredPath, ConfigSyntax flavor) { + Path path = PathParser.parsePathNode(desiredPath, flavor).value(); + return changeValueOnPath(path, null, flavor); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodePath.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodePath.java new file mode 100644 index 0000000..4489841 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodePath.java @@ -0,0 +1,52 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; + +import java.util.ArrayList; +import java.util.Collection; + +final class ConfigNodePath extends AbstractConfigNode { + final private Path path; + final ArrayList tokens; + ConfigNodePath(Path path, Collection tokens) { + this.path = path; + this.tokens = new ArrayList(tokens); + } + + @Override + protected Collection tokens() { + return tokens; + } + + protected Path value() { + return path; + } + + protected ConfigNodePath subPath(int toRemove) { + int periodCount = 0; + ArrayList tokensCopy = new ArrayList(tokens); + for (int i = 0; i < tokensCopy.size(); i++) { + if (Tokens.isUnquotedText(tokensCopy.get(i)) && + tokensCopy.get(i).tokenText().equals(".")) + periodCount++; + + if (periodCount == toRemove) { + return new ConfigNodePath(path.subPath(toRemove), tokensCopy.subList(i + 1, tokensCopy.size())); + } + } + throw new ConfigException.BugOrBroken("Tried to remove too many elements from a Path node"); + } + + protected ConfigNodePath first() { + ArrayList tokensCopy = new ArrayList(tokens); + for (int i = 0; i < tokensCopy.size(); i++) { + if (Tokens.isUnquotedText(tokensCopy.get(i)) && + tokensCopy.get(i).tokenText().equals(".")) + return new ConfigNodePath(path.subPath(0, 1), tokensCopy.subList(0, i)); + } + return this; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeRoot.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeRoot.java new file mode 100644 index 0000000..926c0f6 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeRoot.java @@ -0,0 +1,67 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax; + +import java.util.ArrayList; +import java.util.Collection; + +final class ConfigNodeRoot extends ConfigNodeComplexValue { + final private ConfigOrigin origin; + + ConfigNodeRoot(Collection children, ConfigOrigin origin) { + super(children); + this.origin = origin; + } + + @Override + protected ConfigNodeRoot newNode(Collection nodes) { + throw new ConfigException.BugOrBroken("Tried to indent the root object"); + } + + protected ConfigNodeComplexValue value() { + for (AbstractConfigNode node : children) { + if (node instanceof ConfigNodeComplexValue) { + return (ConfigNodeComplexValue)node; + } + } + throw new ConfigException.BugOrBroken("ConfigNodeRoot did not contain a value"); + } + + protected ConfigNodeRoot setValue(String desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) { + ArrayList childrenCopy = new ArrayList(children); + for (int i = 0; i < childrenCopy.size(); i++) { + AbstractConfigNode node = childrenCopy.get(i); + if (node instanceof ConfigNodeComplexValue) { + if (node instanceof ConfigNodeArray) { + throw new ConfigException.WrongType(origin, "The ConfigDocument had an array at the root level, and values cannot be modified inside an array."); + } else if (node instanceof ConfigNodeObject) { + if (value == null) { + childrenCopy.set(i, ((ConfigNodeObject)node).removeValueOnPath(desiredPath, flavor)); + } else { + childrenCopy.set(i, ((ConfigNodeObject) node).setValueOnPath(desiredPath, value, flavor)); + } + return new ConfigNodeRoot(childrenCopy, origin); + } + } + } + throw new ConfigException.BugOrBroken("ConfigNodeRoot did not contain a value"); + } + + protected boolean hasValue(String desiredPath) { + Path path = PathParser.parsePath(desiredPath); + ArrayList childrenCopy = new ArrayList(children); + for (int i = 0; i < childrenCopy.size(); i++) { + AbstractConfigNode node = childrenCopy.get(i); + if (node instanceof ConfigNodeComplexValue) { + if (node instanceof ConfigNodeArray) { + throw new ConfigException.WrongType(origin, "The ConfigDocument had an array at the root level, and values cannot be modified inside an array."); + } else if (node instanceof ConfigNodeObject) { + return ((ConfigNodeObject) node).hasValue(path); + } + } + } + throw new ConfigException.BugOrBroken("ConfigNodeRoot did not contain a value"); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeSimpleValue.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeSimpleValue.java new file mode 100644 index 0000000..5998e84 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeSimpleValue.java @@ -0,0 +1,39 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +final class ConfigNodeSimpleValue extends AbstractConfigNodeValue { + final Token token; + ConfigNodeSimpleValue(Token value) { + token = value; + } + + @Override + protected Collection tokens() { + return Collections.singletonList(token); + } + + protected Token token() { return token; } + + protected AbstractConfigValue value() { + if (Tokens.isValue(token)) + return Tokens.getValue(token); + else if (Tokens.isUnquotedText(token)) + return new ConfigString.Unquoted(token.origin(), Tokens.getUnquotedText(token)); + else if (Tokens.isSubstitution(token)) { + List expression = Tokens.getSubstitutionPathExpression(token); + Path path = PathParser.parsePathExpression(expression.iterator(), token.origin()); + boolean optional = Tokens.getSubstitutionOptional(token); + + return new ConfigReference(token.origin(), new SubstitutionExpression(path, optional)); + } + throw new ConfigException.BugOrBroken("ConfigNodeSimpleValue did not contain a valid value token"); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeSingleToken.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeSingleToken.java new file mode 100644 index 0000000..fccd06c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNodeSingleToken.java @@ -0,0 +1,21 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.Collection; +import java.util.Collections; + +class ConfigNodeSingleToken extends AbstractConfigNode { + final Token token; + ConfigNodeSingleToken(Token t) { + token = t; + } + + @Override + protected Collection tokens() { + return Collections.singletonList(token); + } + + protected Token token() { return token; } +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNull.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNull.java new file mode 100644 index 0000000..50842df --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNull.java @@ -0,0 +1,58 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +/** + * This exists because sometimes null is not the same as missing. Specifically, + * if a value is set to null we can give a better error message (indicating + * where it was set to null) in case someone asks for the value. Also, null + * overrides values set "earlier" in the search path, while missing values do + * not. + * + */ +final class ConfigNull extends AbstractConfigValue implements Serializable { + + private static final long serialVersionUID = 2L; + + ConfigNull(ConfigOrigin origin) { + super(origin); + } + + @Override + public ConfigValueType valueType() { + return ConfigValueType.NULL; + } + + @Override + public Object unwrapped() { + return null; + } + + @Override + String transformToString() { + return "null"; + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + sb.append("null"); + } + + @Override + protected ConfigNull newCopy(ConfigOrigin origin) { + return new ConfigNull(origin); + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNumber.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNumber.java new file mode 100644 index 0000000..1c5c380 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigNumber.java @@ -0,0 +1,110 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; + +abstract class ConfigNumber extends AbstractConfigValue implements Serializable { + + private static final long serialVersionUID = 2L; + + // This is so when we concatenate a number into a string (say it appears in + // a sentence) we always have it exactly as the person typed it into the + // config file. It's purely cosmetic; equals/hashCode don't consider this + // for example. + final protected String originalText; + + protected ConfigNumber(ConfigOrigin origin, String originalText) { + super(origin); + this.originalText = originalText; + } + + @Override + public abstract Number unwrapped(); + + @Override + String transformToString() { + return originalText; + } + + int intValueRangeChecked(String path) { + long l = longValue(); + if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { + throw new ConfigException.WrongType(origin(), path, "32-bit integer", + "out-of-range value " + l); + } + return (int) l; + } + + protected abstract long longValue(); + + protected abstract double doubleValue(); + + private boolean isWhole() { + long asLong = longValue(); + return asLong == doubleValue(); + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof ConfigNumber; + } + + @Override + public boolean equals(Object other) { + // note that "origin" is deliberately NOT part of equality + if (other instanceof ConfigNumber && canEqual(other)) { + ConfigNumber n = (ConfigNumber) other; + if (isWhole()) { + return n.isWhole() && this.longValue() == n.longValue(); + } else { + return (!n.isWhole()) && this.doubleValue() == n.doubleValue(); + } + } else { + return false; + } + } + + @Override + public int hashCode() { + // note that "origin" is deliberately NOT part of equality + + // this matches what standard Long.hashCode and Double.hashCode + // do, though I don't think it really matters. + long asLong; + if (isWhole()) { + asLong = longValue(); + } else { + asLong = Double.doubleToLongBits(doubleValue()); + } + return (int) (asLong ^ (asLong >>> 32)); + } + + static ConfigNumber newNumber(ConfigOrigin origin, long number, + String originalText) { + if (number <= Integer.MAX_VALUE && number >= Integer.MIN_VALUE) + return new ConfigInt(origin, (int) number, originalText); + else + return new ConfigLong(origin, number, originalText); + } + + static ConfigNumber newNumber(ConfigOrigin origin, double number, + String originalText) { + long asLong = (long) number; + if (asLong == number) { + return newNumber(origin, asLong, originalText); + } else { + return new ConfigDouble(origin, number, originalText); + } + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigParser.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigParser.java new file mode 100644 index 0000000..19a4bc0 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigParser.java @@ -0,0 +1,426 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncludeContext; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax; + +final class ConfigParser { + static AbstractConfigValue parse(ConfigNodeRoot document, + ConfigOrigin origin, ConfigParseOptions options, + ConfigIncludeContext includeContext) { + ParseContext context = new ParseContext(options.getSyntax(), origin, document, + SimpleIncluder.makeFull(options.getIncluder()), includeContext); + return context.parse(); + } + + static private final class ParseContext { + private int lineNumber; + final private ConfigNodeRoot document; + final private FullIncluder includer; + final private ConfigIncludeContext includeContext; + final private ConfigSyntax flavor; + final private ConfigOrigin baseOrigin; + final private LinkedList pathStack; + + // the number of lists we are inside; this is used to detect the "cannot + // generate a reference to a list element" problem, and once we fix that + // problem we should be able to get rid of this variable. + int arrayCount; + + ParseContext(ConfigSyntax flavor, ConfigOrigin origin, ConfigNodeRoot document, + FullIncluder includer, ConfigIncludeContext includeContext) { + lineNumber = 1; + this.document = document; + this.flavor = flavor; + this.baseOrigin = origin; + this.includer = includer; + this.includeContext = includeContext; + this.pathStack = new LinkedList(); + this.arrayCount = 0; + } + + // merge a bunch of adjacent values into one + // value; change unquoted text into a string + // value. + private AbstractConfigValue parseConcatenation(ConfigNodeConcatenation n) { + // this trick is not done in JSON + if (flavor == ConfigSyntax.JSON) + throw new ConfigException.BugOrBroken("Found a concatenation node in JSON"); + + List values = new ArrayList(); + + for (AbstractConfigNode node : n.children()) { + AbstractConfigValue v = null; + if (node instanceof AbstractConfigNodeValue) { + v = parseValue((AbstractConfigNodeValue)node, null); + values.add(v); + } + } + + return ConfigConcatenation.concatenate(values); + } + + private SimpleConfigOrigin lineOrigin() { + return ((SimpleConfigOrigin) baseOrigin).withLineNumber(lineNumber); + } + + private ConfigException parseError(String message) { + return parseError(message, null); + } + + private ConfigException parseError(String message, Throwable cause) { + return new ConfigException.Parse(lineOrigin(), message, cause); + } + + private Path fullCurrentPath() { + // pathStack has top of stack at front + if (pathStack.isEmpty()) + throw new ConfigException.BugOrBroken("Bug in parser; tried to get current path when at root"); + else + return new Path(pathStack.descendingIterator()); + } + + private AbstractConfigValue parseValue(AbstractConfigNodeValue n, List comments) { + AbstractConfigValue v; + + int startingArrayCount = arrayCount; + + if (n instanceof ConfigNodeSimpleValue) { + v = ((ConfigNodeSimpleValue) n).value(); + } else if (n instanceof ConfigNodeObject) { + v = parseObject((ConfigNodeObject)n); + } else if (n instanceof ConfigNodeArray) { + v = parseArray((ConfigNodeArray)n); + } else if (n instanceof ConfigNodeConcatenation) { + v = parseConcatenation((ConfigNodeConcatenation)n); + } else { + throw parseError("Expecting a value but got wrong node type: " + n.getClass()); + } + + if (comments != null && !comments.isEmpty()) { + v = v.withOrigin(v.origin().prependComments(new ArrayList(comments))); + comments.clear(); + } + + if (arrayCount != startingArrayCount) + throw new ConfigException.BugOrBroken("Bug in config parser: unbalanced array count"); + + return v; + } + + private static AbstractConfigObject createValueUnderPath(Path path, + AbstractConfigValue value) { + // for path foo.bar, we are creating + // { "foo" : { "bar" : value } } + List keys = new ArrayList(); + + String key = path.first(); + Path remaining = path.remainder(); + while (key != null) { + keys.add(key); + if (remaining == null) { + break; + } else { + key = remaining.first(); + remaining = remaining.remainder(); + } + } + + // the withComments(null) is to ensure comments are only + // on the exact leaf node they apply to. + // a comment before "foo.bar" applies to the full setting + // "foo.bar" not also to "foo" + ListIterator i = keys.listIterator(keys.size()); + String deepest = i.previous(); + AbstractConfigObject o = new SimpleConfigObject(value.origin().withComments(null), + Collections. singletonMap( + deepest, value)); + while (i.hasPrevious()) { + Map m = Collections. singletonMap( + i.previous(), o); + o = new SimpleConfigObject(value.origin().withComments(null), m); + } + + return o; + } + + private void parseInclude(Map values, ConfigNodeInclude n) { + boolean isRequired = n.isRequired(); + ConfigIncludeContext cic = includeContext.setParseOptions(includeContext.parseOptions().setAllowMissing(!isRequired)); + + AbstractConfigObject obj; + switch (n.kind()) { + case URL: + URL url; + try { + url = new URL(n.name()); + } catch (MalformedURLException e) { + throw parseError("include url() specifies an invalid URL: " + n.name(), e); + } + obj = (AbstractConfigObject) includer.includeURL(cic, url); + break; + + case FILE: + obj = (AbstractConfigObject) includer.includeFile(cic, + new File(n.name())); + break; + + case CLASSPATH: + obj = (AbstractConfigObject) includer.includeResources(cic, n.name()); + break; + + case HEURISTIC: + obj = (AbstractConfigObject) includer + .include(cic, n.name()); + break; + + default: + throw new ConfigException.BugOrBroken("should not be reached"); + } + + // we really should make this work, but for now throwing an + // exception is better than producing an incorrect result. + // See https://github.com/lightbend/config/issues/160 + if (arrayCount > 0 && obj.resolveStatus() != ResolveStatus.RESOLVED) + throw parseError("Due to current limitations of the config parser, when an include statement is nested inside a list value, " + + "${} substitutions inside the included file cannot be resolved correctly. Either move the include outside of the list value or " + + "remove the ${} statements from the included file."); + + if (!pathStack.isEmpty()) { + Path prefix = fullCurrentPath(); + obj = obj.relativized(prefix); + } + + for (String key : obj.keySet()) { + AbstractConfigValue v = obj.get(key); + AbstractConfigValue existing = values.get(key); + if (existing != null) { + values.put(key, v.withFallback(existing)); + } else { + values.put(key, v); + } + } + } + + private AbstractConfigObject parseObject(ConfigNodeObject n) { + Map values = new HashMap(); + SimpleConfigOrigin objectOrigin = lineOrigin(); + boolean lastWasNewline = false; + + ArrayList nodes = new ArrayList(n.children()); + List comments = new ArrayList(); + for (int i = 0; i < nodes.size(); i++) { + AbstractConfigNode node = nodes.get(i); + if (node instanceof ConfigNodeComment) { + lastWasNewline = false; + comments.add(((ConfigNodeComment) node).commentText()); + } else if (node instanceof ConfigNodeSingleToken && Tokens.isNewline(((ConfigNodeSingleToken) node).token())) { + lineNumber++; + if (lastWasNewline) { + // Drop all comments if there was a blank line and start a new comment block + comments.clear(); + } + lastWasNewline = true; + } else if (flavor != ConfigSyntax.JSON && node instanceof ConfigNodeInclude) { + parseInclude(values, (ConfigNodeInclude)node); + lastWasNewline = false; + } else if (node instanceof ConfigNodeField) { + lastWasNewline = false; + Path path = ((ConfigNodeField) node).path().value(); + comments.addAll(((ConfigNodeField) node).comments()); + + // path must be on-stack while we parse the value + pathStack.push(path); + if (((ConfigNodeField) node).separator() == Tokens.PLUS_EQUALS) { + // we really should make this work, but for now throwing + // an exception is better than producing an incorrect + // result. See + // https://github.com/lightbend/config/issues/160 + if (arrayCount > 0) + throw parseError("Due to current limitations of the config parser, += does not work nested inside a list. " + + "+= expands to a ${} substitution and the path in ${} cannot currently refer to list elements. " + + "You might be able to move the += outside of the list and then refer to it from inside the list with ${}."); + + // because we will put it in an array after the fact so + // we want this to be incremented during the parseValue + // below in order to throw the above exception. + arrayCount += 1; + } + + AbstractConfigNodeValue valueNode; + AbstractConfigValue newValue; + + valueNode = ((ConfigNodeField) node).value(); + + // comments from the key token go to the value token + newValue = parseValue(valueNode, comments); + + if (((ConfigNodeField) node).separator() == Tokens.PLUS_EQUALS) { + arrayCount -= 1; + + List concat = new ArrayList(2); + AbstractConfigValue previousRef = new ConfigReference(newValue.origin(), + new SubstitutionExpression(fullCurrentPath(), true /* optional */)); + AbstractConfigValue list = new SimpleConfigList(newValue.origin(), + Collections.singletonList(newValue)); + concat.add(previousRef); + concat.add(list); + newValue = ConfigConcatenation.concatenate(concat); + } + + // Grab any trailing comments on the same line + if (i < nodes.size() - 1) { + i++; + while (i < nodes.size()) { + if (nodes.get(i) instanceof ConfigNodeComment) { + ConfigNodeComment comment = (ConfigNodeComment) nodes.get(i); + newValue = newValue.withOrigin(newValue.origin().appendComments( + Collections.singletonList(comment.commentText()))); + break; + } else if (nodes.get(i) instanceof ConfigNodeSingleToken) { + ConfigNodeSingleToken curr = (ConfigNodeSingleToken) nodes.get(i); + if (curr.token() == Tokens.COMMA || Tokens.isIgnoredWhitespace(curr.token())) { + // keep searching, as there could still be a comment + } else { + i--; + break; + } + } else { + i--; + break; + } + i++; + } + } + + pathStack.pop(); + + String key = path.first(); + Path remaining = path.remainder(); + + if (remaining == null) { + AbstractConfigValue existing = values.get(key); + if (existing != null) { + // In strict JSON, dups should be an error; while in + // our custom config language, they should be merged + // if the value is an object (or substitution that + // could become an object). + + if (flavor == ConfigSyntax.JSON) { + throw parseError("JSON does not allow duplicate fields: '" + + key + + "' was already seen at " + + existing.origin().description()); + } else { + newValue = newValue.withFallback(existing); + } + } + values.put(key, newValue); + } else { + if (flavor == ConfigSyntax.JSON) { + throw new ConfigException.BugOrBroken( + "somehow got multi-element path in JSON mode"); + } + + AbstractConfigObject obj = createValueUnderPath( + remaining, newValue); + AbstractConfigValue existing = values.get(key); + if (existing != null) { + obj = obj.withFallback(existing); + } + values.put(key, obj); + } + } + } + + return new SimpleConfigObject(objectOrigin, values); + } + + private SimpleConfigList parseArray(ConfigNodeArray n) { + arrayCount += 1; + + SimpleConfigOrigin arrayOrigin = lineOrigin(); + List values = new ArrayList(); + + boolean lastWasNewLine = false; + List comments = new ArrayList(); + + AbstractConfigValue v = null; + + for (AbstractConfigNode node : n.children()) { + if (node instanceof ConfigNodeComment) { + comments.add(((ConfigNodeComment) node).commentText()); + lastWasNewLine = false; + } else if (node instanceof ConfigNodeSingleToken && Tokens.isNewline(((ConfigNodeSingleToken) node).token())) { + lineNumber++; + if (lastWasNewLine && v == null) { + comments.clear(); + } else if (v != null) { + values.add(v.withOrigin(v.origin().appendComments(new ArrayList(comments)))); + comments.clear(); + v = null; + } + lastWasNewLine = true; + } else if (node instanceof AbstractConfigNodeValue) { + lastWasNewLine = false; + if (v != null) { + values.add(v.withOrigin(v.origin().appendComments(new ArrayList(comments)))); + comments.clear(); + } + v = parseValue((AbstractConfigNodeValue)node, comments); + } + } + // There shouldn't be any comments at this point, but add them just in case + if (v != null) { + values.add(v.withOrigin(v.origin().appendComments(new ArrayList(comments)))); + } + arrayCount -= 1; + return new SimpleConfigList(arrayOrigin, values); + } + + AbstractConfigValue parse() { + AbstractConfigValue result = null; + ArrayList comments = new ArrayList(); + boolean lastWasNewLine = false; + for (AbstractConfigNode node : document.children()) { + if (node instanceof ConfigNodeComment) { + comments.add(((ConfigNodeComment) node).commentText()); + lastWasNewLine = false; + } else if (node instanceof ConfigNodeSingleToken) { + Token t = ((ConfigNodeSingleToken) node).token(); + if (Tokens.isNewline(t)) { + lineNumber++; + if (lastWasNewLine && result == null) { + comments.clear(); + } else if (result != null) { + result = result.withOrigin(result.origin().appendComments(new ArrayList(comments))); + comments.clear(); + break; + } + lastWasNewLine = true; + } + } else if (node instanceof ConfigNodeComplexValue) { + result = parseValue((ConfigNodeComplexValue)node, comments); + lastWasNewLine = false; + } + } + return result; + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigReference.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigReference.java new file mode 100644 index 0000000..762264c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigReference.java @@ -0,0 +1,161 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.Collection; +import java.util.Collections; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +/** + * ConfigReference replaces ConfigReference (the older class kept for back + * compat) and represents the ${} substitution syntax. It can resolve to any + * kind of value. + */ +final class ConfigReference extends AbstractConfigValue implements Unmergeable { + + final private SubstitutionExpression expr; + // the length of any prefixes added with relativized() + final private int prefixLength; + + ConfigReference(ConfigOrigin origin, SubstitutionExpression expr) { + this(origin, expr, 0); + } + + private ConfigReference(ConfigOrigin origin, SubstitutionExpression expr, int prefixLength) { + super(origin); + this.expr = expr; + this.prefixLength = prefixLength; + } + + private ConfigException.NotResolved notResolved() { + return new ConfigException.NotResolved( + "need to Config#resolve(), see the API docs for Config#resolve(); substitution not resolved: " + + this); + } + + @Override + public ConfigValueType valueType() { + throw notResolved(); + } + + @Override + public Object unwrapped() { + throw notResolved(); + } + + @Override + protected ConfigReference newCopy(ConfigOrigin newOrigin) { + return new ConfigReference(newOrigin, expr, prefixLength); + } + + @Override + protected boolean ignoresFallbacks() { + return false; + } + + @Override + public Collection unmergedValues() { + return Collections.singleton(this); + } + + // ConfigReference should be a firewall against NotPossibleToResolve going + // further up the stack; it should convert everything to ConfigException. + // This way it's impossible for NotPossibleToResolve to "escape" since + // any failure to resolve has to start with a ConfigReference. + @Override + ResolveResult resolveSubstitutions(ResolveContext context, ResolveSource source) { + ResolveContext newContext = context.addCycleMarker(this); + AbstractConfigValue v; + try { + ResolveSource.ResultWithPath resultWithPath = source.lookupSubst(newContext, expr, prefixLength); + newContext = resultWithPath.result.context; + + if (resultWithPath.result.value != null) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), "recursively resolving " + resultWithPath + + " which was the resolution of " + expr + " against " + source); + + ResolveSource recursiveResolveSource = (new ResolveSource( + (AbstractConfigObject) resultWithPath.pathFromRoot.last(), resultWithPath.pathFromRoot)); + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), "will recursively resolve against " + recursiveResolveSource); + + ResolveResult result = newContext.resolve(resultWithPath.result.value, + recursiveResolveSource); + v = result.value; + newContext = result.context; + } else { + ConfigValue fallback = context.options().getResolver().lookup(expr.path().render()); + v = (AbstractConfigValue) fallback; + } + } catch (NotPossibleToResolve e) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(newContext.depth(), + "not possible to resolve " + expr + ", cycle involved: " + e.traceString()); + if (expr.optional()) + v = null; + else + throw new ConfigException.UnresolvedSubstitution(origin(), expr + + " was part of a cycle of substitutions involving " + e.traceString(), e); + } + + if (v == null && !expr.optional()) { + if (newContext.options().getAllowUnresolved()) + return ResolveResult.make(newContext.removeCycleMarker(this), this); + else + throw new ConfigException.UnresolvedSubstitution(origin(), expr.toString()); + } else { + return ResolveResult.make(newContext.removeCycleMarker(this), v); + } + } + + @Override + ResolveStatus resolveStatus() { + return ResolveStatus.UNRESOLVED; + } + + // when you graft a substitution into another object, + // you have to prefix it with the location in that object + // where you grafted it; but save prefixLength so + // system property and env variable lookups don't get + // broken. + @Override + ConfigReference relativized(Path prefix) { + SubstitutionExpression newExpr = expr.changePath(expr.path().prepend(prefix)); + return new ConfigReference(origin(), newExpr, prefixLength + prefix.length()); + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof ConfigReference; + } + + @Override + public boolean equals(Object other) { + // note that "origin" is deliberately NOT part of equality + if (other instanceof ConfigReference) { + return canEqual(other) && this.expr.equals(((ConfigReference) other).expr); + } else { + return false; + } + } + + @Override + public int hashCode() { + // note that "origin" is deliberately NOT part of equality + return expr.hashCode(); + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + sb.append(expr.toString()); + } + + SubstitutionExpression expression() { + return expr; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigString.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigString.java new file mode 100644 index 0000000..36e22e2 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ConfigString.java @@ -0,0 +1,85 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +abstract class ConfigString extends AbstractConfigValue implements Serializable { + + private static final long serialVersionUID = 2L; + + final protected String value; + + protected ConfigString(ConfigOrigin origin, String value) { + super(origin); + this.value = value; + } + + + final static class Quoted extends ConfigString { + Quoted(ConfigOrigin origin, String value) { + super(origin, value); + } + @Override + protected Quoted newCopy(ConfigOrigin origin) { + return new Quoted(origin, value); + } + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } + } + + // this is sort of a hack; we want to preserve whether whitespace + // was quoted until we process substitutions, so we can ignore + // unquoted whitespace when concatenating lists or objects. + // We dump this distinction when serializing and deserializing, + // but that's OK because it isn't in equals/hashCode, and we + // don't allow serializing unresolved objects which is where + // quoted-ness matters. If we later make ConfigOrigin point + // to the original token range, we could use that to implement + // wasQuoted() + final static class Unquoted extends ConfigString { + Unquoted(ConfigOrigin origin, String value) { + super(origin, value); + } + @Override + protected Unquoted newCopy(ConfigOrigin origin) { + return new Unquoted(origin, value); + } + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } + } + + boolean wasQuoted() { + return (this instanceof Quoted); + } + + @Override + public ConfigValueType valueType() { + return ConfigValueType.STRING; + } + + @Override + public String unwrapped() { + return value; + } + + @Override + String transformToString() { + return value; + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + sb.append(ConfigImplUtil.renderJsonString(value)); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Container.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Container.java new file mode 100644 index 0000000..fd9d9c4 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Container.java @@ -0,0 +1,27 @@ +/** + * Copyright (C) 2014 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; + +/** + * An AbstractConfigValue which contains other values. Java has no way to + * express "this has to be an AbstractConfigValue also" other than making + * AbstractConfigValue an interface which would be aggravating. But we can say + * we are a ConfigValue. + */ +interface Container extends ConfigValue { + /** + * Replace a child of this value. CAUTION if replacement is null, delete the + * child, which may also delete the parent, or make the parent into a + * non-container. + */ + AbstractConfigValue replaceChild(AbstractConfigValue child, AbstractConfigValue replacement); + + /** + * Super-expensive full traversal to see if descendant is anywhere + * underneath this container. + */ + boolean hasDescendant(AbstractConfigValue descendant); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/DefaultTransformer.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/DefaultTransformer.java new file mode 100644 index 0000000..f9987bc --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/DefaultTransformer.java @@ -0,0 +1,128 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +/** + * Default automatic type transformations. + */ +final class DefaultTransformer { + + static AbstractConfigValue transform(AbstractConfigValue value, + ConfigValueType requested) { + if (value.valueType() == ConfigValueType.STRING) { + String s = (String) value.unwrapped(); + switch (requested) { + case NUMBER: + try { + Long v = Long.parseLong(s); + return new ConfigLong(value.origin(), v, s); + } catch (NumberFormatException e) { + // try Double + } + try { + Double v = Double.parseDouble(s); + return new ConfigDouble(value.origin(), v, s); + } catch (NumberFormatException e) { + // oh well. + } + break; + case NULL: + if (s.equals("null")) + return new ConfigNull(value.origin()); + break; + case BOOLEAN: + if (s.equals("true") || s.equals("yes") || s.equals("on")) { + return new ConfigBoolean(value.origin(), true); + } else if (s.equals("false") || s.equals("no") + || s.equals("off")) { + return new ConfigBoolean(value.origin(), false); + } + break; + case LIST: + // can't go STRING to LIST automatically + break; + case OBJECT: + // can't go STRING to OBJECT automatically + break; + case STRING: + // no-op STRING to STRING + break; + } + } else if (requested == ConfigValueType.STRING) { + // if we converted null to string here, then you wouldn't properly + // get a missing-value error if you tried to get a null value + // as a string. + switch (value.valueType()) { + case NUMBER: // FALL THROUGH + case BOOLEAN: + return new ConfigString.Quoted(value.origin(), + value.transformToString()); + case NULL: + // want to be sure this throws instead of returning "null" as a + // string + break; + case OBJECT: + // no OBJECT to STRING automatically + break; + case LIST: + // no LIST to STRING automatically + break; + case STRING: + // no-op STRING to STRING + break; + } + } else if (requested == ConfigValueType.LIST && value.valueType() == ConfigValueType.OBJECT) { + // attempt to convert an array-like (numeric indices) object to a + // list. This would be used with .properties syntax for example: + // -Dfoo.0=bar -Dfoo.1=baz + // To ensure we still throw type errors for objects treated + // as lists in most cases, we'll refuse to convert if the object + // does not contain any numeric keys. This means we don't allow + // empty objects here though :-/ + AbstractConfigObject o = (AbstractConfigObject) value; + Map values = new HashMap(); + for (String key : o.keySet()) { + int i; + try { + i = Integer.parseInt(key, 10); + if (i < 0) + continue; + values.put(i, o.get(key)); + } catch (NumberFormatException e) { + continue; + } + } + if (!values.isEmpty()) { + ArrayList> entryList = new ArrayList>( + values.entrySet()); + // sort by numeric index + Collections.sort(entryList, + new Comparator>() { + @Override + public int compare(Map.Entry a, + Map.Entry b) { + return Integer.compare(a.getKey(), b.getKey()); + } + }); + // drop the indices (we allow gaps in the indices, for better or + // worse) + ArrayList list = new ArrayList(); + for (Map.Entry entry : entryList) { + list.add(entry.getValue()); + } + return new SimpleConfigList(value.origin(), list); + } + } + + return value; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/FromMapMode.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/FromMapMode.java new file mode 100644 index 0000000..d464897 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/FromMapMode.java @@ -0,0 +1,8 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +enum FromMapMode { + KEYS_ARE_PATHS, KEYS_ARE_KEYS +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/FullIncluder.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/FullIncluder.java new file mode 100644 index 0000000..51c8b67 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/FullIncluder.java @@ -0,0 +1,14 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluder; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderClasspath; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderFile; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderURL; + +interface FullIncluder extends ConfigIncluder, ConfigIncluderFile, ConfigIncluderURL, + ConfigIncluderClasspath { + +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/MemoKey.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/MemoKey.java new file mode 100644 index 0000000..8593abb --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/MemoKey.java @@ -0,0 +1,44 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +/** The key used to memoize already-traversed nodes when resolving substitutions */ +final class MemoKey { + MemoKey(AbstractConfigValue value, Path restrictToChildOrNull) { + this.value = value; + this.restrictToChildOrNull = restrictToChildOrNull; + } + + final private AbstractConfigValue value; + final private Path restrictToChildOrNull; + + @Override + public final int hashCode() { + int h = System.identityHashCode(value); + if (restrictToChildOrNull != null) { + return h + 41 * (41 + restrictToChildOrNull.hashCode()); + } else { + return h; + } + } + + @Override + public final boolean equals(Object other) { + if (other instanceof MemoKey) { + MemoKey o = (MemoKey) other; + if (o.value != this.value) + return false; + else if (o.restrictToChildOrNull == this.restrictToChildOrNull) + return true; + else if (o.restrictToChildOrNull == null || this.restrictToChildOrNull == null) + return false; + else + return o.restrictToChildOrNull.equals(this.restrictToChildOrNull); + } else { + return false; + } + } + + @Override + public final String toString() { + return "MemoKey(" + value + "@" + System.identityHashCode(value) + "," + restrictToChildOrNull + ")"; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/MergeableValue.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/MergeableValue.java new file mode 100644 index 0000000..a7e0441 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/MergeableValue.java @@ -0,0 +1,9 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; + +interface MergeableValue extends ConfigMergeable { + // converts a Config to its root object and a ConfigValue to itself + ConfigValue toFallbackValue(); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/OriginType.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/OriginType.java new file mode 100644 index 0000000..c43b307 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/OriginType.java @@ -0,0 +1,9 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +// caution: ordinals used in serialization +enum OriginType { + GENERIC, + FILE, + URL, + RESOURCE +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Parseable.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Parseable.java new file mode 100644 index 0000000..4ab4a4b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Parseable.java @@ -0,0 +1,891 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FilterReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.util.*; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncludeContext; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseable; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.parser.ConfigDocument; + +/** + * Internal implementation detail, not ABI stable, do not touch. + * For use only by the {@link com.typesafe.config} package. + * The point of this class is to avoid "propagating" each + * overload on "thing which can be parsed" through multiple + * interfaces. Most interfaces can have just one overload that + * takes a Parseable. Also it's used as an abstract "resource + * handle" in the ConfigIncluder interface. + */ +public abstract class Parseable implements ConfigParseable { + private ConfigIncludeContext includeContext; + private ConfigParseOptions initialOptions; + private ConfigOrigin initialOrigin; + + /** + * Internal implementation detail, not ABI stable, do not touch. + */ + protected interface Relativizer { + ConfigParseable relativeTo(String filename); + } + + private static final ThreadLocal> parseStack = new ThreadLocal>() { + @Override + protected LinkedList initialValue() { + return new LinkedList(); + } + }; + + private static final int MAX_INCLUDE_DEPTH = 50; + + protected Parseable() { + } + + private ConfigParseOptions fixupOptions(ConfigParseOptions baseOptions) { + ConfigSyntax syntax = baseOptions.getSyntax(); + if (syntax == null) { + syntax = guessSyntax(); + } + if (syntax == null) { + syntax = ConfigSyntax.CONF; + } + ConfigParseOptions modified = baseOptions.setSyntax(syntax); + + // make sure the app-provided includer falls back to default + modified = modified.appendIncluder(ConfigImpl.defaultIncluder()); + // make sure the app-provided includer is complete + modified = modified.setIncluder(SimpleIncluder.makeFull(modified.getIncluder())); + + return modified; + } + + protected void postConstruct(ConfigParseOptions baseOptions) { + this.initialOptions = fixupOptions(baseOptions); + + this.includeContext = new SimpleIncludeContext(this); + + if (initialOptions.getOriginDescription() != null) + initialOrigin = SimpleConfigOrigin.newSimple(initialOptions.getOriginDescription()); + else + initialOrigin = createOrigin(); + } + + // the general idea is that any work should be in here, not in the + // constructor, so that exceptions are thrown from the public parse() + // function and not from the creation of the Parseable. + // Essentially this is a lazy field. The parser should close the + // reader when it's done with it. + // ALSO, IMPORTANT: if the file or URL is not found, this must throw. + // to support the "allow missing" feature. + protected abstract Reader reader() throws IOException; + + protected Reader reader(ConfigParseOptions options) throws IOException { + return reader(); + } + + protected static void trace(String message) { + if (ConfigImpl.traceLoadsEnabled()) { + ConfigImpl.trace(message); + } + } + + ConfigSyntax guessSyntax() { + return null; + } + + ConfigSyntax contentType() { + return null; + } + + ConfigParseable relativeTo(String filename) { + // fall back to classpath; we treat the "filename" as absolute + // (don't add a package name in front), + // if it starts with "/" then remove the "/", for consistency + // with ParseableResources.relativeTo + String resource = filename; + if (filename.startsWith("/")) + resource = filename.substring(1); + return newResources(resource, options().setOriginDescription(null)); + } + + ConfigIncludeContext includeContext() { + return includeContext; + } + + static AbstractConfigObject forceParsedToObject(ConfigValue value) { + if (value instanceof AbstractConfigObject) { + return (AbstractConfigObject) value; + } else { + throw new ConfigException.WrongType(value.origin(), "", "object at file root", value + .valueType().name()); + } + } + + @Override + public ConfigObject parse(ConfigParseOptions baseOptions) { + + LinkedList stack = parseStack.get(); + if (stack.size() >= MAX_INCLUDE_DEPTH) { + throw new ConfigException.Parse(initialOrigin, "include statements nested more than " + + MAX_INCLUDE_DEPTH + + " times, you probably have a cycle in your includes. Trace: " + stack); + } + + stack.addFirst(this); + try { + return forceParsedToObject(parseValue(baseOptions)); + } finally { + stack.removeFirst(); + if (stack.isEmpty()) { + parseStack.remove(); + } + } + } + + final AbstractConfigValue parseValue(ConfigParseOptions baseOptions) { + // note that we are NOT using our "initialOptions", + // but using the ones from the passed-in options. The idea is that + // callers can get our original options and then parse with different + // ones if they want. + ConfigParseOptions options = fixupOptions(baseOptions); + + // passed-in options can override origin + ConfigOrigin origin; + if (options.getOriginDescription() != null) + origin = SimpleConfigOrigin.newSimple(options.getOriginDescription()); + else + origin = initialOrigin; + return parseValue(origin, options); + } + + final private AbstractConfigValue parseValue(ConfigOrigin origin, + ConfigParseOptions finalOptions) { + try { + return rawParseValue(origin, finalOptions); + } catch (IOException e) { + if (finalOptions.getAllowMissing()) { + trace(e.getMessage() + ". Allowing Missing File, this can be turned off by setting" + + " ConfigParseOptions.allowMissing = false"); + return SimpleConfigObject.emptyMissing(origin); + } else { + trace("exception loading " + origin.description() + ": " + e.getClass().getName() + + ": " + e.getMessage()); + throw new ConfigException.IO(origin, + e.getClass().getName() + ": " + e.getMessage(), e); + } + } + } + + final ConfigDocument parseDocument(ConfigParseOptions baseOptions) { + // note that we are NOT using our "initialOptions", + // but using the ones from the passed-in options. The idea is that + // callers can get our original options and then parse with different + // ones if they want. + ConfigParseOptions options = fixupOptions(baseOptions); + + // passed-in options can override origin + ConfigOrigin origin; + if (options.getOriginDescription() != null) + origin = SimpleConfigOrigin.newSimple(options.getOriginDescription()); + else + origin = initialOrigin; + return parseDocument(origin, options); + } + + final private ConfigDocument parseDocument(ConfigOrigin origin, + ConfigParseOptions finalOptions) { + try { + return rawParseDocument(origin, finalOptions); + } catch (IOException e) { + if (finalOptions.getAllowMissing()) { + ArrayList children = new ArrayList(); + children.add(new ConfigNodeObject(new ArrayList())); + return new SimpleConfigDocument(new ConfigNodeRoot(children, origin), finalOptions); + } else { + trace("exception loading " + origin.description() + ": " + e.getClass().getName() + + ": " + e.getMessage()); + throw new ConfigException.IO(origin, + e.getClass().getName() + ": " + e.getMessage(), e); + } + } + } + + // this is parseValue without post-processing the IOException or handling + // options.getAllowMissing() + protected AbstractConfigValue rawParseValue(ConfigOrigin origin, ConfigParseOptions finalOptions) + throws IOException { + Reader reader = reader(finalOptions); + + // after reader() we will have loaded the Content-Type. + ConfigSyntax contentType = contentType(); + + ConfigParseOptions optionsWithContentType; + if (contentType != null) { + if (ConfigImpl.traceLoadsEnabled() && finalOptions.getSyntax() != null) + trace("Overriding syntax " + finalOptions.getSyntax() + + " with Content-Type which specified " + contentType); + + optionsWithContentType = finalOptions.setSyntax(contentType); + } else { + optionsWithContentType = finalOptions; + } + + try { + return rawParseValue(reader, origin, optionsWithContentType); + } finally { + reader.close(); + } + } + + private AbstractConfigValue rawParseValue(Reader reader, ConfigOrigin origin, + ConfigParseOptions finalOptions) throws IOException { + if (finalOptions.getSyntax() == ConfigSyntax.PROPERTIES) { + return PropertiesParser.parse(reader, origin); + } else { + Iterator tokens = Tokenizer.tokenize(origin, reader, finalOptions.getSyntax()); + ConfigNodeRoot document = ConfigDocumentParser.parse(tokens, origin, finalOptions); + return ConfigParser.parse(document, origin, finalOptions, includeContext()); + } + } + + // this is parseDocument without post-processing the IOException or handling + // options.getAllowMissing() + protected ConfigDocument rawParseDocument(ConfigOrigin origin, ConfigParseOptions finalOptions) + throws IOException { + Reader reader = reader(finalOptions); + + // after reader() we will have loaded the Content-Type. + ConfigSyntax contentType = contentType(); + + ConfigParseOptions optionsWithContentType; + if (contentType != null) { + if (ConfigImpl.traceLoadsEnabled() && finalOptions.getSyntax() != null) + trace("Overriding syntax " + finalOptions.getSyntax() + + " with Content-Type which specified " + contentType); + + optionsWithContentType = finalOptions.setSyntax(contentType); + } else { + optionsWithContentType = finalOptions; + } + + try { + return rawParseDocument(reader, origin, optionsWithContentType); + } finally { + reader.close(); + } + } + + private ConfigDocument rawParseDocument(Reader reader, ConfigOrigin origin, + ConfigParseOptions finalOptions) throws IOException { + Iterator tokens = Tokenizer.tokenize(origin, reader, finalOptions.getSyntax()); + return new SimpleConfigDocument(ConfigDocumentParser.parse(tokens, origin, finalOptions), finalOptions); + } + + public ConfigObject parse() { + return forceParsedToObject(parseValue(options())); + } + + public ConfigDocument parseConfigDocument() { + return parseDocument(options()); + } + + AbstractConfigValue parseValue() { + return parseValue(options()); + } + + @Override + public final ConfigOrigin origin() { + return initialOrigin; + } + + protected abstract ConfigOrigin createOrigin(); + + @Override + public ConfigParseOptions options() { + return initialOptions; + } + + @Override + public String toString() { + return getClass().getSimpleName(); + } + + private static ConfigSyntax syntaxFromExtension(String name) { + if (name.endsWith(".json")) + return ConfigSyntax.JSON; + else if (name.endsWith(".conf")) + return ConfigSyntax.CONF; + else if (name.endsWith(".properties")) + return ConfigSyntax.PROPERTIES; + else + return null; + } + + private static Reader readerFromStream(InputStream input) { + return readerFromStream(input, "UTF-8"); + } + + private static Reader readerFromStream(InputStream input, String encoding) { + try { + // well, this is messed up. If we aren't going to close + // the passed-in InputStream then we have no way to + // close these readers. So maybe we should not have an + // InputStream version, only a Reader version. + Reader reader = new InputStreamReader(input, encoding); + return new BufferedReader(reader); + } catch (UnsupportedEncodingException e) { + throw new ConfigException.BugOrBroken("Java runtime does not support UTF-8", e); + } + } + + private static Reader doNotClose(Reader input) { + return new FilterReader(input) { + @Override + public void close() { + // NOTHING. + } + }; + } + + static URL relativeTo(URL url, String filename) { + // I'm guessing this completely fails on Windows, help wanted + if (new File(filename).isAbsolute()) + return null; + + try { + URI siblingURI = url.toURI(); + URI relative = new URI(filename); + + // this seems wrong, but it's documented that the last + // element of the path in siblingURI gets stripped out, + // so to get something in the same directory as + // siblingURI we just call resolve(). + URL resolved = siblingURI.resolve(relative).toURL(); + + return resolved; + } catch (MalformedURLException e) { + return null; + } catch (URISyntaxException e) { + return null; + } catch (IllegalArgumentException e) { + return null; + } + } + + static File relativeTo(File file, String filename) { + File child = new File(filename); + + if (child.isAbsolute()) + return null; + + File parent = file.getParentFile(); + + if (parent == null) + return null; + else + return new File(parent, filename); + } + + // this is a parseable that doesn't exist and just throws when you try to + // parse it + private final static class ParseableNotFound extends Parseable { + final private String what; + final private String message; + + ParseableNotFound(String what, String message, ConfigParseOptions options) { + this.what = what; + this.message = message; + postConstruct(options); + } + + @Override + protected Reader reader() throws IOException { + throw new FileNotFoundException(message); + } + + @Override + protected ConfigOrigin createOrigin() { + return SimpleConfigOrigin.newSimple(what); + } + } + + public static Parseable newNotFound(String whatNotFound, String message, + ConfigParseOptions options) { + return new ParseableNotFound(whatNotFound, message, options); + } + + private final static class ParseableReader extends Parseable { + final private Reader reader; + + ParseableReader(Reader reader, ConfigParseOptions options) { + this.reader = reader; + postConstruct(options); + } + + @Override + protected Reader reader() { + if (ConfigImpl.traceLoadsEnabled()) + trace("Loading config from reader " + reader); + return reader; + } + + @Override + protected ConfigOrigin createOrigin() { + return SimpleConfigOrigin.newSimple("Reader"); + } + } + + // note that we will never close this reader; you have to do it when parsing + // is complete. + public static Parseable newReader(Reader reader, ConfigParseOptions options) { + + return new ParseableReader(doNotClose(reader), options); + } + + private final static class ParseableString extends Parseable { + final private String input; + + ParseableString(String input, ConfigParseOptions options) { + this.input = input; + postConstruct(options); + } + + @Override + protected Reader reader() { + if (ConfigImpl.traceLoadsEnabled()) + trace("Loading config from a String " + input); + return new StringReader(input); + } + + @Override + protected ConfigOrigin createOrigin() { + return SimpleConfigOrigin.newSimple("String"); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "(" + input + ")"; + } + } + + public static Parseable newString(String input, ConfigParseOptions options) { + return new ParseableString(input, options); + } + + private static final String jsonContentType = "application/json"; + private static final String propertiesContentType = "text/x-java-properties"; + private static final String hoconContentType = "application/hocon"; + + private static class ParseableURL extends Parseable { + final protected URL input; + private String contentType = null; + + protected ParseableURL(URL input) { + this.input = input; + // does not postConstruct (subclass does it) + } + + ParseableURL(URL input, ConfigParseOptions options) { + this(input); + postConstruct(options); + } + + @Override + protected Reader reader() throws IOException { + throw new ConfigException.BugOrBroken("reader() without options should not be called on ParseableURL"); + } + + private static String acceptContentType(ConfigParseOptions options) { + if (options.getSyntax() == null) + return null; + + switch (options.getSyntax()) { + case JSON: + return jsonContentType; + case CONF: + return hoconContentType; + case PROPERTIES: + return propertiesContentType; + } + + // not sure this is reachable but javac thinks it is + return null; + } + + @Override + protected Reader reader(ConfigParseOptions options) throws IOException { + try { + if (ConfigImpl.traceLoadsEnabled()) + trace("Loading config from a URL: " + input.toExternalForm()); + URLConnection connection = input.openConnection(); + + // allow server to serve multiple types from one URL + String acceptContent = acceptContentType(options); + if (acceptContent != null) { + connection.setRequestProperty("Accept", acceptContent); + } + + connection.connect(); + + // save content type for later + contentType = connection.getContentType(); + if (contentType != null) { + if (ConfigImpl.traceLoadsEnabled()) + trace("URL sets Content-Type: '" + contentType + "'"); + contentType = contentType.trim(); + int semi = contentType.indexOf(';'); + if (semi >= 0) + contentType = contentType.substring(0, semi); + } + + InputStream stream = connection.getInputStream(); + + return readerFromStream(stream); + } catch (FileNotFoundException fnf) { + // If the resource is not found (HTTP response + // code 404 or something alike), then it's fine to + // treat it according to the allowMissing setting + // and "include" spec. But if we have something + // like HTTP 503 it seems to be better to fail + // early, because this may be a sign of broken + // environment. Java throws FileNotFoundException + // if it sees 404 or 410. + throw fnf; + } catch (IOException e) { + throw new ConfigException.BugOrBroken("Cannot load config from URL: " + input.toExternalForm(), e); + } + } + + @Override + ConfigSyntax guessSyntax() { + return syntaxFromExtension(input.getPath()); + } + + @Override + ConfigSyntax contentType() { + if (contentType != null) { + if (contentType.equals(jsonContentType)) + return ConfigSyntax.JSON; + else if (contentType.equals(propertiesContentType)) + return ConfigSyntax.PROPERTIES; + else if (contentType.equals(hoconContentType)) + return ConfigSyntax.CONF; + else { + if (ConfigImpl.traceLoadsEnabled()) + trace("'" + contentType + "' isn't a known content type"); + return null; + } + } else { + return null; + } + } + + @Override + ConfigParseable relativeTo(String filename) { + URL url = relativeTo(input, filename); + if (url == null) + return null; + return newURL(url, options().setOriginDescription(null)); + } + + @Override + protected ConfigOrigin createOrigin() { + return SimpleConfigOrigin.newURL(input); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "(" + input.toExternalForm() + ")"; + } + } + + public static Parseable newURL(URL input, ConfigParseOptions options) { + // we want file: URLs and files to always behave the same, so switch + // to a file if it's a file: URL + if (input.getProtocol().equals("file")) { + return newFile(ConfigImplUtil.urlToFile(input), options); + } else { + return new ParseableURL(input, options); + } + } + + private final static class ParseableFile extends Parseable { + final private File input; + + ParseableFile(File input, ConfigParseOptions options) { + this.input = input; + postConstruct(options); + } + + @Override + protected Reader reader() throws IOException { + if (ConfigImpl.traceLoadsEnabled()) + trace("Loading config from a file: " + input); + InputStream stream = new FileInputStream(input); + return readerFromStream(stream); + } + + @Override + ConfigSyntax guessSyntax() { + return syntaxFromExtension(input.getName()); + } + + @Override + ConfigParseable relativeTo(String filename) { + File sibling; + if ((new File(filename)).isAbsolute()) { + sibling = new File(filename); + } else { + // this may return null + sibling = relativeTo(input, filename); + } + if (sibling == null) + return null; + if (sibling.exists()) { + trace(sibling + " exists, so loading it as a file"); + return newFile(sibling, options().setOriginDescription(null)); + } else { + trace(sibling + " does not exist, so trying it as a classpath resource"); + return super.relativeTo(filename); + } + } + + @Override + protected ConfigOrigin createOrigin() { + return SimpleConfigOrigin.newFile(input.getPath()); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "(" + input.getPath() + ")"; + } + } + + public static Parseable newFile(File input, ConfigParseOptions options) { + return new ParseableFile(input, options); + } + + + private final static class ParseableResourceURL extends ParseableURL { + + private final Relativizer relativizer; + private final String resource; + + ParseableResourceURL(URL input, ConfigParseOptions options, String resource, Relativizer relativizer) { + super(input); + this.relativizer = relativizer; + this.resource = resource; + postConstruct(options); + } + + @Override + protected ConfigOrigin createOrigin() { + return SimpleConfigOrigin.newResource(resource, input); + } + + @Override + ConfigParseable relativeTo(String filename) { + return relativizer.relativeTo(filename); + } + } + + private static Parseable newResourceURL(URL input, ConfigParseOptions options, String resource, Relativizer relativizer) { + return new ParseableResourceURL(input, options, resource, relativizer); + } + + private final static class ParseableResources extends Parseable implements Relativizer { + final private String resource; + + ParseableResources(String resource, ConfigParseOptions options) { + this.resource = resource; + postConstruct(options); + } + + @Override + protected Reader reader() throws IOException { + throw new ConfigException.BugOrBroken("reader() should not be called on resources"); + } + + @Override + protected AbstractConfigObject rawParseValue(ConfigOrigin origin, + ConfigParseOptions finalOptions) throws IOException { + ClassLoader loader = finalOptions.getClassLoader(); + if (loader == null) + throw new ConfigException.BugOrBroken( + "null class loader; pass in a class loader or use Thread.currentThread().setContextClassLoader()"); + Enumeration e = loader.getResources(resource); + if (!e.hasMoreElements()) { + if (ConfigImpl.traceLoadsEnabled()) + trace("Loading config from class loader " + loader + + " but there were no resources called " + resource); + throw new IOException("resource not found on classpath: " + resource); + } + AbstractConfigObject merged = SimpleConfigObject.empty(origin); + while (e.hasMoreElements()) { + URL url = e.nextElement(); + + if (ConfigImpl.traceLoadsEnabled()) + trace("Loading config from resource '" + resource + "' URL " + url.toExternalForm() + " from class loader " + + loader); + + Parseable element = newResourceURL(url, finalOptions, resource, this); + + AbstractConfigValue v = element.parseValue(); + + merged = merged.withFallback(v); + } + + return merged; + } + + @Override + ConfigSyntax guessSyntax() { + return syntaxFromExtension(resource); + } + + static String parent(String resource) { + // the "resource" is not supposed to begin with a "/" + // because it's supposed to be the raw resource + // (ClassLoader#getResource), not the + // resource "syntax" (Class#getResource) + int i = resource.lastIndexOf('/'); + if (i < 0) { + return null; + } else { + return resource.substring(0, i); + } + } + + @Override + public ConfigParseable relativeTo(String sibling) { + if (sibling.startsWith("/")) { + // if it starts with "/" then don't make it relative to + // the including resource + return newResources(sibling.substring(1), options().setOriginDescription(null)); + } else { + // here we want to build a new resource name and let + // the class loader have it, rather than getting the + // url with getResource() and relativizing to that url. + // This is needed in case the class loader is going to + // search a classpath. + String parent = parent(resource); + if (parent == null) + return newResources(sibling, options().setOriginDescription(null)); + else + return newResources(parent + "/" + sibling, options() + .setOriginDescription(null)); + } + } + + @Override + protected ConfigOrigin createOrigin() { + return SimpleConfigOrigin.newResource(resource); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "(" + resource + ")"; + } + } + + public static Parseable newResources(Class klass, String resource, ConfigParseOptions options) { + return newResources(convertResourceName(klass, resource), + options.setClassLoader(klass.getClassLoader())); + } + + // this function is supposed to emulate the difference + // between Class.getResource and ClassLoader.getResource + // (unfortunately there doesn't seem to be public API for it). + // We're using it because the Class API is more limited, + // for example it lacks getResources(). So we want to be able to + // use ClassLoader directly. + private static String convertResourceName(Class klass, String resource) { + if (resource.startsWith("/")) { + // "absolute" resource, chop the slash + return resource.substring(1); + } else { + String className = klass.getName(); + int i = className.lastIndexOf('.'); + if (i < 0) { + // no package + return resource; + } else { + // need to be relative to the package + String packageName = className.substring(0, i); + String packagePath = packageName.replace('.', '/'); + return packagePath + "/" + resource; + } + } + } + + public static Parseable newResources(String resource, ConfigParseOptions options) { + if (options.getClassLoader() == null) + throw new ConfigException.BugOrBroken( + "null class loader; pass in a class loader or use Thread.currentThread().setContextClassLoader()"); + return new ParseableResources(resource, options); + } + + private final static class ParseableProperties extends Parseable { + final private Properties props; + + ParseableProperties(Properties props, ConfigParseOptions options) { + this.props = props; + postConstruct(options); + } + + @Override + protected Reader reader() throws IOException { + throw new ConfigException.BugOrBroken("reader() should not be called on props"); + } + + @Override + protected AbstractConfigObject rawParseValue(ConfigOrigin origin, + ConfigParseOptions finalOptions) { + if (ConfigImpl.traceLoadsEnabled()) + trace("Loading config from properties " + props); + return PropertiesParser.fromProperties(origin, props); + } + + @Override + ConfigSyntax guessSyntax() { + return ConfigSyntax.PROPERTIES; + } + + @Override + protected ConfigOrigin createOrigin() { + return SimpleConfigOrigin.newSimple("properties"); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "(" + props.size() + " props)"; + } + } + + public static Parseable newProperties(Properties properties, ConfigParseOptions options) { + return new ParseableProperties(properties, options); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Path.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Path.java new file mode 100644 index 0000000..d833f09 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Path.java @@ -0,0 +1,232 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.*; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; + +final class Path { + + final private String first; + final private Path remainder; + + Path(String first, Path remainder) { + this.first = first; + this.remainder = remainder; + } + + Path(String... elements) { + if (elements.length == 0) + throw new ConfigException.BugOrBroken("empty path"); + this.first = elements[0]; + if (elements.length > 1) { + PathBuilder pb = new PathBuilder(); + for (int i = 1; i < elements.length; ++i) { + pb.appendKey(elements[i]); + } + this.remainder = pb.result(); + } else { + this.remainder = null; + } + } + + // append all the paths in the list together into one path + Path(List pathsToConcat) { + this(pathsToConcat.iterator()); + } + + // append all the paths in the iterator together into one path + Path(Iterator i) { + if (!i.hasNext()) + throw new ConfigException.BugOrBroken("empty path"); + + Path firstPath = i.next(); + this.first = firstPath.first; + + PathBuilder pb = new PathBuilder(); + if (firstPath.remainder != null) { + pb.appendPath(firstPath.remainder); + } + while (i.hasNext()) { + pb.appendPath(i.next()); + } + this.remainder = pb.result(); + } + + String first() { + return first; + } + + /** + * + * @return path minus the first element or null if no more elements + */ + Path remainder() { + return remainder; + } + + /** + * + * @return path minus the last element or null if we have just one element + */ + Path parent() { + if (remainder == null) + return null; + + PathBuilder pb = new PathBuilder(); + Path p = this; + while (p.remainder != null) { + pb.appendKey(p.first); + p = p.remainder; + } + return pb.result(); + } + + /** + * + * @return last element in the path + */ + String last() { + Path p = this; + while (p.remainder != null) { + p = p.remainder; + } + return p.first; + } + + Path prepend(Path toPrepend) { + PathBuilder pb = new PathBuilder(); + pb.appendPath(toPrepend); + pb.appendPath(this); + return pb.result(); + } + + int length() { + int count = 1; + Path p = remainder; + while (p != null) { + count += 1; + p = p.remainder; + } + return count; + } + + Path subPath(int removeFromFront) { + int count = removeFromFront; + Path p = this; + while (p != null && count > 0) { + count -= 1; + p = p.remainder; + } + return p; + } + + Path subPath(int firstIndex, int lastIndex) { + if (lastIndex < firstIndex) + throw new ConfigException.BugOrBroken("bad call to subPath"); + + Path from = subPath(firstIndex); + PathBuilder pb = new PathBuilder(); + int count = lastIndex - firstIndex; + while (count > 0) { + count -= 1; + pb.appendKey(from.first()); + from = from.remainder(); + if (from == null) + throw new ConfigException.BugOrBroken("subPath lastIndex out of range " + lastIndex); + } + return pb.result(); + } + + boolean startsWith(Path other) { + Path myRemainder = this; + Path otherRemainder = other; + if (otherRemainder.length() <= myRemainder.length()) { + while(otherRemainder != null) { + if (!otherRemainder.first().equals(myRemainder.first())) + return false; + myRemainder = myRemainder.remainder(); + otherRemainder = otherRemainder.remainder(); + } + return true; + } + return false; + } + + @Override + public boolean equals(Object other) { + if (other instanceof Path) { + Path that = (Path) other; + return this.first.equals(that.first) + && ConfigImplUtil.equalsHandlingNull(this.remainder, + that.remainder); + } else { + return false; + } + } + + @Override + public int hashCode() { + return 41 * (41 + first.hashCode()) + + (remainder == null ? 0 : remainder.hashCode()); + } + + // this doesn't have a very precise meaning, just to reduce + // noise from quotes in the rendered path for average cases + static boolean hasFunkyChars(String s) { + int length = s.length(); + + if (length == 0) + return false; + + for (int i = 0; i < length; ++i) { + char c = s.charAt(i); + + if (Character.isLetterOrDigit(c) || c == '-' || c == '_') + continue; + else + return true; + } + return false; + } + + private void appendToStringBuilder(StringBuilder sb) { + if (hasFunkyChars(first) || first.isEmpty()) + sb.append(ConfigImplUtil.renderJsonString(first)); + else + sb.append(first); + if (remainder != null) { + sb.append("."); + remainder.appendToStringBuilder(sb); + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Path("); + appendToStringBuilder(sb); + sb.append(")"); + return sb.toString(); + } + + /** + * toString() is a debugging-oriented version while this is an + * error-message-oriented human-readable one. + */ + String render() { + StringBuilder sb = new StringBuilder(); + appendToStringBuilder(sb); + return sb.toString(); + } + + static Path newKey(String key) { + return new Path(key, null); + } + + static Path newPath(String path) { + return PathParser.parsePath(path); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PathBuilder.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PathBuilder.java new file mode 100644 index 0000000..7a33f8b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PathBuilder.java @@ -0,0 +1,60 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.Stack; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; + +final class PathBuilder { + // the keys are kept "backward" (top of stack is end of path) + final private Stack keys; + private Path result; + + PathBuilder() { + keys = new Stack(); + } + + private void checkCanAppend() { + if (result != null) + throw new ConfigException.BugOrBroken( + "Adding to PathBuilder after getting result"); + } + + void appendKey(String key) { + checkCanAppend(); + + keys.push(key); + } + + void appendPath(Path path) { + checkCanAppend(); + + String first = path.first(); + Path remainder = path.remainder(); + while (true) { + keys.push(first); + if (remainder != null) { + first = remainder.first(); + remainder = remainder.remainder(); + } else { + break; + } + } + } + + Path result() { + // note: if keys is empty, we want to return null, which is a valid + // empty path + if (result == null) { + Path remainder = null; + while (!keys.isEmpty()) { + String key = keys.pop(); + remainder = new Path(key, remainder); + } + result = remainder; + } + return result; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PathParser.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PathParser.java new file mode 100644 index 0000000..51915ba --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PathParser.java @@ -0,0 +1,281 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +import java.io.StringReader; +import java.util.*; + +final class PathParser { + static class Element { + StringBuilder sb; + // an element can be empty if it has a quoted empty string "" in it + boolean canBeEmpty; + + Element(String initial, boolean canBeEmpty) { + this.canBeEmpty = canBeEmpty; + this.sb = new StringBuilder(initial); + } + + @Override + public String toString() { + return "Element(" + sb.toString() + "," + canBeEmpty + ")"; + } + } + + static ConfigOrigin apiOrigin = SimpleConfigOrigin.newSimple("path parameter"); + + static ConfigNodePath parsePathNode(String path) { + return parsePathNode(path, ConfigSyntax.CONF); + } + + static ConfigNodePath parsePathNode(String path, ConfigSyntax flavor) { + StringReader reader = new StringReader(path); + + try { + Iterator tokens = Tokenizer.tokenize(apiOrigin, reader, + flavor); + tokens.next(); // drop START + return parsePathNodeExpression(tokens, apiOrigin, path, flavor); + } finally { + reader.close(); + } + } + + static Path parsePath(String path) { + Path speculated = speculativeFastParsePath(path); + if (speculated != null) + return speculated; + + StringReader reader = new StringReader(path); + + try { + Iterator tokens = Tokenizer.tokenize(apiOrigin, reader, + ConfigSyntax.CONF); + tokens.next(); // drop START + return parsePathExpression(tokens, apiOrigin, path); + } finally { + reader.close(); + } + } + + protected static Path parsePathExpression(Iterator expression, + ConfigOrigin origin) { + return parsePathExpression(expression, origin, null, null, ConfigSyntax.CONF); + } + + protected static Path parsePathExpression(Iterator expression, + ConfigOrigin origin, String originalText) { + return parsePathExpression(expression, origin, originalText, null, ConfigSyntax.CONF); + } + + protected static ConfigNodePath parsePathNodeExpression(Iterator expression, + ConfigOrigin origin) { + return parsePathNodeExpression(expression, origin, null, ConfigSyntax.CONF); + } + + protected static ConfigNodePath parsePathNodeExpression(Iterator expression, + ConfigOrigin origin, String originalText, ConfigSyntax flavor) { + ArrayList pathTokens = new ArrayList(); + Path path = parsePathExpression(expression, origin, originalText, pathTokens, flavor); + return new ConfigNodePath(path, pathTokens); + } + + // originalText may be null if not available + protected static Path parsePathExpression(Iterator expression, + ConfigOrigin origin, String originalText, + ArrayList pathTokens, + ConfigSyntax flavor) { + // each builder in "buf" is an element in the path. + List buf = new ArrayList(); + buf.add(new Element("", false)); + + if (!expression.hasNext()) { + throw new ConfigException.BadPath(origin, originalText, + "Expecting a field name or path here, but got nothing"); + } + + while (expression.hasNext()) { + Token t = expression.next(); + + if (pathTokens != null) + pathTokens.add(t); + + // Ignore all IgnoredWhitespace tokens + if (Tokens.isIgnoredWhitespace(t)) + continue; + + if (Tokens.isValueWithType(t, ConfigValueType.STRING)) { + AbstractConfigValue v = Tokens.getValue(t); + // this is a quoted string; so any periods + // in here don't count as path separators + String s = v.transformToString(); + + addPathText(buf, true, s); + } else if (t == Tokens.END) { + // ignore this; when parsing a file, it should not happen + // since we're parsing a token list rather than the main + // token iterator, and when parsing a path expression from the + // API, it's expected to have an END. + } else { + // any periods outside of a quoted string count as + // separators + String text; + if (Tokens.isValue(t)) { + // appending a number here may add + // a period, but we _do_ count those as path + // separators, because we basically want + // "foo 3.0bar" to parse as a string even + // though there's a number in it. The fact that + // we tokenize non-string values is largely an + // implementation detail. + AbstractConfigValue v = Tokens.getValue(t); + + // We need to split the tokens on a . so that we can get sub-paths but still preserve + // the original path text when doing an insertion + if (pathTokens != null) { + pathTokens.remove(pathTokens.size() - 1); + pathTokens.addAll(splitTokenOnPeriod(t, flavor)); + } + text = v.transformToString(); + } else if (Tokens.isUnquotedText(t)) { + // We need to split the tokens on a . so that we can get sub-paths but still preserve + // the original path text when doing an insertion on ConfigNodeObjects + if (pathTokens != null) { + pathTokens.remove(pathTokens.size() - 1); + pathTokens.addAll(splitTokenOnPeriod(t, flavor)); + } + text = Tokens.getUnquotedText(t); + } else { + throw new ConfigException.BadPath( + origin, + originalText, + "Token not allowed in path expression: " + + t + + " (you can double-quote this token if you really want it here)"); + } + + addPathText(buf, false, text); + } + } + + PathBuilder pb = new PathBuilder(); + for (Element e : buf) { + if (e.sb.length() == 0 && !e.canBeEmpty) { + throw new ConfigException.BadPath( + origin, + originalText, + "path has a leading, trailing, or two adjacent period '.' (use quoted \"\" empty string if you want an empty element)"); + } else { + pb.appendKey(e.sb.toString()); + } + } + + return pb.result(); + } + + private static Collection splitTokenOnPeriod(Token t, ConfigSyntax flavor) { + String tokenText = t.tokenText(); + if (tokenText.equals(".")) { + return Collections.singletonList(t); + } + String[] splitToken = tokenText.split("\\."); + ArrayList splitTokens = new ArrayList(); + for (String s : splitToken) { + if (flavor == ConfigSyntax.CONF) + splitTokens.add(Tokens.newUnquotedText(t.origin(), s)); + else + splitTokens.add(Tokens.newString(t.origin(), s, "\"" + s + "\"")); + splitTokens.add(Tokens.newUnquotedText(t.origin(), ".")); + } + if (tokenText.charAt(tokenText.length() - 1) != '.') + splitTokens.remove(splitTokens.size() - 1); + return splitTokens; + } + + private static void addPathText(List buf, boolean wasQuoted, + String newText) { + int i = wasQuoted ? -1 : newText.indexOf('.'); + Element current = buf.get(buf.size() - 1); + if (i < 0) { + // add to current path element + current.sb.append(newText); + // any empty quoted string means this element can + // now be empty. + if (wasQuoted && current.sb.length() == 0) + current.canBeEmpty = true; + } else { + // "buf" plus up to the period is an element + current.sb.append(newText.substring(0, i)); + // then start a new element + buf.add(new Element("", false)); + // recurse to consume remainder of newText + addPathText(buf, false, newText.substring(i + 1)); + } + } + + // the idea is to see if the string has any chars or features + // that might require the full parser to deal with. + private static boolean looksUnsafeForFastParser(String s) { + boolean lastWasDot = true; // start of path is also a "dot" + int len = s.length(); + if (s.isEmpty()) + return true; + if (s.charAt(0) == '.') + return true; + if (s.charAt(len - 1) == '.') + return true; + + for (int i = 0; i < len; ++i) { + char c = s.charAt(i); + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_') { + lastWasDot = false; + continue; + } else if (c == '.') { + if (lastWasDot) + return true; // ".." means we need to throw an error + lastWasDot = true; + } else if (c == '-') { + if (lastWasDot) + return true; + continue; + } else { + return true; + } + } + + if (lastWasDot) + return true; + + return false; + } + + private static Path fastPathBuild(Path tail, String s, int end) { + // lastIndexOf takes last index it should look at, end - 1 not end + int splitAt = s.lastIndexOf('.', end - 1); + ArrayList tokens = new ArrayList(); + tokens.add(Tokens.newUnquotedText(null, s)); + // this works even if splitAt is -1; then we start the substring at 0 + Path withOneMoreElement = new Path(s.substring(splitAt + 1, end), tail); + if (splitAt < 0) { + return withOneMoreElement; + } else { + return fastPathBuild(withOneMoreElement, s, splitAt); + } + } + + // do something much faster than the full parser if + // we just have something like "foo" or "foo.bar" + private static Path speculativeFastParsePath(String path) { + String s = ConfigImplUtil.unicodeTrim(path); + if (looksUnsafeForFastParser(s)) + return null; + + return fastPathBuild(null, s, s.length()); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PropertiesParser.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PropertiesParser.java new file mode 100644 index 0000000..50e31a3 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/PropertiesParser.java @@ -0,0 +1,210 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; + +final class PropertiesParser { + static AbstractConfigObject parse(Reader reader, + ConfigOrigin origin) throws IOException { + Properties props = new Properties(); + props.load(reader); + return fromProperties(origin, props); + } + + static String lastElement(String path) { + int i = path.lastIndexOf('.'); + if (i < 0) + return path; + else + return path.substring(i + 1); + } + + static String exceptLastElement(String path) { + int i = path.lastIndexOf('.'); + if (i < 0) + return null; + else + return path.substring(0, i); + } + + static Path pathFromPropertyKey(String key) { + String last = lastElement(key); + String exceptLast = exceptLastElement(key); + Path path = new Path(last, null); + while (exceptLast != null) { + last = lastElement(exceptLast); + exceptLast = exceptLastElement(exceptLast); + path = new Path(last, path); + } + return path; + } + + static AbstractConfigObject fromProperties(ConfigOrigin origin, + Properties props) { + return fromEntrySet(origin, props.entrySet()); + } + + private static AbstractConfigObject fromEntrySet(ConfigOrigin origin, Set> entries) { + final Map pathMap = getPathMap(entries); + return fromPathMap(origin, pathMap, true /* from properties */); + } + + private static Map getPathMap(Set> entries) { + Map pathMap = new HashMap(); + for (Map.Entry entry : entries) { + Object key = entry.getKey(); + if (key instanceof String) { + Path path = pathFromPropertyKey((String) key); + pathMap.put(path, entry.getValue()); + } + } + return pathMap; + } + + static AbstractConfigObject fromStringMap(ConfigOrigin origin, Map stringMap) { + return fromEntrySet(origin, stringMap.entrySet()); + } + + static AbstractConfigObject fromPathMap(ConfigOrigin origin, + Map pathExpressionMap) { + Map pathMap = new HashMap(); + for (Map.Entry entry : pathExpressionMap.entrySet()) { + Object keyObj = entry.getKey(); + if (!(keyObj instanceof String)) { + throw new ConfigException.BugOrBroken( + "Map has a non-string as a key, expecting a path expression as a String"); + } + Path path = Path.newPath((String) keyObj); + pathMap.put(path, entry.getValue()); + } + return fromPathMap(origin, pathMap, false /* from properties */); + } + + private static AbstractConfigObject fromPathMap(ConfigOrigin origin, + Map pathMap, boolean convertedFromProperties) { + /* + * First, build a list of paths that will have values, either string or + * object values. + */ + Set scopePaths = new HashSet(); + Set valuePaths = new HashSet(); + for (Path path : pathMap.keySet()) { + // add value's path + valuePaths.add(path); + + // all parent paths are objects + Path next = path.parent(); + while (next != null) { + scopePaths.add(next); + next = next.parent(); + } + } + + if (convertedFromProperties) { + /* + * If any string values are also objects containing other values, + * drop those string values - objects "win". + */ + valuePaths.removeAll(scopePaths); + } else { + /* If we didn't start out as properties, then this is an error. */ + for (Path path : valuePaths) { + if (scopePaths.contains(path)) { + throw new ConfigException.BugOrBroken( + "In the map, path '" + + path.render() + + "' occurs as both the parent object of a value and as a value. " + + "Because Map has no defined ordering, this is a broken situation."); + } + } + } + + /* + * Create maps for the object-valued values. + */ + Map root = new HashMap(); + Map> scopes = new HashMap>(); + + for (Path path : scopePaths) { + Map scope = new HashMap(); + scopes.put(path, scope); + } + + /* Store string values in the associated scope maps */ + for (Path path : valuePaths) { + Path parentPath = path.parent(); + Map parent = parentPath != null ? scopes + .get(parentPath) : root; + + String last = path.last(); + Object rawValue = pathMap.get(path); + AbstractConfigValue value; + if (convertedFromProperties) { + if (rawValue instanceof String) { + value = new ConfigString.Quoted(origin, (String) rawValue); + } else { + // silently ignore non-string values in Properties + value = null; + } + } else { + value = ConfigImpl.fromAnyRef(pathMap.get(path), origin, + FromMapMode.KEYS_ARE_PATHS); + } + if (value != null) + parent.put(last, value); + } + + /* + * Make a list of scope paths from longest to shortest, so children go + * before parents. + */ + List sortedScopePaths = new ArrayList(); + sortedScopePaths.addAll(scopePaths); + // sort descending by length + Collections.sort(sortedScopePaths, new Comparator() { + @Override + public int compare(Path a, Path b) { + // Path.length() is O(n) so in theory this sucks + // but in practice we can make Path precompute length + // if it ever matters. + return b.length() - a.length(); + } + }); + + /* + * Create ConfigObject for each scope map, working from children to + * parents to avoid modifying any already-created ConfigObject. This is + * where we need the sorted list. + */ + for (Path scopePath : sortedScopePaths) { + Map scope = scopes.get(scopePath); + + Path parentPath = scopePath.parent(); + Map parent = parentPath != null ? scopes + .get(parentPath) : root; + + AbstractConfigObject o = new SimpleConfigObject(origin, scope, + ResolveStatus.RESOLVED, false /* ignoresFallbacks */); + parent.put(scopePath.last(), o); + } + + // return root config object + return new SimpleConfigObject(origin, root, ResolveStatus.RESOLVED, + false /* ignoresFallbacks */); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ReplaceableMergeStack.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ReplaceableMergeStack.java new file mode 100644 index 0000000..bde6e41 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ReplaceableMergeStack.java @@ -0,0 +1,14 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +/** + * Implemented by a merge stack (ConfigDelayedMerge, ConfigDelayedMergeObject) + * that replaces itself during substitution resolution in order to implement + * "look backwards only" semantics. + */ +interface ReplaceableMergeStack extends Container { + /** + * Make a replacement for this object skipping the given number of elements + * which are lower in merge priority. + */ + AbstractConfigValue makeReplacement(ResolveContext context, int skipping); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveContext.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveContext.java new file mode 100644 index 0000000..4f1ef72 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveContext.java @@ -0,0 +1,237 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Set; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigResolveOptions; + +final class ResolveContext { + final private ResolveMemos memos; + + final private ConfigResolveOptions options; + // the current path restriction, used to ensure lazy + // resolution and avoid gratuitous cycles. without this, + // any sibling of an object we're traversing could + // cause a cycle "by side effect" + // CAN BE NULL for a full resolve. + final private Path restrictToChild; + + // This is used for tracing and debugging and nice error messages; + // contains every node as we call resolve on it. + final private List resolveStack; + + final private Set cycleMarkers; + + ResolveContext(ResolveMemos memos, ConfigResolveOptions options, Path restrictToChild, + List resolveStack, Set cycleMarkers) { + this.memos = memos; + this.options = options; + this.restrictToChild = restrictToChild; + this.resolveStack = Collections.unmodifiableList(resolveStack); + this.cycleMarkers = Collections.unmodifiableSet(cycleMarkers); + } + + private static Set newCycleMarkers() { + return Collections.newSetFromMap(new IdentityHashMap()); + } + + ResolveContext(ConfigResolveOptions options, Path restrictToChild) { + // LinkedHashSet keeps the traversal order which is at least useful + // in error messages if nothing else + this(new ResolveMemos(), options, restrictToChild, new ArrayList(), newCycleMarkers()); + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "ResolveContext restrict to child " + restrictToChild); + } + + ResolveContext addCycleMarker(AbstractConfigValue value) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "++ Cycle marker " + value + "@" + System.identityHashCode(value)); + if (cycleMarkers.contains(value)) + throw new ConfigException.BugOrBroken("Added cycle marker twice " + value); + Set copy = newCycleMarkers(); + copy.addAll(cycleMarkers); + copy.add(value); + return new ResolveContext(memos, options, restrictToChild, resolveStack, copy); + } + + ResolveContext removeCycleMarker(AbstractConfigValue value) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "-- Cycle marker " + value + "@" + System.identityHashCode(value)); + + Set copy = newCycleMarkers(); + copy.addAll(cycleMarkers); + copy.remove(value); + return new ResolveContext(memos, options, restrictToChild, resolveStack, copy); + } + + private ResolveContext memoize(MemoKey key, AbstractConfigValue value) { + ResolveMemos changed = memos.put(key, value); + return new ResolveContext(changed, options, restrictToChild, resolveStack, cycleMarkers); + } + + ConfigResolveOptions options() { + return options; + } + + boolean isRestrictedToChild() { + return restrictToChild != null; + } + + Path restrictToChild() { + return restrictToChild; + } + + // restrictTo may be null to unrestrict + ResolveContext restrict(Path restrictTo) { + if (restrictTo == restrictToChild) + return this; + else + return new ResolveContext(memos, options, restrictTo, resolveStack, cycleMarkers); + } + + ResolveContext unrestricted() { + return restrict(null); + } + + String traceString() { + String separator = ", "; + StringBuilder sb = new StringBuilder(); + for (AbstractConfigValue value : resolveStack) { + if (value instanceof ConfigReference) { + sb.append(((ConfigReference) value).expression().toString()); + sb.append(separator); + } + } + if (sb.length() > 0) + sb.setLength(sb.length() - separator.length()); + return sb.toString(); + } + + private ResolveContext pushTrace(AbstractConfigValue value) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "pushing trace " + value); + List copy = new ArrayList(resolveStack); + copy.add(value); + return new ResolveContext(memos, options, restrictToChild, copy, cycleMarkers); + } + + ResolveContext popTrace() { + List copy = new ArrayList(resolveStack); + AbstractConfigValue old = copy.remove(resolveStack.size() - 1); + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth() - 1, "popped trace " + old); + return new ResolveContext(memos, options, restrictToChild, copy, cycleMarkers); + } + + int depth() { + if (resolveStack.size() > 30) + throw new ConfigException.BugOrBroken("resolve getting too deep"); + return resolveStack.size(); + } + + ResolveResult resolve(AbstractConfigValue original, ResolveSource source) + throws AbstractConfigValue.NotPossibleToResolve { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl + .trace(depth(), "resolving " + original + " restrictToChild=" + restrictToChild + " in " + source); + return pushTrace(original).realResolve(original, source).popTrace(); + } + + private ResolveResult realResolve(AbstractConfigValue original, ResolveSource source) + throws AbstractConfigValue.NotPossibleToResolve { + // a fully-resolved (no restrictToChild) object can satisfy a + // request for a restricted object, so always check that first. + final MemoKey fullKey = new MemoKey(original, null); + MemoKey restrictedKey = null; + + AbstractConfigValue cached = memos.get(fullKey); + + // but if there was no fully-resolved object cached, we'll only + // compute the restrictToChild object so use a more limited + // memo key + if (cached == null && isRestrictedToChild()) { + restrictedKey = new MemoKey(original, restrictToChild()); + cached = memos.get(restrictedKey); + } + + if (cached != null) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "using cached resolution " + cached + " for " + original + + " restrictToChild " + restrictToChild()); + return ResolveResult.make(this, cached); + } else { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), + "not found in cache, resolving " + original + "@" + System.identityHashCode(original)); + + if (cycleMarkers.contains(original)) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), + "Cycle detected, can't resolve; " + original + "@" + System.identityHashCode(original)); + throw new AbstractConfigValue.NotPossibleToResolve(this); + } + + ResolveResult result = original.resolveSubstitutions(this, source); + AbstractConfigValue resolved = result.value; + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "resolved to " + resolved + "@" + System.identityHashCode(resolved) + + " from " + original + "@" + System.identityHashCode(resolved)); + + ResolveContext withMemo = result.context; + + if (resolved == null || resolved.resolveStatus() == ResolveStatus.RESOLVED) { + // if the resolved object is fully resolved by resolving + // only the restrictToChildOrNull, then it can be cached + // under fullKey since the child we were restricted to + // turned out to be the only unresolved thing. + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "caching " + fullKey + " result " + resolved); + + withMemo = withMemo.memoize(fullKey, resolved); + } else { + // if we have an unresolved object then either we did a + // partial resolve restricted to a certain child, or we are + // allowing incomplete resolution, or it's a bug. + if (isRestrictedToChild()) { + if (restrictedKey == null) { + throw new ConfigException.BugOrBroken( + "restrictedKey should not be null here"); + } + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "caching " + restrictedKey + " result " + resolved); + + withMemo = withMemo.memoize(restrictedKey, resolved); + } else if (options().getAllowUnresolved()) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(depth(), "caching " + fullKey + " result " + resolved); + + withMemo = withMemo.memoize(fullKey, resolved); + } else { + throw new ConfigException.BugOrBroken( + "resolveSubstitutions() did not give us a resolved object"); + } + } + + return ResolveResult.make(withMemo, resolved); + } + } + + static AbstractConfigValue resolve(AbstractConfigValue value, AbstractConfigObject root, + ConfigResolveOptions options) { + ResolveSource source = new ResolveSource(root); + ResolveContext context = new ResolveContext(options, null /* restrictToChild */); + + try { + return context.resolve(value, source).value; + } catch (AbstractConfigValue.NotPossibleToResolve e) { + // ConfigReference was supposed to catch NotPossibleToResolve + throw new ConfigException.BugOrBroken( + "NotPossibleToResolve was thrown from an outermost resolve", e); + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveMemos.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveMemos.java new file mode 100644 index 0000000..6f5049b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveMemos.java @@ -0,0 +1,35 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.HashMap; +import java.util.Map; + +/** + * This exists because we have to memoize resolved substitutions as we go + * through the config tree; otherwise we could end up creating multiple copies + * of values or whole trees of values as we follow chains of substitutions. + */ +final class ResolveMemos { + // note that we can resolve things to undefined (represented as Java null, + // rather than ConfigNull) so this map can have null values. + final private Map memos; + + private ResolveMemos(Map memos) { + this.memos = memos; + } + + ResolveMemos() { + this(new HashMap()); + } + + AbstractConfigValue get(MemoKey key) { + return memos.get(key); + } + + ResolveMemos put(MemoKey key, AbstractConfigValue value) { + // completely inefficient, but so far nobody cares about resolve() + // performance, we can clean it up someday... + Map copy = new HashMap(memos); + copy.put(key, value); + return new ResolveMemos(copy); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveResult.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveResult.java new file mode 100644 index 0000000..5dd63e0 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveResult.java @@ -0,0 +1,43 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; + +// value is allowed to be null +final class ResolveResult { + public final ResolveContext context; + public final V value; + + private ResolveResult(ResolveContext context, V value) { + this.context = context; + this.value = value; + } + + static ResolveResult make(ResolveContext context, V value) { + return new ResolveResult(context, value); + } + + // better option? we don't have variance + @SuppressWarnings("unchecked") + ResolveResult asObjectResult() { + if (!(value instanceof AbstractConfigObject)) + throw new ConfigException.BugOrBroken("Expecting a resolve result to be an object, but it was " + value); + Object o = this; + return (ResolveResult) o; + } + + // better option? we don't have variance + @SuppressWarnings("unchecked") + ResolveResult asValueResult() { + Object o = this; + return (ResolveResult) o; + } + + ResolveResult popTrace() { + return make(context.popTrace(), value); + } + + @Override + public String toString() { + return "ResolveResult(" + value + ")"; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveSource.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveSource.java new file mode 100644 index 0000000..1f81c8b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveSource.java @@ -0,0 +1,349 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; + +/** + * This class is the source for values for a substitution like ${foo}. + */ +final class ResolveSource { + + final AbstractConfigObject root; + // This is used for knowing the chain of parents we used to get here. + // null if we should assume we are not a descendant of the root. + // the root itself should be a node in this if non-null. + final Node pathFromRoot; + + ResolveSource(AbstractConfigObject root, Node pathFromRoot) { + this.root = root; + this.pathFromRoot = pathFromRoot; + } + + ResolveSource(AbstractConfigObject root) { + this.root = root; + this.pathFromRoot = null; + } + + // if we replace the root with a non-object, use an empty + // object with nothing in it instead. + private AbstractConfigObject rootMustBeObj(Container value) { + if (value instanceof AbstractConfigObject) { + return (AbstractConfigObject) value; + } else { + return SimpleConfigObject.empty(); + } + } + + // as a side effect, findInObject() will have to resolve all parents of the + // child being peeked, but NOT the child itself. Caller has to resolve + // the child itself if needed. ValueWithPath.value can be null but + // the ValueWithPath instance itself should not be. + static private ResultWithPath findInObject(AbstractConfigObject obj, ResolveContext context, Path path) + throws AbstractConfigValue.NotPossibleToResolve { + // resolve ONLY portions of the object which are along our path + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace("*** finding '" + path + "' in " + obj); + Path restriction = context.restrictToChild(); + ResolveResult partiallyResolved = context.restrict(path).resolve(obj, + new ResolveSource(obj)); + ResolveContext newContext = partiallyResolved.context.restrict(restriction); + if (partiallyResolved.value instanceof AbstractConfigObject) { + ValueWithPath pair = findInObject((AbstractConfigObject) partiallyResolved.value, path); + return new ResultWithPath(ResolveResult.make(newContext, pair.value), pair.pathFromRoot); + } else { + throw new ConfigException.BugOrBroken("resolved object to non-object " + obj + " to " + partiallyResolved); + } + } + + static private ValueWithPath findInObject(AbstractConfigObject obj, Path path) { + try { + // we'll fail if anything along the path can't + // be looked at without resolving. + return findInObject(obj, path, null); + } catch (ConfigException.NotResolved e) { + throw ConfigImpl.improveNotResolved(path, e); + } + } + + static private ValueWithPath findInObject(AbstractConfigObject obj, Path path, Node parents) { + String key = path.first(); + Path next = path.remainder(); + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace("*** looking up '" + key + "' in " + obj); + AbstractConfigValue v = obj.attemptPeekWithPartialResolve(key); + Node newParents = parents == null ? new Node(obj) : parents.prepend(obj); + + if (next == null) { + return new ValueWithPath(v, newParents); + } else { + if (v instanceof AbstractConfigObject) { + return findInObject((AbstractConfigObject) v, next, newParents); + } else { + return new ValueWithPath(null, newParents); + } + } + } + + ResultWithPath lookupSubst(ResolveContext context, SubstitutionExpression subst, + int prefixLength) + throws AbstractConfigValue.NotPossibleToResolve { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(context.depth(), "searching for " + subst); + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(context.depth(), subst + " - looking up relative to file it occurred in"); + // First we look up the full path, which means relative to the + // included file if we were not a root file + ResultWithPath result = findInObject(root, context, subst.path()); + + if (result.result.value == null) { + // Then we want to check relative to the root file. We don't + // want the prefix we were included at to be used when looking + // up env variables either. + Path unprefixed = subst.path().subPath(prefixLength); + + if (prefixLength > 0) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(result.result.context.depth(), unprefixed + + " - looking up relative to parent file"); + result = findInObject(root, result.result.context, unprefixed); + } + + if (result.result.value == null && result.result.context.options().getUseSystemEnvironment()) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(result.result.context.depth(), unprefixed + " - looking up in system environment"); + result = findInObject(ConfigImpl.envVariablesAsConfigObject(), context, unprefixed); + } + } + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace(result.result.context.depth(), "resolved to " + result); + + return result; + } + + ResolveSource pushParent(Container parent) { + if (parent == null) + throw new ConfigException.BugOrBroken("can't push null parent"); + + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace("pushing parent " + parent + " ==root " + (parent == root) + " onto " + this); + + if (pathFromRoot == null) { + if (parent == root) { + return new ResolveSource(root, new Node(parent)); + } else { + if (ConfigImpl.traceSubstitutionsEnabled()) { + // this hasDescendant check is super-expensive so it's a + // trace message rather than an assertion + if (root.hasDescendant((AbstractConfigValue) parent)) + ConfigImpl.trace("***** BUG ***** tried to push parent " + parent + + " without having a path to it in " + this); + } + // ignore parents if we aren't proceeding from the + // root + return this; + } + } else { + Container parentParent = pathFromRoot.head(); + if (ConfigImpl.traceSubstitutionsEnabled()) { + // this hasDescendant check is super-expensive so it's a + // trace message rather than an assertion + if (parentParent != null && !parentParent.hasDescendant((AbstractConfigValue) parent)) + ConfigImpl.trace("***** BUG ***** trying to push non-child of " + parentParent + ", non-child was " + + parent); + } + + return new ResolveSource(root, pathFromRoot.prepend(parent)); + } + } + + ResolveSource resetParents() { + if (pathFromRoot == null) + return this; + else + return new ResolveSource(root); + } + + // returns null if the replacement results in deleting all the nodes. + private static Node replace(Node list, Container old, AbstractConfigValue replacement) { + Container child = list.head(); + if (child != old) + throw new ConfigException.BugOrBroken("Can only replace() the top node we're resolving; had " + child + + " on top and tried to replace " + old + " overall list was " + list); + Container parent = list.tail() == null ? null : list.tail().head(); + if (replacement == null || !(replacement instanceof Container)) { + if (parent == null) { + return null; + } else { + /* + * we are deleting the child from the stack of containers + * because it's either going away or not a container + */ + AbstractConfigValue newParent = parent.replaceChild((AbstractConfigValue) old, null); + + return replace(list.tail(), parent, newParent); + } + } else { + /* we replaced the container with another container */ + if (parent == null) { + return new Node((Container) replacement); + } else { + AbstractConfigValue newParent = parent.replaceChild((AbstractConfigValue) old, replacement); + Node newTail = replace(list.tail(), parent, newParent); + if (newTail != null) + return newTail.prepend((Container) replacement); + else + return new Node((Container) replacement); + } + } + } + + ResolveSource replaceCurrentParent(Container old, Container replacement) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace("replaceCurrentParent old " + old + "@" + System.identityHashCode(old) + " replacement " + + replacement + "@" + System.identityHashCode(old) + " in " + this); + if (old == replacement) { + return this; + } else if (pathFromRoot != null) { + Node newPath = replace(pathFromRoot, old, (AbstractConfigValue) replacement); + if (ConfigImpl.traceSubstitutionsEnabled()) { + ConfigImpl.trace("replaced " + old + " with " + replacement + " in " + this); + ConfigImpl.trace("path was: " + pathFromRoot + " is now " + newPath); + } + // if we end up nuking the root object itself, we replace it with an + // empty root + if (newPath != null) + return new ResolveSource((AbstractConfigObject) newPath.last(), newPath); + else + return new ResolveSource(SimpleConfigObject.empty()); + } else { + if (old == root) { + return new ResolveSource(rootMustBeObj(replacement)); + } else { + throw new ConfigException.BugOrBroken("attempt to replace root " + root + " with " + replacement); + // return this; + } + } + } + + // replacement may be null to delete + ResolveSource replaceWithinCurrentParent(AbstractConfigValue old, AbstractConfigValue replacement) { + if (ConfigImpl.traceSubstitutionsEnabled()) + ConfigImpl.trace("replaceWithinCurrentParent old " + old + "@" + System.identityHashCode(old) + + " replacement " + replacement + "@" + System.identityHashCode(old) + " in " + this); + if (old == replacement) { + return this; + } else if (pathFromRoot != null) { + Container parent = pathFromRoot.head(); + AbstractConfigValue newParent = parent.replaceChild(old, replacement); + return replaceCurrentParent(parent, (newParent instanceof Container) ? (Container) newParent : null); + } else { + if (old == root && replacement instanceof Container) { + return new ResolveSource(rootMustBeObj((Container) replacement)); + } else { + throw new ConfigException.BugOrBroken("replace in parent not possible " + old + " with " + replacement + + " in " + this); + // return this; + } + } + } + + @Override + public String toString() { + return "ResolveSource(root=" + root + ", pathFromRoot=" + pathFromRoot + ")"; + } + + // a persistent list + static final class Node { + final T value; + final Node next; + + Node(T value, Node next) { + this.value = value; + this.next = next; + } + + Node(T value) { + this(value, null); + } + + Node prepend(T value) { + return new Node(value, this); + } + + T head() { + return value; + } + + Node tail() { + return next; + } + + T last() { + Node i = this; + while (i.next != null) + i = i.next; + return i.value; + } + + Node reverse() { + if (next == null) { + return this; + } else { + Node reversed = new Node(value); + Node i = next; + while (i != null) { + reversed = reversed.prepend(i.value); + i = i.next; + } + return reversed; + } + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("["); + Node toAppendValue = this.reverse(); + while (toAppendValue != null) { + sb.append(toAppendValue.value.toString()); + if (toAppendValue.next != null) + sb.append(" <= "); + toAppendValue = toAppendValue.next; + } + sb.append("]"); + return sb.toString(); + } + } + + // value is allowed to be null + static final class ValueWithPath { + final AbstractConfigValue value; + final Node pathFromRoot; + + ValueWithPath(AbstractConfigValue value, Node pathFromRoot) { + this.value = value; + this.pathFromRoot = pathFromRoot; + } + + @Override + public String toString() { + return "ValueWithPath(value=" + value + ", pathFromRoot=" + pathFromRoot + ")"; + } + } + + static final class ResultWithPath { + final ResolveResult result; + final Node pathFromRoot; + + ResultWithPath(ResolveResult result, Node pathFromRoot) { + this.result = result; + this.pathFromRoot = pathFromRoot; + } + + @Override + public String toString() { + return "ResultWithPath(result=" + result + ", pathFromRoot=" + pathFromRoot + ")"; + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveStatus.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveStatus.java new file mode 100644 index 0000000..27eef3b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/ResolveStatus.java @@ -0,0 +1,26 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.Collection; + +/** + * Status of substitution resolution. + */ +enum ResolveStatus { + UNRESOLVED, RESOLVED; + + final static ResolveStatus fromValues( + Collection values) { + for (AbstractConfigValue v : values) { + if (v.resolveStatus() == ResolveStatus.UNRESOLVED) + return ResolveStatus.UNRESOLVED; + } + return ResolveStatus.RESOLVED; + } + + final static ResolveStatus fromBoolean(boolean resolved) { + return resolved ? ResolveStatus.RESOLVED : ResolveStatus.UNRESOLVED; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SerializedConfigValue.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SerializedConfigValue.java new file mode 100644 index 0000000..f159f7f --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SerializedConfigValue.java @@ -0,0 +1,534 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.io.Externalizable; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.io.ObjectStreamException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.drtshock.playervaults.lib.com.typesafe.config.Config; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigList; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +/** + * Deliberately shoving all the serialization code into this class instead of + * doing it OO-style with each subclass. Seems better to have it all in one + * place. This class implements a lame serialization format that supports + * skipping unknown fields, so it's moderately more extensible than the default + * Java serialization format. + */ +class SerializedConfigValue extends AbstractConfigValue implements Externalizable { + + // this is the version used by Java serialization, if it increments it's + // essentially an ABI break and bad + private static final long serialVersionUID = 1L; + + // this is how we try to be extensible + static enum SerializedField { + // represents a field code we didn't recognize + UNKNOWN, + + // end of a list of fields + END_MARKER, + + // Fields at the root + ROOT_VALUE, + ROOT_WAS_CONFIG, + + // Fields that make up a value + VALUE_DATA, + VALUE_ORIGIN, + + // Fields that make up an origin + ORIGIN_DESCRIPTION, + ORIGIN_LINE_NUMBER, + ORIGIN_END_LINE_NUMBER, + ORIGIN_TYPE, + ORIGIN_URL, + ORIGIN_COMMENTS, + ORIGIN_NULL_URL, + ORIGIN_NULL_COMMENTS, + ORIGIN_RESOURCE, + ORIGIN_NULL_RESOURCE; + + static SerializedField forInt(int b) { + if (b < values().length) + return values()[b]; + else + return UNKNOWN; + } + }; + + private static enum SerializedValueType { + // the ordinals here are in the wire format, caution + NULL(ConfigValueType.NULL), + BOOLEAN(ConfigValueType.BOOLEAN), + INT(ConfigValueType.NUMBER), + LONG(ConfigValueType.NUMBER), + DOUBLE(ConfigValueType.NUMBER), + STRING(ConfigValueType.STRING), + LIST(ConfigValueType.LIST), + OBJECT(ConfigValueType.OBJECT); + + ConfigValueType configType; + + SerializedValueType(ConfigValueType configType) { + this.configType = configType; + } + + static SerializedValueType forInt(int b) { + if (b < values().length) + return values()[b]; + else + return null; + } + + static SerializedValueType forValue(ConfigValue value) { + ConfigValueType t = value.valueType(); + if (t == ConfigValueType.NUMBER) { + if (value instanceof ConfigInt) + return INT; + else if (value instanceof ConfigLong) + return LONG; + else if (value instanceof ConfigDouble) + return DOUBLE; + } else { + for (SerializedValueType st : values()) { + if (st.configType == t) + return st; + } + } + + throw new ConfigException.BugOrBroken("don't know how to serialize " + value); + } + }; + + private ConfigValue value; + private boolean wasConfig; + + // this has to be public for the Java deserializer + public SerializedConfigValue() { + super(null); + } + + SerializedConfigValue(ConfigValue value) { + this(); + this.value = value; + this.wasConfig = false; + } + + SerializedConfigValue(Config conf) { + this(conf.root()); + this.wasConfig = true; + } + + // when Java deserializer reads this object, return the contained + // object instead. + private Object readResolve() throws ObjectStreamException { + if (wasConfig) + return ((ConfigObject) value).toConfig(); + else + return value; + } + + private static class FieldOut { + final SerializedField code; + final ByteArrayOutputStream bytes; + final DataOutput data; + + FieldOut(SerializedField code) { + this.code = code; + this.bytes = new ByteArrayOutputStream(); + this.data = new DataOutputStream(bytes); + } + } + + // this is a separate function to prevent bugs writing to the + // outer stream instead of field.data + private static void writeOriginField(DataOutput out, SerializedField code, Object v) + throws IOException { + switch (code) { + case ORIGIN_DESCRIPTION: + out.writeUTF((String) v); + break; + case ORIGIN_LINE_NUMBER: + out.writeInt((Integer) v); + break; + case ORIGIN_END_LINE_NUMBER: + out.writeInt((Integer) v); + break; + case ORIGIN_TYPE: + out.writeByte((Integer) v); + break; + case ORIGIN_URL: + out.writeUTF((String) v); + break; + case ORIGIN_RESOURCE: + out.writeUTF((String) v); + break; + case ORIGIN_COMMENTS: + @SuppressWarnings("unchecked") + List list = (List) v; + int size = list.size(); + out.writeInt(size); + for (String s : list) { + out.writeUTF(s); + } + break; + case ORIGIN_NULL_URL: // FALL THRU + case ORIGIN_NULL_RESOURCE: // FALL THRU + case ORIGIN_NULL_COMMENTS: + // nothing to write out besides code and length + break; + default: + throw new IOException("Unhandled field from origin: " + code); + } + } + + // not private because we use it to serialize ConfigException + static void writeOrigin(DataOutput out, SimpleConfigOrigin origin, + SimpleConfigOrigin baseOrigin) throws IOException { + Map m; + // to serialize a null origin, we write out no fields at all + if (origin != null) + m = origin.toFieldsDelta(baseOrigin); + else + m = Collections.emptyMap(); + for (Map.Entry e : m.entrySet()) { + FieldOut field = new FieldOut(e.getKey()); + Object v = e.getValue(); + writeOriginField(field.data, field.code, v); + writeField(out, field); + } + writeEndMarker(out); + } + + // not private because we use it to deserialize ConfigException + static SimpleConfigOrigin readOrigin(DataInput in, SimpleConfigOrigin baseOrigin) + throws IOException { + Map m = new EnumMap(SerializedField.class); + while (true) { + Object v = null; + SerializedField field = readCode(in); + switch (field) { + case END_MARKER: + return SimpleConfigOrigin.fromBase(baseOrigin, m); + case ORIGIN_DESCRIPTION: + in.readInt(); // discard length + v = in.readUTF(); + break; + case ORIGIN_LINE_NUMBER: + in.readInt(); // discard length + v = in.readInt(); + break; + case ORIGIN_END_LINE_NUMBER: + in.readInt(); // discard length + v = in.readInt(); + break; + case ORIGIN_TYPE: + in.readInt(); // discard length + v = in.readUnsignedByte(); + break; + case ORIGIN_URL: + in.readInt(); // discard length + v = in.readUTF(); + break; + case ORIGIN_RESOURCE: + in.readInt(); // discard length + v = in.readUTF(); + break; + case ORIGIN_COMMENTS: + in.readInt(); // discard length + int size = in.readInt(); + List list = new ArrayList(size); + for (int i = 0; i < size; ++i) { + list.add(in.readUTF()); + } + v = list; + break; + case ORIGIN_NULL_URL: // FALL THRU + case ORIGIN_NULL_RESOURCE: // FALL THRU + case ORIGIN_NULL_COMMENTS: + // nothing to read besides code and length + in.readInt(); // discard length + v = ""; // just something non-null to put in the map + break; + case ROOT_VALUE: + case ROOT_WAS_CONFIG: + case VALUE_DATA: + case VALUE_ORIGIN: + throw new IOException("Not expecting this field here: " + field); + case UNKNOWN: + // skip unknown field + skipField(in); + break; + } + if (v != null) + m.put(field, v); + } + } + + private static void writeValueData(DataOutput out, ConfigValue value) throws IOException { + SerializedValueType st = SerializedValueType.forValue(value); + out.writeByte(st.ordinal()); + switch (st) { + case BOOLEAN: + out.writeBoolean(((ConfigBoolean) value).unwrapped()); + break; + case NULL: + break; + case INT: + // saving numbers as both string and binary is redundant but easy + out.writeInt(((ConfigInt) value).unwrapped()); + out.writeUTF(((ConfigNumber) value).transformToString()); + break; + case LONG: + out.writeLong(((ConfigLong) value).unwrapped()); + out.writeUTF(((ConfigNumber) value).transformToString()); + break; + case DOUBLE: + out.writeDouble(((ConfigDouble) value).unwrapped()); + out.writeUTF(((ConfigNumber) value).transformToString()); + break; + case STRING: + out.writeUTF(((ConfigString) value).unwrapped()); + break; + case LIST: + ConfigList list = (ConfigList) value; + out.writeInt(list.size()); + for (ConfigValue v : list) { + writeValue(out, v, (SimpleConfigOrigin) list.origin()); + } + break; + case OBJECT: + ConfigObject obj = (ConfigObject) value; + out.writeInt(obj.size()); + for (Map.Entry e : obj.entrySet()) { + out.writeUTF(e.getKey()); + writeValue(out, e.getValue(), (SimpleConfigOrigin) obj.origin()); + } + break; + } + } + + private static AbstractConfigValue readValueData(DataInput in, SimpleConfigOrigin origin) + throws IOException { + int stb = in.readUnsignedByte(); + SerializedValueType st = SerializedValueType.forInt(stb); + if (st == null) + throw new IOException("Unknown serialized value type: " + stb); + switch (st) { + case BOOLEAN: + return new ConfigBoolean(origin, in.readBoolean()); + case NULL: + return new ConfigNull(origin); + case INT: + int vi = in.readInt(); + String si = in.readUTF(); + return new ConfigInt(origin, vi, si); + case LONG: + long vl = in.readLong(); + String sl = in.readUTF(); + return new ConfigLong(origin, vl, sl); + case DOUBLE: + double vd = in.readDouble(); + String sd = in.readUTF(); + return new ConfigDouble(origin, vd, sd); + case STRING: + return new ConfigString.Quoted(origin, in.readUTF()); + case LIST: + int listSize = in.readInt(); + List list = new ArrayList(listSize); + for (int i = 0; i < listSize; ++i) { + AbstractConfigValue v = readValue(in, origin); + list.add(v); + } + return new SimpleConfigList(origin, list); + case OBJECT: + int mapSize = in.readInt(); + Map map = new HashMap(mapSize); + for (int i = 0; i < mapSize; ++i) { + String key = in.readUTF(); + AbstractConfigValue v = readValue(in, origin); + map.put(key, v); + } + return new SimpleConfigObject(origin, map); + } + throw new IOException("Unhandled serialized value type: " + st); + } + + private static void writeValue(DataOutput out, ConfigValue value, SimpleConfigOrigin baseOrigin) + throws IOException { + FieldOut origin = new FieldOut(SerializedField.VALUE_ORIGIN); + writeOrigin(origin.data, (SimpleConfigOrigin) value.origin(), + baseOrigin); + writeField(out, origin); + + FieldOut data = new FieldOut(SerializedField.VALUE_DATA); + writeValueData(data.data, value); + writeField(out, data); + + writeEndMarker(out); + } + + private static AbstractConfigValue readValue(DataInput in, SimpleConfigOrigin baseOrigin) + throws IOException { + AbstractConfigValue value = null; + SimpleConfigOrigin origin = null; + while (true) { + SerializedField code = readCode(in); + if (code == SerializedField.END_MARKER) { + if (value == null) + throw new IOException("No value data found in serialization of value"); + return value; + } else if (code == SerializedField.VALUE_DATA) { + if (origin == null) + throw new IOException("Origin must be stored before value data"); + in.readInt(); // discard length + value = readValueData(in, origin); + } else if (code == SerializedField.VALUE_ORIGIN) { + in.readInt(); // discard length + origin = readOrigin(in, baseOrigin); + } else { + // ignore unknown field + skipField(in); + } + } + } + + private static void writeField(DataOutput out, FieldOut field) throws IOException { + byte[] bytes = field.bytes.toByteArray(); + out.writeByte(field.code.ordinal()); + out.writeInt(bytes.length); + out.write(bytes); + } + + private static void writeEndMarker(DataOutput out) throws IOException { + out.writeByte(SerializedField.END_MARKER.ordinal()); + } + + private static SerializedField readCode(DataInput in) throws IOException { + int c = in.readUnsignedByte(); + if (c == SerializedField.UNKNOWN.ordinal()) + throw new IOException("field code " + c + " is not supposed to be on the wire"); + return SerializedField.forInt(c); + } + + private static void skipField(DataInput in) throws IOException { + int len = in.readInt(); + // skipBytes doesn't have to block + int skipped = in.skipBytes(len); + if (skipped < len) { + // wastefully use readFully() if skipBytes didn't work + byte[] bytes = new byte[(len - skipped)]; + in.readFully(bytes); + } + } + + @Override + public void writeExternal(ObjectOutput out) throws IOException { + if (((AbstractConfigValue) value).resolveStatus() != ResolveStatus.RESOLVED) + throw new NotSerializableException( + "tried to serialize a value with unresolved substitutions, need to Config#resolve() first, see API docs"); + FieldOut field = new FieldOut(SerializedField.ROOT_VALUE); + writeValue(field.data, value, null /* baseOrigin */); + writeField(out, field); + + field = new FieldOut(SerializedField.ROOT_WAS_CONFIG); + field.data.writeBoolean(wasConfig); + writeField(out, field); + + writeEndMarker(out); + } + + @Override + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + while (true) { + SerializedField code = readCode(in); + if (code == SerializedField.END_MARKER) { + return; + } + + DataInput input = fieldIn(in); + if (code == SerializedField.ROOT_VALUE) { + this.value = readValue(input, null /* baseOrigin */); + } else if (code == SerializedField.ROOT_WAS_CONFIG) { + this.wasConfig = input.readBoolean(); + } + } + } + + private DataInput fieldIn(ObjectInput in) throws IOException { + byte[] bytes = new byte[in.readInt()]; + in.readFully(bytes); + return new DataInputStream(new ByteArrayInputStream(bytes)); + } + + private static ConfigException shouldNotBeUsed() { + return new ConfigException.BugOrBroken(SerializedConfigValue.class.getName() + + " should not exist outside of serialization"); + } + + @Override + public ConfigValueType valueType() { + throw shouldNotBeUsed(); + } + + @Override + public Object unwrapped() { + throw shouldNotBeUsed(); + } + + @Override + protected SerializedConfigValue newCopy(ConfigOrigin origin) { + throw shouldNotBeUsed(); + } + + @Override + public final String toString() { + return getClass().getSimpleName() + "(value=" + value + ",wasConfig=" + wasConfig + ")"; + } + + @Override + public boolean equals(Object other) { + // there's no reason we will ever call this equals(), but + // the one in AbstractConfigValue would explode due to + // calling unwrapped() above, so we just give some + // safe-to-call implementation to avoid breaking the + // contract of java.lang.Object + if (other instanceof SerializedConfigValue) { + return canEqual(other) + && (this.wasConfig == ((SerializedConfigValue) other).wasConfig) + && (this.value.equals(((SerializedConfigValue) other).value)); + } else { + return false; + } + } + + @Override + public int hashCode() { + int h = 41 * (41 + value.hashCode()); + h = 41 * (h + (wasConfig ? 1 : 0)); + return h; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfig.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfig.java new file mode 100644 index 0000000..b8c897f --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfig.java @@ -0,0 +1,1168 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.DateTimeException; +import java.time.Duration; +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalAmount; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigList; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMemorySize; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigResolveOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; +import com.drtshock.playervaults.lib.com.typesafe.config.Config; + +/** + * One thing to keep in mind in the future: as Collection-like APIs are added + * here, including iterators or size() or anything, they should be consistent + * with a one-level java.util.Map from paths to non-null values. Null values are + * not "in" the map. + */ +final class SimpleConfig implements Config, MergeableValue, Serializable { + + private static final long serialVersionUID = 1L; + + final private AbstractConfigObject object; + + SimpleConfig(AbstractConfigObject object) { + this.object = object; + } + + @Override + public AbstractConfigObject root() { + return object; + } + + @Override + public ConfigOrigin origin() { + return object.origin(); + } + + @Override + public SimpleConfig resolve() { + return resolve(ConfigResolveOptions.defaults()); + } + + @Override + public SimpleConfig resolve(ConfigResolveOptions options) { + return resolveWith(this, options); + } + + @Override + public SimpleConfig resolveWith(Config source) { + return resolveWith(source, ConfigResolveOptions.defaults()); + } + + @Override + public SimpleConfig resolveWith(Config source, ConfigResolveOptions options) { + AbstractConfigValue resolved = ResolveContext.resolve(object, ((SimpleConfig) source).object, options); + + if (resolved == object) + return this; + else + return new SimpleConfig((AbstractConfigObject) resolved); + } + + private ConfigValue hasPathPeek(String pathExpression) { + Path path = Path.newPath(pathExpression); + ConfigValue peeked; + try { + peeked = object.peekPath(path); + } catch (ConfigException.NotResolved e) { + throw ConfigImpl.improveNotResolved(path, e); + } + return peeked; + } + + @Override + public boolean hasPath(String pathExpression) { + ConfigValue peeked = hasPathPeek(pathExpression); + return peeked != null && peeked.valueType() != ConfigValueType.NULL; + } + + @Override + public boolean hasPathOrNull(String path) { + ConfigValue peeked = hasPathPeek(path); + return peeked != null; + } + + @Override + public boolean isEmpty() { + return object.isEmpty(); + } + + private static void findPaths(Set> entries, Path parent, + AbstractConfigObject obj) { + for (Map.Entry entry : obj.entrySet()) { + String elem = entry.getKey(); + ConfigValue v = entry.getValue(); + Path path = Path.newKey(elem); + if (parent != null) + path = path.prepend(parent); + if (v instanceof AbstractConfigObject) { + findPaths(entries, path, (AbstractConfigObject) v); + } else if (v instanceof ConfigNull) { + // nothing; nulls are conceptually not in a Config + } else { + entries.add(new AbstractMap.SimpleImmutableEntry(path.render(), v)); + } + } + } + + @Override + public Set> entrySet() { + Set> entries = new HashSet>(); + findPaths(entries, null, object); + return entries; + } + + static private AbstractConfigValue throwIfNull(AbstractConfigValue v, ConfigValueType expected, Path originalPath) { + if (v.valueType() == ConfigValueType.NULL) + throw new ConfigException.Null(v.origin(), originalPath.render(), + expected != null ? expected.name() : null); + else + return v; + } + + static private AbstractConfigValue findKey(AbstractConfigObject self, String key, + ConfigValueType expected, Path originalPath) { + return throwIfNull(findKeyOrNull(self, key, expected, originalPath), expected, originalPath); + } + + static private AbstractConfigValue findKeyOrNull(AbstractConfigObject self, String key, + ConfigValueType expected, Path originalPath) { + AbstractConfigValue v = self.peekAssumingResolved(key, originalPath); + if (v == null) + throw new ConfigException.Missing(originalPath.render()); + + if (expected != null) + v = DefaultTransformer.transform(v, expected); + + if (expected != null && (v.valueType() != expected && v.valueType() != ConfigValueType.NULL)) + throw new ConfigException.WrongType(v.origin(), originalPath.render(), expected.name(), + v.valueType().name()); + else + return v; + } + + static private AbstractConfigValue findOrNull(AbstractConfigObject self, Path path, + ConfigValueType expected, Path originalPath) { + try { + String key = path.first(); + Path next = path.remainder(); + if (next == null) { + return findKeyOrNull(self, key, expected, originalPath); + } else { + AbstractConfigObject o = (AbstractConfigObject) findKey(self, key, + ConfigValueType.OBJECT, + originalPath.subPath(0, originalPath.length() - next.length())); + assert (o != null); // missing was supposed to throw + return findOrNull(o, next, expected, originalPath); + } + } catch (ConfigException.NotResolved e) { + throw ConfigImpl.improveNotResolved(path, e); + } + } + + AbstractConfigValue find(Path pathExpression, ConfigValueType expected, Path originalPath) { + return throwIfNull(findOrNull(object, pathExpression, expected, originalPath), expected, originalPath); + } + + AbstractConfigValue find(String pathExpression, ConfigValueType expected) { + Path path = Path.newPath(pathExpression); + return find(path, expected, path); + } + + private AbstractConfigValue findOrNull(Path pathExpression, ConfigValueType expected, Path originalPath) { + return findOrNull(object, pathExpression, expected, originalPath); + } + + private AbstractConfigValue findOrNull(String pathExpression, ConfigValueType expected) { + Path path = Path.newPath(pathExpression); + return findOrNull(path, expected, path); + } + + @Override + public AbstractConfigValue getValue(String path) { + return find(path, null); + } + + @Override + public boolean getIsNull(String path) { + AbstractConfigValue v = findOrNull(path, null); + return (v.valueType() == ConfigValueType.NULL); + } + + @Override + public boolean getBoolean(String path) { + ConfigValue v = find(path, ConfigValueType.BOOLEAN); + return (Boolean) v.unwrapped(); + } + + private ConfigNumber getConfigNumber(String path) { + ConfigValue v = find(path, ConfigValueType.NUMBER); + return (ConfigNumber) v; + } + + @Override + public Number getNumber(String path) { + return getConfigNumber(path).unwrapped(); + } + + @Override + public int getInt(String path) { + ConfigNumber n = getConfigNumber(path); + return n.intValueRangeChecked(path); + } + + @Override + public long getLong(String path) { + return getNumber(path).longValue(); + } + + @Override + public double getDouble(String path) { + return getNumber(path).doubleValue(); + } + + @Override + public String getString(String path) { + ConfigValue v = find(path, ConfigValueType.STRING); + return (String) v.unwrapped(); + } + + @Override + public > T getEnum(Class enumClass, String path) { + ConfigValue v = find(path, ConfigValueType.STRING); + return getEnumValue(path, enumClass, v); + } + + @Override + public ConfigList getList(String path) { + AbstractConfigValue v = find(path, ConfigValueType.LIST); + return (ConfigList) v; + } + + @Override + public AbstractConfigObject getObject(String path) { + AbstractConfigObject obj = (AbstractConfigObject) find(path, ConfigValueType.OBJECT); + return obj; + } + + @Override + public SimpleConfig getConfig(String path) { + return getObject(path).toConfig(); + } + + @Override + public Object getAnyRef(String path) { + ConfigValue v = find(path, null); + return v.unwrapped(); + } + + @Override + public Long getBytes(String path) { + Long size = null; + try { + size = getLong(path); + } catch (ConfigException.WrongType e) { + ConfigValue v = find(path, ConfigValueType.STRING); + size = parseBytes((String) v.unwrapped(), + v.origin(), path); + } + return size; + } + + @Override + public ConfigMemorySize getMemorySize(String path) { + return ConfigMemorySize.ofBytes(getBytes(path)); + } + + @Deprecated + @Override + public Long getMilliseconds(String path) { + return getDuration(path, TimeUnit.MILLISECONDS); + } + + @Deprecated + @Override + public Long getNanoseconds(String path) { + return getDuration(path, TimeUnit.NANOSECONDS); + } + + @Override + public long getDuration(String path, TimeUnit unit) { + ConfigValue v = find(path, ConfigValueType.STRING); + long result = unit.convert( + parseDuration((String) v.unwrapped(), v.origin(), path), + TimeUnit.NANOSECONDS); + return result; + } + + @Override + public Duration getDuration(String path) { + ConfigValue v = find(path, ConfigValueType.STRING); + long nanos = parseDuration((String) v.unwrapped(), v.origin(), path); + return Duration.ofNanos(nanos); + } + + @Override + public Period getPeriod(String path){ + ConfigValue v = find(path, ConfigValueType.STRING); + return parsePeriod((String) v.unwrapped(), v.origin(), path); + } + + @Override + public TemporalAmount getTemporal(String path){ + try{ + return getDuration(path); + } catch (ConfigException.BadValue e){ + return getPeriod(path); + } + } + + @SuppressWarnings("unchecked") + private List getHomogeneousUnwrappedList(String path, + ConfigValueType expected) { + List l = new ArrayList(); + List list = getList(path); + for (ConfigValue cv : list) { + // variance would be nice, but stupid cast will do + AbstractConfigValue v = (AbstractConfigValue) cv; + if (expected != null) { + v = DefaultTransformer.transform(v, expected); + } + if (v.valueType() != expected) + throw new ConfigException.WrongType(v.origin(), path, + "list of " + expected.name(), "list of " + + v.valueType().name()); + l.add((T) v.unwrapped()); + } + return l; + } + + @Override + public List getBooleanList(String path) { + return getHomogeneousUnwrappedList(path, ConfigValueType.BOOLEAN); + } + + @Override + public List getNumberList(String path) { + return getHomogeneousUnwrappedList(path, ConfigValueType.NUMBER); + } + + @Override + public List getIntList(String path) { + List l = new ArrayList(); + List numbers = getHomogeneousWrappedList(path, ConfigValueType.NUMBER); + for (AbstractConfigValue v : numbers) { + l.add(((ConfigNumber) v).intValueRangeChecked(path)); + } + return l; + } + + @Override + public List getLongList(String path) { + List l = new ArrayList(); + List numbers = getNumberList(path); + for (Number n : numbers) { + l.add(n.longValue()); + } + return l; + } + + @Override + public List getDoubleList(String path) { + List l = new ArrayList(); + List numbers = getNumberList(path); + for (Number n : numbers) { + l.add(n.doubleValue()); + } + return l; + } + + @Override + public List getStringList(String path) { + return getHomogeneousUnwrappedList(path, ConfigValueType.STRING); + } + + @Override + public > List getEnumList(Class enumClass, String path) { + List enumNames = getHomogeneousWrappedList(path, ConfigValueType.STRING); + List enumList = new ArrayList(); + for (ConfigString enumName : enumNames) { + enumList.add(getEnumValue(path, enumClass, enumName)); + } + return enumList; + } + + private > T getEnumValue(String path, Class enumClass, ConfigValue enumConfigValue) { + String enumName = (String) enumConfigValue.unwrapped(); + try { + return Enum.valueOf(enumClass, enumName); + } catch (IllegalArgumentException e) { + List enumNames = new ArrayList(); + Enum[] enumConstants = enumClass.getEnumConstants(); + if (enumConstants != null) { + for (Enum enumConstant : enumConstants) { + enumNames.add(enumConstant.name()); + } + } + throw new ConfigException.BadValue( + enumConfigValue.origin(), path, + String.format("The enum class %s has no constant of the name '%s' (should be one of %s.)", + enumClass.getSimpleName(), enumName, enumNames)); + } + } + + @SuppressWarnings("unchecked") + private List getHomogeneousWrappedList( + String path, ConfigValueType expected) { + List l = new ArrayList(); + List list = getList(path); + for (ConfigValue cv : list) { + // variance would be nice, but stupid cast will do + AbstractConfigValue v = (AbstractConfigValue) cv; + if (expected != null) { + v = DefaultTransformer.transform(v, expected); + } + if (v.valueType() != expected) + throw new ConfigException.WrongType(v.origin(), path, + "list of " + expected.name(), "list of " + + v.valueType().name()); + l.add((T) v); + } + return l; + } + + @Override + public List getObjectList(String path) { + return getHomogeneousWrappedList(path, ConfigValueType.OBJECT); + } + + @Override + public List getConfigList(String path) { + List objects = getObjectList(path); + List l = new ArrayList(); + for (ConfigObject o : objects) { + l.add(o.toConfig()); + } + return l; + } + + @Override + public List getAnyRefList(String path) { + List l = new ArrayList(); + List list = getList(path); + for (ConfigValue v : list) { + l.add(v.unwrapped()); + } + return l; + } + + @Override + public List getBytesList(String path) { + List l = new ArrayList(); + List list = getList(path); + for (ConfigValue v : list) { + if (v.valueType() == ConfigValueType.NUMBER) { + l.add(((Number) v.unwrapped()).longValue()); + } else if (v.valueType() == ConfigValueType.STRING) { + String s = (String) v.unwrapped(); + Long n = parseBytes(s, v.origin(), path); + l.add(n); + } else { + throw new ConfigException.WrongType(v.origin(), path, + "memory size string or number of bytes", v.valueType() + .name()); + } + } + return l; + } + + @Override + public List getMemorySizeList(String path) { + List list = getBytesList(path); + List builder = new ArrayList(); + for (Long v : list) { + builder.add(ConfigMemorySize.ofBytes(v)); + } + return builder; + } + + @Override + public List getDurationList(String path, TimeUnit unit) { + List l = new ArrayList(); + List list = getList(path); + for (ConfigValue v : list) { + if (v.valueType() == ConfigValueType.NUMBER) { + Long n = unit.convert( + ((Number) v.unwrapped()).longValue(), + TimeUnit.MILLISECONDS); + l.add(n); + } else if (v.valueType() == ConfigValueType.STRING) { + String s = (String) v.unwrapped(); + Long n = unit.convert( + parseDuration(s, v.origin(), path), + TimeUnit.NANOSECONDS); + l.add(n); + } else { + throw new ConfigException.WrongType(v.origin(), path, + "duration string or number of milliseconds", + v.valueType().name()); + } + } + return l; + } + + @Override + public List getDurationList(String path) { + List l = getDurationList(path, TimeUnit.NANOSECONDS); + List builder = new ArrayList(l.size()); + for (Long value : l) { + builder.add(Duration.ofNanos(value)); + } + return builder; + } + + @Deprecated + @Override + public List getMillisecondsList(String path) { + return getDurationList(path, TimeUnit.MILLISECONDS); + } + + @Deprecated + @Override + public List getNanosecondsList(String path) { + return getDurationList(path, TimeUnit.NANOSECONDS); + } + + @Override + public AbstractConfigObject toFallbackValue() { + return object; + } + + @Override + public SimpleConfig withFallback(ConfigMergeable other) { + // this can return "this" if the withFallback doesn't need a new + // ConfigObject + return object.withFallback(other).toConfig(); + } + + @Override + public final boolean equals(Object other) { + if (other instanceof SimpleConfig) { + return object.equals(((SimpleConfig) other).object); + } else { + return false; + } + } + + @Override + public final int hashCode() { + // we do the "41*" just so our hash code won't match that of the + // underlying object. there's no real reason it can't match, but + // making it not match might catch some kinds of bug. + return 41 * object.hashCode(); + } + + @Override + public String toString() { + return "Config(" + object.toString() + ")"; + } + + private static String getUnits(String s) { + int i = s.length() - 1; + while (i >= 0) { + char c = s.charAt(i); + if (!Character.isLetter(c)) + break; + i -= 1; + } + return s.substring(i + 1); + } + + /** + * Parses a period string. If no units are specified in the string, it is + * assumed to be in days. The returned period is in days. + * The purpose of this function is to implement the period-related methods + * in the ConfigObject interface. + * + * @param input + * the string to parse + * @param originForException + * origin of the value being parsed + * @param pathForException + * path to include in exceptions + * @return duration in days + * @throws ConfigException + * if string is invalid + */ + public static Period parsePeriod(String input, + ConfigOrigin originForException, String pathForException) { + String s = ConfigImplUtil.unicodeTrim(input); + String originalUnitString = getUnits(s); + String unitString = originalUnitString; + String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() + - unitString.length())); + ChronoUnit units; + + // this would be caught later anyway, but the error message + // is more helpful if we check it here. + if (numberString.length() == 0) + throw new ConfigException.BadValue(originForException, + pathForException, "No number in period value '" + input + + "'"); + + if (unitString.length() > 2 && !unitString.endsWith("s")) + unitString = unitString + "s"; + + // note that this is deliberately case-sensitive + if (unitString.equals("") || unitString.equals("d") || unitString.equals("days")) { + units = ChronoUnit.DAYS; + + } else if (unitString.equals("w") || unitString.equals("weeks")) { + units = ChronoUnit.WEEKS; + + } else if (unitString.equals("m") || unitString.equals("mo") || unitString.equals("months")) { + units = ChronoUnit.MONTHS; + + } else if (unitString.equals("y") || unitString.equals("years")) { + units = ChronoUnit.YEARS; + + } else { + throw new ConfigException.BadValue(originForException, + pathForException, "Could not parse time unit '" + + originalUnitString + + "' (try d, w, mo, y)"); + } + + try { + return periodOf(Integer.parseInt(numberString), units); + } catch (NumberFormatException e) { + throw new ConfigException.BadValue(originForException, + pathForException, "Could not parse duration number '" + + numberString + "'"); + } + } + + + private static Period periodOf(int n, ChronoUnit unit){ + if(unit.isTimeBased()){ + throw new DateTimeException(unit + " cannot be converted to a java.time.Period"); + } + + switch (unit){ + case DAYS: + return Period.ofDays(n); + case WEEKS: + return Period.ofWeeks(n); + case MONTHS: + return Period.ofMonths(n); + case YEARS: + return Period.ofYears(n); + default: + throw new DateTimeException(unit + " cannot be converted to a java.time.Period"); + } + } + + /** + * Parses a duration string. If no units are specified in the string, it is + * assumed to be in milliseconds. The returned duration is in nanoseconds. + * The purpose of this function is to implement the duration-related methods + * in the ConfigObject interface. + * + * @param input + * the string to parse + * @param originForException + * origin of the value being parsed + * @param pathForException + * path to include in exceptions + * @return duration in nanoseconds + * @throws ConfigException + * if string is invalid + */ + public static long parseDuration(String input, + ConfigOrigin originForException, String pathForException) { + String s = ConfigImplUtil.unicodeTrim(input); + String originalUnitString = getUnits(s); + String unitString = originalUnitString; + String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() + - unitString.length())); + TimeUnit units = null; + + // this would be caught later anyway, but the error message + // is more helpful if we check it here. + if (numberString.length() == 0) + throw new ConfigException.BadValue(originForException, + pathForException, "No number in duration value '" + input + + "'"); + + if (unitString.length() > 2 && !unitString.endsWith("s")) + unitString = unitString + "s"; + + // note that this is deliberately case-sensitive + if (unitString.equals("") || unitString.equals("ms") || unitString.equals("millis") + || unitString.equals("milliseconds")) { + units = TimeUnit.MILLISECONDS; + } else if (unitString.equals("us") || unitString.equals("micros") || unitString.equals("microseconds")) { + units = TimeUnit.MICROSECONDS; + } else if (unitString.equals("ns") || unitString.equals("nanos") || unitString.equals("nanoseconds")) { + units = TimeUnit.NANOSECONDS; + } else if (unitString.equals("d") || unitString.equals("days")) { + units = TimeUnit.DAYS; + } else if (unitString.equals("h") || unitString.equals("hours")) { + units = TimeUnit.HOURS; + } else if (unitString.equals("s") || unitString.equals("seconds")) { + units = TimeUnit.SECONDS; + } else if (unitString.equals("m") || unitString.equals("minutes")) { + units = TimeUnit.MINUTES; + } else { + throw new ConfigException.BadValue(originForException, + pathForException, "Could not parse time unit '" + + originalUnitString + + "' (try ns, us, ms, s, m, h, d)"); + } + + try { + // if the string is purely digits, parse as an integer to avoid + // possible precision loss; + // otherwise as a double. + if (numberString.matches("[+-]?[0-9]+")) { + return units.toNanos(Long.parseLong(numberString)); + } else { + long nanosInUnit = units.toNanos(1); + return (long) (Double.parseDouble(numberString) * nanosInUnit); + } + } catch (NumberFormatException e) { + throw new ConfigException.BadValue(originForException, + pathForException, "Could not parse duration number '" + + numberString + "'"); + } + } + + private static enum MemoryUnit { + BYTES("", 1024, 0), + + KILOBYTES("kilo", 1000, 1), + MEGABYTES("mega", 1000, 2), + GIGABYTES("giga", 1000, 3), + TERABYTES("tera", 1000, 4), + PETABYTES("peta", 1000, 5), + EXABYTES("exa", 1000, 6), + ZETTABYTES("zetta", 1000, 7), + YOTTABYTES("yotta", 1000, 8), + + KIBIBYTES("kibi", 1024, 1), + MEBIBYTES("mebi", 1024, 2), + GIBIBYTES("gibi", 1024, 3), + TEBIBYTES("tebi", 1024, 4), + PEBIBYTES("pebi", 1024, 5), + EXBIBYTES("exbi", 1024, 6), + ZEBIBYTES("zebi", 1024, 7), + YOBIBYTES("yobi", 1024, 8); + + final String prefix; + final int powerOf; + final int power; + final BigInteger bytes; + + MemoryUnit(String prefix, int powerOf, int power) { + this.prefix = prefix; + this.powerOf = powerOf; + this.power = power; + this.bytes = BigInteger.valueOf(powerOf).pow(power); + } + + private static Map makeUnitsMap() { + Map map = new HashMap(); + for (MemoryUnit unit : MemoryUnit.values()) { + map.put(unit.prefix + "byte", unit); + map.put(unit.prefix + "bytes", unit); + if (unit.prefix.length() == 0) { + map.put("b", unit); + map.put("B", unit); + map.put("", unit); // no unit specified means bytes + } else { + String first = unit.prefix.substring(0, 1); + String firstUpper = first.toUpperCase(); + if (unit.powerOf == 1024) { + map.put(first, unit); // 512m + map.put(firstUpper, unit); // 512M + map.put(firstUpper + "i", unit); // 512Mi + map.put(firstUpper + "iB", unit); // 512MiB + } else if (unit.powerOf == 1000) { + if (unit.power == 1) { + map.put(first + "B", unit); // 512kB + } else { + map.put(firstUpper + "B", unit); // 512MB + } + } else { + throw new RuntimeException("broken MemoryUnit enum"); + } + } + } + return map; + } + + private static Map unitsMap = makeUnitsMap(); + + static MemoryUnit parseUnit(String unit) { + return unitsMap.get(unit); + } + } + + /** + * Parses a size-in-bytes string. If no units are specified in the string, + * it is assumed to be in bytes. The returned value is in bytes. The purpose + * of this function is to implement the size-in-bytes-related methods in the + * Config interface. + * + * @param input + * the string to parse + * @param originForException + * origin of the value being parsed + * @param pathForException + * path to include in exceptions + * @return size in bytes + * @throws ConfigException + * if string is invalid + */ + public static long parseBytes(String input, ConfigOrigin originForException, + String pathForException) { + String s = ConfigImplUtil.unicodeTrim(input); + String unitString = getUnits(s); + String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, + s.length() - unitString.length())); + + // this would be caught later anyway, but the error message + // is more helpful if we check it here. + if (numberString.length() == 0) + throw new ConfigException.BadValue(originForException, + pathForException, "No number in size-in-bytes value '" + + input + "'"); + + MemoryUnit units = MemoryUnit.parseUnit(unitString); + + if (units == null) { + throw new ConfigException.BadValue(originForException, pathForException, + "Could not parse size-in-bytes unit '" + unitString + + "' (try k, K, kB, KiB, kilobytes, kibibytes)"); + } + + try { + BigInteger result; + // if the string is purely digits, parse as an integer to avoid + // possible precision loss; otherwise as a double. + if (numberString.matches("[0-9]+")) { + result = units.bytes.multiply(new BigInteger(numberString)); + } else { + BigDecimal resultDecimal = (new BigDecimal(units.bytes)).multiply(new BigDecimal(numberString)); + result = resultDecimal.toBigInteger(); + } + if (result.bitLength() < 64) + return result.longValue(); + else + throw new ConfigException.BadValue(originForException, pathForException, + "size-in-bytes value is out of range for a 64-bit long: '" + input + "'"); + } catch (NumberFormatException e) { + throw new ConfigException.BadValue(originForException, pathForException, + "Could not parse size-in-bytes number '" + numberString + "'"); + } + } + + private AbstractConfigValue peekPath(Path path) { + return root().peekPath(path); + } + + private static void addProblem(List accumulator, Path path, + ConfigOrigin origin, String problem) { + accumulator.add(new ConfigException.ValidationProblem(path.render(), origin, problem)); + } + + private static String getDesc(ConfigValueType type) { + return type.name().toLowerCase(); + } + + private static String getDesc(ConfigValue refValue) { + if (refValue instanceof AbstractConfigObject) { + AbstractConfigObject obj = (AbstractConfigObject) refValue; + if (!obj.isEmpty()) + return "object with keys " + obj.keySet(); + else + return getDesc(refValue.valueType()); + } else { + return getDesc(refValue.valueType()); + } + } + + private static void addMissing(List accumulator, + String refDesc, Path path, ConfigOrigin origin) { + addProblem(accumulator, path, origin, "No setting at '" + path.render() + "', expecting: " + + refDesc); + } + + private static void addMissing(List accumulator, + ConfigValue refValue, Path path, ConfigOrigin origin) { + addMissing(accumulator, getDesc(refValue), path, origin); + } + + // JavaBean stuff uses this + static void addMissing(List accumulator, + ConfigValueType refType, Path path, ConfigOrigin origin) { + addMissing(accumulator, getDesc(refType), path, origin); + } + + private static void addWrongType(List accumulator, + String refDesc, AbstractConfigValue actual, Path path) { + addProblem(accumulator, path, actual.origin(), "Wrong value type at '" + path.render() + + "', expecting: " + refDesc + " but got: " + + getDesc(actual)); + } + + private static void addWrongType(List accumulator, + ConfigValue refValue, AbstractConfigValue actual, Path path) { + addWrongType(accumulator, getDesc(refValue), actual, path); + } + + private static void addWrongType(List accumulator, + ConfigValueType refType, AbstractConfigValue actual, Path path) { + addWrongType(accumulator, getDesc(refType), actual, path); + } + + private static boolean couldBeNull(AbstractConfigValue v) { + return DefaultTransformer.transform(v, ConfigValueType.NULL) + .valueType() == ConfigValueType.NULL; + } + + private static boolean haveCompatibleTypes(ConfigValue reference, AbstractConfigValue value) { + if (couldBeNull((AbstractConfigValue) reference)) { + // we allow any setting to be null + return true; + } else { + return haveCompatibleTypes(reference.valueType(), value); + } + } + + private static boolean haveCompatibleTypes(ConfigValueType referenceType, AbstractConfigValue value) { + if (referenceType == ConfigValueType.NULL || couldBeNull(value)) { + // we allow any setting to be null + return true; + } else if (referenceType == ConfigValueType.OBJECT) { + if (value instanceof AbstractConfigObject) { + return true; + } else { + return false; + } + } else if (referenceType == ConfigValueType.LIST) { + // objects may be convertible to lists if they have numeric keys + if (value instanceof SimpleConfigList || value instanceof SimpleConfigObject) { + return true; + } else { + return false; + } + } else if (referenceType == ConfigValueType.STRING) { + // assume a string could be gotten as any non-collection type; + // allows things like getMilliseconds including domain-specific + // interpretations of strings + return true; + } else if (value instanceof ConfigString) { + // assume a string could be gotten as any non-collection type + return true; + } else { + if (referenceType == value.valueType()) { + return true; + } else { + return false; + } + } + } + + // path is null if we're at the root + private static void checkValidObject(Path path, AbstractConfigObject reference, + AbstractConfigObject value, + List accumulator) { + for (Map.Entry entry : reference.entrySet()) { + String key = entry.getKey(); + + Path childPath; + if (path != null) + childPath = Path.newKey(key).prepend(path); + else + childPath = Path.newKey(key); + + AbstractConfigValue v = value.get(key); + if (v == null) { + addMissing(accumulator, entry.getValue(), childPath, value.origin()); + } else { + checkValid(childPath, entry.getValue(), v, accumulator); + } + } + } + + private static void checkListCompatibility(Path path, SimpleConfigList listRef, + SimpleConfigList listValue, List accumulator) { + if (listRef.isEmpty() || listValue.isEmpty()) { + // can't verify type, leave alone + } else { + AbstractConfigValue refElement = listRef.get(0); + for (ConfigValue elem : listValue) { + AbstractConfigValue e = (AbstractConfigValue) elem; + if (!haveCompatibleTypes(refElement, e)) { + addProblem(accumulator, path, e.origin(), "List at '" + path.render() + + "' contains wrong value type, expecting list of " + + getDesc(refElement) + " but got element of type " + getDesc(e)); + // don't add a problem for every last array element + break; + } + } + } + } + + // Used by the JavaBean-based validator + static void checkValid(Path path, ConfigValueType referenceType, AbstractConfigValue value, + List accumulator) { + if (haveCompatibleTypes(referenceType, value)) { + if (referenceType == ConfigValueType.LIST && value instanceof SimpleConfigObject) { + // attempt conversion of indexed object to list + AbstractConfigValue listValue = DefaultTransformer.transform(value, + ConfigValueType.LIST); + if (!(listValue instanceof SimpleConfigList)) + addWrongType(accumulator, referenceType, value, path); + } + } else { + addWrongType(accumulator, referenceType, value, path); + } + } + + private static void checkValid(Path path, ConfigValue reference, AbstractConfigValue value, + List accumulator) { + // Unmergeable is supposed to be impossible to encounter in here + // because we check for resolve status up front. + + if (haveCompatibleTypes(reference, value)) { + if (reference instanceof AbstractConfigObject && value instanceof AbstractConfigObject) { + checkValidObject(path, (AbstractConfigObject) reference, + (AbstractConfigObject) value, accumulator); + } else if (reference instanceof SimpleConfigList && value instanceof SimpleConfigList) { + SimpleConfigList listRef = (SimpleConfigList) reference; + SimpleConfigList listValue = (SimpleConfigList) value; + checkListCompatibility(path, listRef, listValue, accumulator); + } else if (reference instanceof SimpleConfigList && value instanceof SimpleConfigObject) { + // attempt conversion of indexed object to list + SimpleConfigList listRef = (SimpleConfigList) reference; + AbstractConfigValue listValue = DefaultTransformer.transform(value, + ConfigValueType.LIST); + if (listValue instanceof SimpleConfigList) + checkListCompatibility(path, listRef, (SimpleConfigList) listValue, accumulator); + else + addWrongType(accumulator, reference, value, path); + } + } else { + addWrongType(accumulator, reference, value, path); + } + } + + @Override + public boolean isResolved() { + return root().resolveStatus() == ResolveStatus.RESOLVED; + } + + @Override + public void checkValid(Config reference, String... restrictToPaths) { + SimpleConfig ref = (SimpleConfig) reference; + + // unresolved reference config is a bug in the caller of checkValid + if (ref.root().resolveStatus() != ResolveStatus.RESOLVED) + throw new ConfigException.BugOrBroken( + "do not call checkValid() with an unresolved reference config, call Config#resolve(), see Config#resolve() API docs"); + + // unresolved config under validation is a bug in something, + // NotResolved is a more specific subclass of BugOrBroken + if (root().resolveStatus() != ResolveStatus.RESOLVED) + throw new ConfigException.NotResolved( + "need to Config#resolve() each config before using it, see the API docs for Config#resolve()"); + + // Now we know that both reference and this config are resolved + + List problems = new ArrayList(); + + if (restrictToPaths.length == 0) { + checkValidObject(null, ref.root(), root(), problems); + } else { + for (String p : restrictToPaths) { + Path path = Path.newPath(p); + AbstractConfigValue refValue = ref.peekPath(path); + if (refValue != null) { + AbstractConfigValue child = peekPath(path); + if (child != null) { + checkValid(path, refValue, child, problems); + } else { + addMissing(problems, refValue, path, origin()); + } + } + } + } + + if (!problems.isEmpty()) { + throw new ConfigException.ValidationFailed(problems); + } + } + + @Override + public SimpleConfig withOnlyPath(String pathExpression) { + Path path = Path.newPath(pathExpression); + return new SimpleConfig(root().withOnlyPath(path)); + } + + @Override + public SimpleConfig withoutPath(String pathExpression) { + Path path = Path.newPath(pathExpression); + return new SimpleConfig(root().withoutPath(path)); + } + + @Override + public SimpleConfig withValue(String pathExpression, ConfigValue v) { + Path path = Path.newPath(pathExpression); + return new SimpleConfig(root().withValue(path, v)); + } + + SimpleConfig atKey(ConfigOrigin origin, String key) { + return root().atKey(origin, key); + } + + @Override + public SimpleConfig atKey(String key) { + return root().atKey(key); + } + + @Override + public Config atPath(String path) { + return root().atPath(path); + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigDocument.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigDocument.java new file mode 100644 index 0000000..bc262ea --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigDocument.java @@ -0,0 +1,66 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.parser.ConfigDocument; + +import java.io.StringReader; +import java.util.Iterator; + +final class SimpleConfigDocument implements ConfigDocument { + private ConfigNodeRoot configNodeTree; + private ConfigParseOptions parseOptions; + + SimpleConfigDocument(ConfigNodeRoot parsedNode, ConfigParseOptions parseOptions) { + configNodeTree = parsedNode; + this.parseOptions = parseOptions; + } + + @Override + public ConfigDocument withValueText(String path, String newValue) { + if (newValue == null) + throw new ConfigException.BugOrBroken("null value for " + path + " passed to withValueText"); + SimpleConfigOrigin origin = SimpleConfigOrigin.newSimple("single value parsing"); + StringReader reader = new StringReader(newValue); + Iterator tokens = Tokenizer.tokenize(origin, reader, parseOptions.getSyntax()); + AbstractConfigNodeValue parsedValue = ConfigDocumentParser.parseValue(tokens, origin, parseOptions); + reader.close(); + + return new SimpleConfigDocument(configNodeTree.setValue(path, parsedValue, parseOptions.getSyntax()), parseOptions); + } + + @Override + public ConfigDocument withValue(String path, ConfigValue newValue) { + if (newValue == null) + throw new ConfigException.BugOrBroken("null value for " + path + " passed to withValue"); + ConfigRenderOptions options = ConfigRenderOptions.defaults(); + options = options.setOriginComments(false); + return withValueText(path, newValue.render(options).trim()); + } + + @Override + public ConfigDocument withoutPath(String path) { + return new SimpleConfigDocument(configNodeTree.setValue(path, null, parseOptions.getSyntax()), parseOptions); + } + + @Override + public boolean hasPath(String path) { + return configNodeTree.hasValue(path); + } + + public String render() { + return configNodeTree.render(); + } + + @Override + public boolean equals(Object other) { + return other instanceof ConfigDocument && render().equals(((ConfigDocument) other).render()); + } + + @Override + public int hashCode() { + return render().hashCode(); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigList.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigList.java new file mode 100644 index 0000000..5007d9c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigList.java @@ -0,0 +1,464 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigList; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +final class SimpleConfigList extends AbstractConfigValue implements ConfigList, Container, Serializable { + + private static final long serialVersionUID = 2L; + + final private List value; + final private boolean resolved; + + SimpleConfigList(ConfigOrigin origin, List value) { + this(origin, value, ResolveStatus + .fromValues(value)); + } + + SimpleConfigList(ConfigOrigin origin, List value, + ResolveStatus status) { + super(origin); + this.value = value; + this.resolved = status == ResolveStatus.RESOLVED; + + // kind of an expensive debug check (makes this constructor pointless) + if (status != ResolveStatus.fromValues(value)) + throw new ConfigException.BugOrBroken( + "SimpleConfigList created with wrong resolve status: " + this); + } + + @Override + public ConfigValueType valueType() { + return ConfigValueType.LIST; + } + + @Override + public List unwrapped() { + List list = new ArrayList(); + for (AbstractConfigValue v : value) { + list.add(v.unwrapped()); + } + return list; + } + + @Override + ResolveStatus resolveStatus() { + return ResolveStatus.fromBoolean(resolved); + } + + @Override + public SimpleConfigList replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) { + List newList = replaceChildInList(value, child, replacement); + if (newList == null) { + return null; + } else { + // we use the constructor flavor that will recompute the resolve + // status + return new SimpleConfigList(origin(), newList); + } + } + + @Override + public boolean hasDescendant(AbstractConfigValue descendant) { + return hasDescendantInList(value, descendant); + } + + private SimpleConfigList modify(NoExceptionsModifier modifier, ResolveStatus newResolveStatus) { + try { + return modifyMayThrow(modifier, newResolveStatus); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new ConfigException.BugOrBroken("unexpected checked exception", e); + } + } + + private SimpleConfigList modifyMayThrow(Modifier modifier, ResolveStatus newResolveStatus) + throws Exception { + // lazy-create for optimization + List changed = null; + int i = 0; + for (AbstractConfigValue v : value) { + AbstractConfigValue modified = modifier.modifyChildMayThrow(null /* key */, v); + + // lazy-create the new list if required + if (changed == null && modified != v) { + changed = new ArrayList(); + for (int j = 0; j < i; ++j) { + changed.add(value.get(j)); + } + } + + // once the new list is created, all elements + // have to go in it. if modifyChild returned + // null, we drop that element. + if (changed != null && modified != null) { + changed.add(modified); + } + + i += 1; + } + + if (changed != null) { + if (newResolveStatus != null) { + return new SimpleConfigList(origin(), changed, newResolveStatus); + } else { + return new SimpleConfigList(origin(), changed); + } + } else { + return this; + } + } + + private static class ResolveModifier implements Modifier { + ResolveContext context; + final ResolveSource source; + ResolveModifier(ResolveContext context, ResolveSource source) { + this.context = context; + this.source = source; + } + + @Override + public AbstractConfigValue modifyChildMayThrow(String key, AbstractConfigValue v) + throws NotPossibleToResolve { + ResolveResult result = context.resolve(v, source); + context = result.context; + return result.value; + } + } + + @Override + ResolveResult resolveSubstitutions(ResolveContext context, ResolveSource source) + throws NotPossibleToResolve { + if (resolved) + return ResolveResult.make(context, this); + + if (context.isRestrictedToChild()) { + // if a list restricts to a child path, then it has no child paths, + // so nothing to do. + return ResolveResult.make(context, this); + } else { + try { + ResolveModifier modifier = new ResolveModifier(context, source.pushParent(this)); + SimpleConfigList value = modifyMayThrow(modifier, context.options().getAllowUnresolved() ? null : ResolveStatus.RESOLVED); + return ResolveResult.make(modifier.context, value); + } catch (NotPossibleToResolve e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new ConfigException.BugOrBroken("unexpected checked exception", e); + } + } + } + + @Override + SimpleConfigList relativized(final Path prefix) { + return modify(new NoExceptionsModifier() { + @Override + public AbstractConfigValue modifyChild(String key, AbstractConfigValue v) { + return v.relativized(prefix); + } + + }, resolveStatus()); + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof SimpleConfigList; + } + + @Override + public boolean equals(Object other) { + // note that "origin" is deliberately NOT part of equality + if (other instanceof SimpleConfigList) { + // optimization to avoid unwrapped() for two ConfigList + return canEqual(other) + && (value == ((SimpleConfigList) other).value || value.equals(((SimpleConfigList) other).value)); + } else { + return false; + } + } + + @Override + public int hashCode() { + // note that "origin" is deliberately NOT part of equality + return value.hashCode(); + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + if (value.isEmpty()) { + sb.append("[]"); + } else { + sb.append("["); + if (options.getFormatted()) + sb.append('\n'); + for (AbstractConfigValue v : value) { + if (options.getOriginComments()) { + String[] lines = v.origin().description().split("\n"); + for (String l : lines) { + indent(sb, indent + 1, options); + sb.append('#'); + if (!l.isEmpty()) + sb.append(' '); + sb.append(l); + sb.append("\n"); + } + } + if (options.getComments()) { + for (String comment : v.origin().comments()) { + indent(sb, indent + 1, options); + sb.append("# "); + sb.append(comment); + sb.append("\n"); + } + } + indent(sb, indent + 1, options); + + v.render(sb, indent + 1, atRoot, options); + sb.append(","); + if (options.getFormatted()) + sb.append('\n'); + } + sb.setLength(sb.length() - 1); // chop or newline + if (options.getFormatted()) { + sb.setLength(sb.length() - 1); // also chop comma + sb.append('\n'); + indent(sb, indent, options); + } + sb.append("]"); + } + } + + @Override + public boolean contains(Object o) { + return value.contains(o); + } + + @Override + public boolean containsAll(Collection c) { + return value.containsAll(c); + } + + @Override + public AbstractConfigValue get(int index) { + return value.get(index); + } + + @Override + public int indexOf(Object o) { + return value.indexOf(o); + } + + @Override + public boolean isEmpty() { + return value.isEmpty(); + } + + @Override + public Iterator iterator() { + final Iterator i = value.iterator(); + + return new Iterator() { + @Override + public boolean hasNext() { + return i.hasNext(); + } + + @Override + public ConfigValue next() { + return i.next(); + } + + @Override + public void remove() { + throw weAreImmutable("iterator().remove"); + } + }; + } + + @Override + public int lastIndexOf(Object o) { + return value.lastIndexOf(o); + } + + private static ListIterator wrapListIterator( + final ListIterator i) { + return new ListIterator() { + @Override + public boolean hasNext() { + return i.hasNext(); + } + + @Override + public ConfigValue next() { + return i.next(); + } + + @Override + public void remove() { + throw weAreImmutable("listIterator().remove"); + } + + @Override + public void add(ConfigValue arg0) { + throw weAreImmutable("listIterator().add"); + } + + @Override + public boolean hasPrevious() { + return i.hasPrevious(); + } + + @Override + public int nextIndex() { + return i.nextIndex(); + } + + @Override + public ConfigValue previous() { + return i.previous(); + } + + @Override + public int previousIndex() { + return i.previousIndex(); + } + + @Override + public void set(ConfigValue arg0) { + throw weAreImmutable("listIterator().set"); + } + }; + } + + @Override + public ListIterator listIterator() { + return wrapListIterator(value.listIterator()); + } + + @Override + public ListIterator listIterator(int index) { + return wrapListIterator(value.listIterator(index)); + } + + @Override + public int size() { + return value.size(); + } + + @Override + public List subList(int fromIndex, int toIndex) { + List list = new ArrayList(); + // yay bloat caused by lack of type variance + for (AbstractConfigValue v : value.subList(fromIndex, toIndex)) { + list.add(v); + } + return list; + } + + @Override + public Object[] toArray() { + return value.toArray(); + } + + @Override + public T[] toArray(T[] a) { + return value.toArray(a); + } + + private static UnsupportedOperationException weAreImmutable(String method) { + return new UnsupportedOperationException( + "ConfigList is immutable, you can't call List.'" + method + "'"); + } + + @Override + public boolean add(ConfigValue e) { + throw weAreImmutable("add"); + } + + @Override + public void add(int index, ConfigValue element) { + throw weAreImmutable("add"); + } + + @Override + public boolean addAll(Collection c) { + throw weAreImmutable("addAll"); + } + + @Override + public boolean addAll(int index, Collection c) { + throw weAreImmutable("addAll"); + } + + @Override + public void clear() { + throw weAreImmutable("clear"); + } + + @Override + public boolean remove(Object o) { + throw weAreImmutable("remove"); + } + + @Override + public ConfigValue remove(int index) { + throw weAreImmutable("remove"); + } + + @Override + public boolean removeAll(Collection c) { + throw weAreImmutable("removeAll"); + } + + @Override + public boolean retainAll(Collection c) { + throw weAreImmutable("retainAll"); + } + + @Override + public ConfigValue set(int index, ConfigValue element) { + throw weAreImmutable("set"); + } + + @Override + protected SimpleConfigList newCopy(ConfigOrigin newOrigin) { + return new SimpleConfigList(newOrigin, value); + } + + final SimpleConfigList concatenate(SimpleConfigList other) { + ConfigOrigin combinedOrigin = SimpleConfigOrigin.mergeOrigins(origin(), other.origin()); + List combined = new ArrayList(value.size() + + other.value.size()); + combined.addAll(value); + combined.addAll(other.value); + return new SimpleConfigList(combinedOrigin, combined); + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } + + @Override + public SimpleConfigList withOrigin(ConfigOrigin origin) { + return (SimpleConfigList) super.withOrigin(origin); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigObject.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigObject.java new file mode 100644 index 0000000..381d940 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigObject.java @@ -0,0 +1,679 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; + +final class SimpleConfigObject extends AbstractConfigObject implements Serializable { + + private static final long serialVersionUID = 2L; + + // this map should never be modified - assume immutable + final private Map value; + final private boolean resolved; + final private boolean ignoresFallbacks; + + SimpleConfigObject(ConfigOrigin origin, + Map value, ResolveStatus status, + boolean ignoresFallbacks) { + super(origin); + if (value == null) + throw new ConfigException.BugOrBroken( + "creating config object with null map"); + this.value = value; + this.resolved = status == ResolveStatus.RESOLVED; + this.ignoresFallbacks = ignoresFallbacks; + + // Kind of an expensive debug check. Comment out? + if (status != ResolveStatus.fromValues(value.values())) + throw new ConfigException.BugOrBroken("Wrong resolved status on " + this); + } + + SimpleConfigObject(ConfigOrigin origin, + Map value) { + this(origin, value, ResolveStatus.fromValues(value.values()), false /* ignoresFallbacks */); + } + + @Override + public SimpleConfigObject withOnlyKey(String key) { + return withOnlyPath(Path.newKey(key)); + } + + @Override + public SimpleConfigObject withoutKey(String key) { + return withoutPath(Path.newKey(key)); + } + + // gets the object with only the path if the path + // exists, otherwise null if it doesn't. this ensures + // that if we have { a : { b : 42 } } and do + // withOnlyPath("a.b.c") that we don't keep an empty + // "a" object. + @Override + protected SimpleConfigObject withOnlyPathOrNull(Path path) { + String key = path.first(); + Path next = path.remainder(); + AbstractConfigValue v = value.get(key); + + if (next != null) { + if (v != null && (v instanceof AbstractConfigObject)) { + v = ((AbstractConfigObject) v).withOnlyPathOrNull(next); + } else { + // if the path has more elements but we don't have an object, + // then the rest of the path does not exist. + v = null; + } + } + + if (v == null) { + return null; + } else { + return new SimpleConfigObject(origin(), Collections.singletonMap(key, v), + v.resolveStatus(), ignoresFallbacks); + } + } + + @Override + SimpleConfigObject withOnlyPath(Path path) { + SimpleConfigObject o = withOnlyPathOrNull(path); + if (o == null) { + return new SimpleConfigObject(origin(), + Collections. emptyMap(), ResolveStatus.RESOLVED, + ignoresFallbacks); + } else { + return o; + } + } + + @Override + SimpleConfigObject withoutPath(Path path) { + String key = path.first(); + Path next = path.remainder(); + AbstractConfigValue v = value.get(key); + + if (v != null && next != null && v instanceof AbstractConfigObject) { + v = ((AbstractConfigObject) v).withoutPath(next); + Map updated = new HashMap( + value); + updated.put(key, v); + return new SimpleConfigObject(origin(), updated, ResolveStatus.fromValues(updated + .values()), ignoresFallbacks); + } else if (next != null || v == null) { + // can't descend, nothing to remove + return this; + } else { + Map smaller = new HashMap( + value.size() - 1); + for (Map.Entry old : value.entrySet()) { + if (!old.getKey().equals(key)) + smaller.put(old.getKey(), old.getValue()); + } + return new SimpleConfigObject(origin(), smaller, ResolveStatus.fromValues(smaller + .values()), ignoresFallbacks); + } + } + + @Override + public SimpleConfigObject withValue(String key, ConfigValue v) { + if (v == null) + throw new ConfigException.BugOrBroken( + "Trying to store null ConfigValue in a ConfigObject"); + + Map newMap; + if (value.isEmpty()) { + newMap = Collections.singletonMap(key, (AbstractConfigValue) v); + } else { + newMap = new HashMap(value); + newMap.put(key, (AbstractConfigValue) v); + } + + return new SimpleConfigObject(origin(), newMap, ResolveStatus.fromValues(newMap.values()), + ignoresFallbacks); + } + + @Override + SimpleConfigObject withValue(Path path, ConfigValue v) { + String key = path.first(); + Path next = path.remainder(); + + if (next == null) { + return withValue(key, v); + } else { + AbstractConfigValue child = value.get(key); + if (child != null && child instanceof AbstractConfigObject) { + // if we have an object, add to it + return withValue(key, ((AbstractConfigObject) child).withValue(next, v)); + } else { + // as soon as we have a non-object, replace it entirely + SimpleConfig subtree = ((AbstractConfigValue) v).atPath( + SimpleConfigOrigin.newSimple("withValue(" + next.render() + ")"), next); + return withValue(key, subtree.root()); + } + } + } + + @Override + protected AbstractConfigValue attemptPeekWithPartialResolve(String key) { + return value.get(key); + } + + private SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin, + boolean newIgnoresFallbacks) { + return new SimpleConfigObject(newOrigin, value, newStatus, newIgnoresFallbacks); + } + + @Override + protected SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin) { + return newCopy(newStatus, newOrigin, ignoresFallbacks); + } + + @Override + protected SimpleConfigObject withFallbacksIgnored() { + if (ignoresFallbacks) + return this; + else + return newCopy(resolveStatus(), origin(), true /* ignoresFallbacks */); + } + + @Override + ResolveStatus resolveStatus() { + return ResolveStatus.fromBoolean(resolved); + } + + @Override + public SimpleConfigObject replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) { + HashMap newChildren = new HashMap(value); + for (Map.Entry old : newChildren.entrySet()) { + if (old.getValue() == child) { + if (replacement != null) + old.setValue(replacement); + else + newChildren.remove(old.getKey()); + + return new SimpleConfigObject(origin(), newChildren, ResolveStatus.fromValues(newChildren.values()), + ignoresFallbacks); + } + } + throw new ConfigException.BugOrBroken("SimpleConfigObject.replaceChild did not find " + child + " in " + this); + } + + @Override + public boolean hasDescendant(AbstractConfigValue descendant) { + for (AbstractConfigValue child : value.values()) { + if (child == descendant) + return true; + } + // now do the expensive search + for (AbstractConfigValue child : value.values()) { + if (child instanceof Container && ((Container) child).hasDescendant(descendant)) + return true; + } + + return false; + } + + @Override + protected boolean ignoresFallbacks() { + return ignoresFallbacks; + } + + @Override + public Map unwrapped() { + Map m = new HashMap(); + for (Map.Entry e : value.entrySet()) { + m.put(e.getKey(), e.getValue().unwrapped()); + } + return m; + } + + @Override + protected SimpleConfigObject mergedWithObject(AbstractConfigObject abstractFallback) { + requireNotIgnoringFallbacks(); + + if (!(abstractFallback instanceof SimpleConfigObject)) { + throw new ConfigException.BugOrBroken( + "should not be reached (merging non-SimpleConfigObject)"); + } + + SimpleConfigObject fallback = (SimpleConfigObject) abstractFallback; + + boolean changed = false; + boolean allResolved = true; + Map merged = new HashMap(); + Set allKeys = new HashSet(); + allKeys.addAll(this.keySet()); + allKeys.addAll(fallback.keySet()); + for (String key : allKeys) { + AbstractConfigValue first = this.value.get(key); + AbstractConfigValue second = fallback.value.get(key); + AbstractConfigValue kept; + if (first == null) + kept = second; + else if (second == null) + kept = first; + else + kept = first.withFallback(second); + + merged.put(key, kept); + + if (first != kept) + changed = true; + + if (kept.resolveStatus() == ResolveStatus.UNRESOLVED) + allResolved = false; + } + + ResolveStatus newResolveStatus = ResolveStatus.fromBoolean(allResolved); + boolean newIgnoresFallbacks = fallback.ignoresFallbacks(); + + if (changed) + return new SimpleConfigObject(mergeOrigins(this, fallback), merged, newResolveStatus, + newIgnoresFallbacks); + else if (newResolveStatus != resolveStatus() || newIgnoresFallbacks != ignoresFallbacks()) + return newCopy(newResolveStatus, origin(), newIgnoresFallbacks); + else + return this; + } + + private SimpleConfigObject modify(NoExceptionsModifier modifier) { + try { + return modifyMayThrow(modifier); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new ConfigException.BugOrBroken("unexpected checked exception", e); + } + } + + private SimpleConfigObject modifyMayThrow(Modifier modifier) throws Exception { + Map changes = null; + for (String k : keySet()) { + AbstractConfigValue v = value.get(k); + // "modified" may be null, which means remove the child; + // to do that we put null in the "changes" map. + AbstractConfigValue modified = modifier.modifyChildMayThrow(k, v); + if (modified != v) { + if (changes == null) + changes = new HashMap(); + changes.put(k, modified); + } + } + if (changes == null) { + return this; + } else { + Map modified = new HashMap(); + boolean sawUnresolved = false; + for (String k : keySet()) { + if (changes.containsKey(k)) { + AbstractConfigValue newValue = changes.get(k); + if (newValue != null) { + modified.put(k, newValue); + if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED) + sawUnresolved = true; + } else { + // remove this child; don't put it in the new map. + } + } else { + AbstractConfigValue newValue = value.get(k); + modified.put(k, newValue); + if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED) + sawUnresolved = true; + } + } + return new SimpleConfigObject(origin(), modified, + sawUnresolved ? ResolveStatus.UNRESOLVED : ResolveStatus.RESOLVED, + ignoresFallbacks()); + } + } + + private static final class ResolveModifier implements Modifier { + + final Path originalRestrict; + ResolveContext context; + final ResolveSource source; + + ResolveModifier(ResolveContext context, ResolveSource source) { + this.context = context; + this.source = source; + originalRestrict = context.restrictToChild(); + } + + @Override + public AbstractConfigValue modifyChildMayThrow(String key, AbstractConfigValue v) throws NotPossibleToResolve { + if (context.isRestrictedToChild()) { + if (key.equals(context.restrictToChild().first())) { + Path remainder = context.restrictToChild().remainder(); + if (remainder != null) { + ResolveResult result = context.restrict(remainder).resolve(v, + source); + context = result.context.unrestricted().restrict(originalRestrict); + return result.value; + } else { + // we don't want to resolve the leaf child. + return v; + } + } else { + // not in the restrictToChild path + return v; + } + } else { + // no restrictToChild, resolve everything + ResolveResult result = context.unrestricted().resolve(v, source); + context = result.context.unrestricted().restrict(originalRestrict); + return result.value; + } + } + + } + + @Override + ResolveResult resolveSubstitutions(ResolveContext context, ResolveSource source) + throws NotPossibleToResolve { + if (resolveStatus() == ResolveStatus.RESOLVED) + return ResolveResult.make(context, this); + + final ResolveSource sourceWithParent = source.pushParent(this); + + try { + ResolveModifier modifier = new ResolveModifier(context, sourceWithParent); + + AbstractConfigValue value = modifyMayThrow(modifier); + return ResolveResult.make(modifier.context, value).asObjectResult(); + } catch (NotPossibleToResolve e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new ConfigException.BugOrBroken("unexpected checked exception", e); + } + } + + @Override + SimpleConfigObject relativized(final Path prefix) { + return modify(new NoExceptionsModifier() { + + @Override + public AbstractConfigValue modifyChild(String key, AbstractConfigValue v) { + return v.relativized(prefix); + } + + }); + } + + // this is only Serializable to chill out a findbugs warning + static final private class RenderComparator implements java.util.Comparator, Serializable { + private static final long serialVersionUID = 1L; + + private static boolean isAllDigits(String s) { + int length = s.length(); + + // empty string doesn't count as a number + if (length == 0) + return false; + + for (int i = 0; i < length; ++i) { + char c = s.charAt(i); + + if (Character.isDigit(c)) + continue; + else + return false; + } + return true; + } + + // This is supposed to sort numbers before strings, + // and sort the numbers numerically. The point is + // to make objects which are really list-like + // (numeric indices) appear in order. + @Override + public int compare(String a, String b) { + boolean aDigits = isAllDigits(a); + boolean bDigits = isAllDigits(b); + if (aDigits && bDigits) { + return Integer.compare(Integer.parseInt(a), Integer.parseInt(b)); + } else if (aDigits) { + return -1; + } else if (bDigits) { + return 1; + } else { + return a.compareTo(b); + } + } + } + + @Override + protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { + if (isEmpty()) { + sb.append("{}"); + } else { + boolean outerBraces = options.getJson() || !atRoot; + + int innerIndent; + if (outerBraces) { + innerIndent = indent + 1; + sb.append("{"); + + if (options.getFormatted()) + sb.append('\n'); + } else { + innerIndent = indent; + } + + int separatorCount = 0; + String[] keys = keySet().toArray(new String[size()]); + Arrays.sort(keys, new RenderComparator()); + int count = 0; + for (String k : keys) { + count++; + AbstractConfigValue v; + v = value.get(k); + + if (options.getOriginComments()) { + String[] lines = v.origin().description().split("\n"); + for (String l : lines) { + indent(sb, indent + 1, options); + sb.append('#'); + if (!l.isEmpty()) + sb.append(' '); + sb.append(l); + sb.append("\n"); + } + } + if (options.getComments()) { + if (count > 1) { + sb.append('\n'); + if (!v.origin().comments().isEmpty()) { + sb.append('\n'); + } + } + for (String comment : v.origin().comments()) { + indent(sb, innerIndent, options); + sb.append("#"); + if (!comment.startsWith(" ")) + sb.append(' '); + sb.append(comment); + sb.append("\n"); + } + } + indent(sb, innerIndent, options); + v.render(sb, innerIndent, false /* atRoot */, k, options); + + if (options.getFormatted()) { + if (options.getJson()) { + sb.append(","); + separatorCount = 2; + } else { + separatorCount = 1; + } + sb.append('\n'); + } else { + sb.append(","); + separatorCount = 1; + } + } + // chop last commas/newlines + sb.setLength(sb.length() - separatorCount); + + if (outerBraces) { + if (options.getFormatted()) { + sb.append('\n'); // put a newline back + if (outerBraces) + indent(sb, indent, options); + } + sb.append("}"); + } + } + if (atRoot && options.getFormatted()) + sb.append('\n'); + } + + @Override + public AbstractConfigValue get(Object key) { + return value.get(key); + } + + private static boolean mapEquals(Map a, Map b) { + if (a == b) + return true; + + Set aKeys = a.keySet(); + Set bKeys = b.keySet(); + + if (!aKeys.equals(bKeys)) + return false; + + for (String key : aKeys) { + if (!a.get(key).equals(b.get(key))) + return false; + } + return true; + } + + private static int mapHash(Map m) { + // the keys have to be sorted, otherwise we could be equal + // to another map but have a different hashcode. + List keys = new ArrayList(); + keys.addAll(m.keySet()); + Collections.sort(keys); + + int valuesHash = 0; + for (String k : keys) { + valuesHash += m.get(k).hashCode(); + } + return 41 * (41 + keys.hashCode()) + valuesHash; + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof ConfigObject; + } + + @Override + public boolean equals(Object other) { + // note that "origin" is deliberately NOT part of equality. + // neither are other "extras" like ignoresFallbacks or resolve status. + if (other instanceof ConfigObject) { + // optimization to avoid unwrapped() for two ConfigObject, + // which is what AbstractConfigValue does. + return canEqual(other) && mapEquals(this, ((ConfigObject) other)); + } else { + return false; + } + } + + @Override + public int hashCode() { + // note that "origin" is deliberately NOT part of equality + // neither are other "extras" like ignoresFallbacks or resolve status. + return mapHash(this); + } + + @Override + public boolean containsKey(Object key) { + return value.containsKey(key); + } + + @Override + public Set keySet() { + return value.keySet(); + } + + @Override + public boolean containsValue(Object v) { + return value.containsValue(v); + } + + @Override + public Set> entrySet() { + // total bloat just to work around lack of type variance + + HashSet> entries = new HashSet>(); + for (Map.Entry e : value.entrySet()) { + entries.add(new AbstractMap.SimpleImmutableEntry( + e.getKey(), e + .getValue())); + } + return entries; + } + + @Override + public boolean isEmpty() { + return value.isEmpty(); + } + + @Override + public int size() { + return value.size(); + } + + @Override + public Collection values() { + return new HashSet(value.values()); + } + + final private static String EMPTY_NAME = "empty config"; + final private static SimpleConfigObject emptyInstance = empty(SimpleConfigOrigin + .newSimple(EMPTY_NAME)); + + final static SimpleConfigObject empty() { + return emptyInstance; + } + + final static SimpleConfigObject empty(ConfigOrigin origin) { + if (origin == null) + return empty(); + else + return new SimpleConfigObject(origin, + Collections. emptyMap()); + } + + final static SimpleConfigObject emptyMissing(ConfigOrigin baseOrigin) { + return new SimpleConfigObject(SimpleConfigOrigin.newSimple( + baseOrigin.description() + " (not found)"), + Collections. emptyMap()); + } + + // serialization all goes through SerializedConfigValue + private Object writeReplace() throws ObjectStreamException { + return new SerializedConfigValue(this); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigOrigin.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigOrigin.java new file mode 100644 index 0000000..790fccb --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleConfigOrigin.java @@ -0,0 +1,575 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.impl.SerializedConfigValue.SerializedField; + +// it would be cleaner to have a class hierarchy for various origin types, +// but was hoping this would be enough simpler to be a little messy. eh. +final class SimpleConfigOrigin implements ConfigOrigin { + + final private String description; + final private int lineNumber; + final private int endLineNumber; + final private OriginType originType; + final private String urlOrNull; + final private String resourceOrNull; + final private List commentsOrNull; + + protected SimpleConfigOrigin(String description, int lineNumber, int endLineNumber, OriginType originType, + String urlOrNull, String resourceOrNull, List commentsOrNull) { + if (description == null) + throw new ConfigException.BugOrBroken("description may not be null"); + this.description = description; + this.lineNumber = lineNumber; + this.endLineNumber = endLineNumber; + this.originType = originType; + this.urlOrNull = urlOrNull; + this.resourceOrNull = resourceOrNull; + this.commentsOrNull = commentsOrNull; + } + + static SimpleConfigOrigin newSimple(String description) { + return new SimpleConfigOrigin(description, -1, -1, OriginType.GENERIC, null, null, null); + } + + static SimpleConfigOrigin newFile(String filename) { + String url; + try { + url = (new File(filename)).toURI().toURL().toExternalForm(); + } catch (MalformedURLException e) { + url = null; + } + return new SimpleConfigOrigin(filename, -1, -1, OriginType.FILE, url, null, null); + } + + static SimpleConfigOrigin newURL(URL url) { + String u = url.toExternalForm(); + return new SimpleConfigOrigin(u, -1, -1, OriginType.URL, u, null, null); + } + + static SimpleConfigOrigin newResource(String resource, URL url) { + String desc; + if (url != null) + desc = resource + " @ " + url.toExternalForm(); + else + desc = resource; + return new SimpleConfigOrigin(desc, -1, -1, OriginType.RESOURCE, url != null ? url.toExternalForm() : null, + resource, null); + } + + static SimpleConfigOrigin newResource(String resource) { + return newResource(resource, null); + } + + @Override + public SimpleConfigOrigin withLineNumber(int lineNumber) { + if (lineNumber == this.lineNumber && lineNumber == this.endLineNumber) { + return this; + } else { + return new SimpleConfigOrigin(this.description, lineNumber, lineNumber, this.originType, this.urlOrNull, + this.resourceOrNull, this.commentsOrNull); + } + } + + SimpleConfigOrigin addURL(URL url) { + return new SimpleConfigOrigin(this.description, this.lineNumber, this.endLineNumber, this.originType, + url != null ? url.toExternalForm() : null, this.resourceOrNull, this.commentsOrNull); + } + + @Override + public SimpleConfigOrigin withComments(List comments) { + if (ConfigImplUtil.equalsHandlingNull(comments, this.commentsOrNull)) { + return this; + } else { + return new SimpleConfigOrigin(this.description, this.lineNumber, this.endLineNumber, this.originType, + this.urlOrNull, this.resourceOrNull, comments); + } + } + + SimpleConfigOrigin prependComments(List comments) { + if (ConfigImplUtil.equalsHandlingNull(comments, this.commentsOrNull) || comments == null) { + return this; + } else if (this.commentsOrNull == null) { + return withComments(comments); + } else { + List merged = new ArrayList(comments.size() + this.commentsOrNull.size()); + merged.addAll(comments); + merged.addAll(this.commentsOrNull); + return withComments(merged); + } + } + + SimpleConfigOrigin appendComments(List comments) { + if (ConfigImplUtil.equalsHandlingNull(comments, this.commentsOrNull) || comments == null) { + return this; + } else if (this.commentsOrNull == null) { + return withComments(comments); + } else { + List merged = new ArrayList(comments.size() + this.commentsOrNull.size()); + merged.addAll(this.commentsOrNull); + merged.addAll(comments); + return withComments(merged); + } + } + + @Override + public String description() { + if (lineNumber < 0) { + return description; + } else if (endLineNumber == lineNumber) { + return description + ": " + lineNumber; + } else { + return description + ": " + lineNumber + "-" + endLineNumber; + } + } + + @Override + public boolean equals(Object other) { + if (other instanceof SimpleConfigOrigin) { + SimpleConfigOrigin otherOrigin = (SimpleConfigOrigin) other; + + return this.description.equals(otherOrigin.description) && this.lineNumber == otherOrigin.lineNumber + && this.endLineNumber == otherOrigin.endLineNumber && this.originType == otherOrigin.originType + && ConfigImplUtil.equalsHandlingNull(this.urlOrNull, otherOrigin.urlOrNull) + && ConfigImplUtil.equalsHandlingNull(this.resourceOrNull, otherOrigin.resourceOrNull); + } else { + return false; + } + } + + @Override + public int hashCode() { + int h = 41 * (41 + description.hashCode()); + h = 41 * (h + lineNumber); + h = 41 * (h + endLineNumber); + h = 41 * (h + originType.hashCode()); + if (urlOrNull != null) + h = 41 * (h + urlOrNull.hashCode()); + if (resourceOrNull != null) + h = 41 * (h + resourceOrNull.hashCode()); + return h; + } + + @Override + public String toString() { + return "ConfigOrigin(" + description + ")"; + } + + @Override + public String filename() { + if (originType == OriginType.FILE) { + return description; + } else if (urlOrNull != null) { + URL url; + try { + url = new URL(urlOrNull); + } catch (MalformedURLException e) { + return null; + } + if (url.getProtocol().equals("file")) { + return url.getFile(); + } else { + return null; + } + } else { + return null; + } + } + + @Override + public URL url() { + if (urlOrNull == null) { + return null; + } else { + try { + return new URL(urlOrNull); + } catch (MalformedURLException e) { + return null; + } + } + } + + @Override + public String resource() { + return resourceOrNull; + } + + @Override + public int lineNumber() { + return lineNumber; + } + + @Override + public List comments() { + if (commentsOrNull != null) { + return Collections.unmodifiableList(commentsOrNull); + } else { + return Collections.emptyList(); + } + } + + static final String MERGE_OF_PREFIX = "merge of "; + + private static SimpleConfigOrigin mergeTwo(SimpleConfigOrigin a, SimpleConfigOrigin b) { + String mergedDesc; + int mergedStartLine; + int mergedEndLine; + List mergedComments; + + OriginType mergedType; + if (a.originType == b.originType) { + mergedType = a.originType; + } else { + mergedType = OriginType.GENERIC; + } + + // first use the "description" field which has no line numbers + // cluttering it. + String aDesc = a.description; + String bDesc = b.description; + if (aDesc.startsWith(MERGE_OF_PREFIX)) + aDesc = aDesc.substring(MERGE_OF_PREFIX.length()); + if (bDesc.startsWith(MERGE_OF_PREFIX)) + bDesc = bDesc.substring(MERGE_OF_PREFIX.length()); + + if (aDesc.equals(bDesc)) { + mergedDesc = aDesc; + + if (a.lineNumber < 0) + mergedStartLine = b.lineNumber; + else if (b.lineNumber < 0) + mergedStartLine = a.lineNumber; + else + mergedStartLine = Math.min(a.lineNumber, b.lineNumber); + + mergedEndLine = Math.max(a.endLineNumber, b.endLineNumber); + } else { + // this whole merge song-and-dance was intended to avoid this case + // whenever possible, but we've lost. Now we have to lose some + // structured information and cram into a string. + + // description() method includes line numbers, so use it instead + // of description field. + String aFull = a.description(); + String bFull = b.description(); + if (aFull.startsWith(MERGE_OF_PREFIX)) + aFull = aFull.substring(MERGE_OF_PREFIX.length()); + if (bFull.startsWith(MERGE_OF_PREFIX)) + bFull = bFull.substring(MERGE_OF_PREFIX.length()); + + mergedDesc = MERGE_OF_PREFIX + aFull + "," + bFull; + + mergedStartLine = -1; + mergedEndLine = -1; + } + + String mergedURL; + if (ConfigImplUtil.equalsHandlingNull(a.urlOrNull, b.urlOrNull)) { + mergedURL = a.urlOrNull; + } else { + mergedURL = null; + } + + String mergedResource; + if (ConfigImplUtil.equalsHandlingNull(a.resourceOrNull, b.resourceOrNull)) { + mergedResource = a.resourceOrNull; + } else { + mergedResource = null; + } + + if (ConfigImplUtil.equalsHandlingNull(a.commentsOrNull, b.commentsOrNull)) { + mergedComments = a.commentsOrNull; + } else { + mergedComments = new ArrayList(); + if (a.commentsOrNull != null) + mergedComments.addAll(a.commentsOrNull); + if (b.commentsOrNull != null) + mergedComments.addAll(b.commentsOrNull); + } + + return new SimpleConfigOrigin(mergedDesc, mergedStartLine, mergedEndLine, mergedType, mergedURL, + mergedResource, mergedComments); + } + + private static int similarity(SimpleConfigOrigin a, SimpleConfigOrigin b) { + int count = 0; + + if (a.originType == b.originType) + count += 1; + + if (a.description.equals(b.description)) { + count += 1; + + // only count these if the description field (which is the file + // or resource name) also matches. + if (a.lineNumber == b.lineNumber) + count += 1; + if (a.endLineNumber == b.endLineNumber) + count += 1; + if (ConfigImplUtil.equalsHandlingNull(a.urlOrNull, b.urlOrNull)) + count += 1; + if (ConfigImplUtil.equalsHandlingNull(a.resourceOrNull, b.resourceOrNull)) + count += 1; + } + + return count; + } + + // this picks the best pair to merge, because the pair has the most in + // common. we want to merge two lines in the same file rather than something + // else with one of the lines; because two lines in the same file can be + // better consolidated. + private static SimpleConfigOrigin mergeThree(SimpleConfigOrigin a, SimpleConfigOrigin b, SimpleConfigOrigin c) { + if (similarity(a, b) >= similarity(b, c)) { + return mergeTwo(mergeTwo(a, b), c); + } else { + return mergeTwo(a, mergeTwo(b, c)); + } + } + + static ConfigOrigin mergeOrigins(ConfigOrigin a, ConfigOrigin b) { + return mergeTwo((SimpleConfigOrigin) a, (SimpleConfigOrigin) b); + } + + static ConfigOrigin mergeOrigins(List stack) { + List origins = new ArrayList(stack.size()); + for (AbstractConfigValue v : stack) { + origins.add(v.origin()); + } + return mergeOrigins(origins); + } + + static ConfigOrigin mergeOrigins(Collection stack) { + if (stack.isEmpty()) { + throw new ConfigException.BugOrBroken("can't merge empty list of origins"); + } else if (stack.size() == 1) { + return stack.iterator().next(); + } else if (stack.size() == 2) { + Iterator i = stack.iterator(); + return mergeTwo((SimpleConfigOrigin) i.next(), (SimpleConfigOrigin) i.next()); + } else { + List remaining = new ArrayList(); + for (ConfigOrigin o : stack) { + remaining.add((SimpleConfigOrigin) o); + } + while (remaining.size() > 2) { + SimpleConfigOrigin c = remaining.get(remaining.size() - 1); + remaining.remove(remaining.size() - 1); + SimpleConfigOrigin b = remaining.get(remaining.size() - 1); + remaining.remove(remaining.size() - 1); + SimpleConfigOrigin a = remaining.get(remaining.size() - 1); + remaining.remove(remaining.size() - 1); + + SimpleConfigOrigin merged = mergeThree(a, b, c); + + remaining.add(merged); + } + + // should be down to either 1 or 2 + return mergeOrigins(remaining); + } + } + + Map toFields() { + Map m = new EnumMap(SerializedField.class); + + m.put(SerializedField.ORIGIN_DESCRIPTION, description); + + if (lineNumber >= 0) + m.put(SerializedField.ORIGIN_LINE_NUMBER, lineNumber); + if (endLineNumber >= 0) + m.put(SerializedField.ORIGIN_END_LINE_NUMBER, endLineNumber); + + m.put(SerializedField.ORIGIN_TYPE, originType.ordinal()); + + if (urlOrNull != null) + m.put(SerializedField.ORIGIN_URL, urlOrNull); + if (resourceOrNull != null) + m.put(SerializedField.ORIGIN_RESOURCE, resourceOrNull); + if (commentsOrNull != null) + m.put(SerializedField.ORIGIN_COMMENTS, commentsOrNull); + + return m; + } + + Map toFieldsDelta(SimpleConfigOrigin baseOrigin) { + Map baseFields; + if (baseOrigin != null) + baseFields = baseOrigin.toFields(); + else + baseFields = Collections. emptyMap(); + return fieldsDelta(baseFields, toFields()); + } + + // Here we're trying to avoid serializing the same info over and over + // in the common case that child objects have the same origin fields + // as their parent objects. e.g. we don't need to store the source + // filename with every single value. + static Map fieldsDelta(Map base, + Map child) { + Map m = new EnumMap(child); + + for (Map.Entry baseEntry : base.entrySet()) { + SerializedField f = baseEntry.getKey(); + if (m.containsKey(f) && ConfigImplUtil.equalsHandlingNull(baseEntry.getValue(), m.get(f))) { + // if field is unchanged, just remove it so we inherit + m.remove(f); + } else if (!m.containsKey(f)) { + // if field has been removed, we have to add a deletion entry + switch (f) { + case ORIGIN_DESCRIPTION: + throw new ConfigException.BugOrBroken("origin missing description field? " + child); + case ORIGIN_LINE_NUMBER: + m.put(SerializedField.ORIGIN_LINE_NUMBER, -1); + break; + case ORIGIN_END_LINE_NUMBER: + m.put(SerializedField.ORIGIN_END_LINE_NUMBER, -1); + break; + case ORIGIN_TYPE: + throw new ConfigException.BugOrBroken("should always be an ORIGIN_TYPE field"); + case ORIGIN_URL: + m.put(SerializedField.ORIGIN_NULL_URL, ""); + break; + case ORIGIN_RESOURCE: + m.put(SerializedField.ORIGIN_NULL_RESOURCE, ""); + break; + case ORIGIN_COMMENTS: + m.put(SerializedField.ORIGIN_NULL_COMMENTS, ""); + break; + case ORIGIN_NULL_URL: // FALL THRU + case ORIGIN_NULL_RESOURCE: // FALL THRU + case ORIGIN_NULL_COMMENTS: + throw new ConfigException.BugOrBroken("computing delta, base object should not contain " + f + " " + + base); + case END_MARKER: + case ROOT_VALUE: + case ROOT_WAS_CONFIG: + case UNKNOWN: + case VALUE_DATA: + case VALUE_ORIGIN: + throw new ConfigException.BugOrBroken("should not appear here: " + f); + } + } else { + // field is in base and child, but differs, so leave it + } + } + + return m; + } + + static SimpleConfigOrigin fromFields(Map m) throws IOException { + // we represent a null origin as one with no fields at all + if (m.isEmpty()) + return null; + + String description = (String) m.get(SerializedField.ORIGIN_DESCRIPTION); + Integer lineNumber = (Integer) m.get(SerializedField.ORIGIN_LINE_NUMBER); + Integer endLineNumber = (Integer) m.get(SerializedField.ORIGIN_END_LINE_NUMBER); + Number originTypeOrdinal = (Number) m.get(SerializedField.ORIGIN_TYPE); + if (originTypeOrdinal == null) + throw new IOException("Missing ORIGIN_TYPE field"); + OriginType originType = OriginType.values()[originTypeOrdinal.byteValue()]; + String urlOrNull = (String) m.get(SerializedField.ORIGIN_URL); + String resourceOrNull = (String) m.get(SerializedField.ORIGIN_RESOURCE); + @SuppressWarnings("unchecked") + List commentsOrNull = (List) m.get(SerializedField.ORIGIN_COMMENTS); + // Older versions did not have a resource field, they stuffed it into + // the description. + if (originType == OriginType.RESOURCE && resourceOrNull == null) { + resourceOrNull = description; + } + return new SimpleConfigOrigin(description, lineNumber != null ? lineNumber : -1, + endLineNumber != null ? endLineNumber : -1, originType, urlOrNull, resourceOrNull, commentsOrNull); + } + + static Map applyFieldsDelta(Map base, + Map delta) throws IOException { + + Map m = new EnumMap(delta); + + for (Map.Entry baseEntry : base.entrySet()) { + SerializedField f = baseEntry.getKey(); + if (delta.containsKey(f)) { + // delta overrides when keys are in both + // "m" should already contain the right thing + } else { + // base has the key and delta does not. + // we inherit from base unless a "NULL" key blocks. + switch (f) { + case ORIGIN_DESCRIPTION: + m.put(f, base.get(f)); + break; + case ORIGIN_URL: + if (delta.containsKey(SerializedField.ORIGIN_NULL_URL)) { + m.remove(SerializedField.ORIGIN_NULL_URL); + } else { + m.put(f, base.get(f)); + } + break; + case ORIGIN_RESOURCE: + if (delta.containsKey(SerializedField.ORIGIN_NULL_RESOURCE)) { + m.remove(SerializedField.ORIGIN_NULL_RESOURCE); + } else { + m.put(f, base.get(f)); + } + break; + case ORIGIN_COMMENTS: + if (delta.containsKey(SerializedField.ORIGIN_NULL_COMMENTS)) { + m.remove(SerializedField.ORIGIN_NULL_COMMENTS); + } else { + m.put(f, base.get(f)); + } + break; + case ORIGIN_NULL_URL: // FALL THRU + case ORIGIN_NULL_RESOURCE: // FALL THRU + case ORIGIN_NULL_COMMENTS: // FALL THRU + // base objects shouldn't contain these, should just + // lack the field. these are only in deltas. + throw new ConfigException.BugOrBroken("applying fields, base object should not contain " + f + " " + + base); + case ORIGIN_END_LINE_NUMBER: // FALL THRU + case ORIGIN_LINE_NUMBER: // FALL THRU + case ORIGIN_TYPE: + m.put(f, base.get(f)); + break; + + case END_MARKER: + case ROOT_VALUE: + case ROOT_WAS_CONFIG: + case UNKNOWN: + case VALUE_DATA: + case VALUE_ORIGIN: + throw new ConfigException.BugOrBroken("should not appear here: " + f); + } + } + } + return m; + } + + static SimpleConfigOrigin fromBase(SimpleConfigOrigin baseOrigin, Map delta) + throws IOException { + Map baseFields; + if (baseOrigin != null) + baseFields = baseOrigin.toFields(); + else + baseFields = Collections. emptyMap(); + Map fields = applyFieldsDelta(baseFields, delta); + return fromFields(fields); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleIncludeContext.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleIncludeContext.java new file mode 100644 index 0000000..b81d990 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleIncludeContext.java @@ -0,0 +1,51 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncludeContext; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseable; + +class SimpleIncludeContext implements ConfigIncludeContext { + + private final Parseable parseable; + private final ConfigParseOptions options; + + SimpleIncludeContext(Parseable parseable) { + this.parseable = parseable; + this.options = SimpleIncluder.clearForInclude(parseable.options()); + } + + private SimpleIncludeContext(Parseable parseable, ConfigParseOptions options) { + this.parseable = parseable; + this.options = options; + } + + SimpleIncludeContext withParseable(Parseable parseable) { + if (parseable == this.parseable) + return this; + else + return new SimpleIncludeContext(parseable); + } + + @Override + public ConfigParseable relativeTo(String filename) { + if (ConfigImpl.traceLoadsEnabled()) + ConfigImpl.trace("Looking for '" + filename + "' relative to " + parseable); + if (parseable != null) + return parseable.relativeTo(filename); + else + return null; + } + + @Override + public ConfigParseOptions parseOptions() { + return options; + } + + @Override + public ConfigIncludeContext setParseOptions(ConfigParseOptions options) { + return new SimpleIncludeContext(parseable, options.setSyntax(null).setOriginDescription(null)); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleIncluder.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleIncluder.java new file mode 100644 index 0000000..04c30be --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SimpleIncluder.java @@ -0,0 +1,302 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigFactory; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncludeContext; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluder; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderClasspath; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderFile; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderURL; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseable; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax; + +class SimpleIncluder implements FullIncluder { + + private ConfigIncluder fallback; + + SimpleIncluder(ConfigIncluder fallback) { + this.fallback = fallback; + } + + // ConfigIncludeContext does this for us on its options + static ConfigParseOptions clearForInclude(ConfigParseOptions options) { + // the class loader and includer are inherited, but not this other + // stuff. + return options.setSyntax(null).setOriginDescription(null).setAllowMissing(true); + } + + // this is the heuristic includer + @Override + public ConfigObject include(final ConfigIncludeContext context, String name) { + ConfigObject obj = includeWithoutFallback(context, name); + + // now use the fallback includer if any and merge + // its result. + if (fallback != null) { + return obj.withFallback(fallback.include(context, name)); + } else { + return obj; + } + } + + // the heuristic includer in static form + static ConfigObject includeWithoutFallback(final ConfigIncludeContext context, String name) { + // the heuristic is valid URL then URL, else relative to including file; + // relativeTo in a file falls back to classpath inside relativeTo(). + + URL url; + try { + url = new URL(name); + } catch (MalformedURLException e) { + url = null; + } + + if (url != null) { + return includeURLWithoutFallback(context, url); + } else { + NameSource source = new RelativeNameSource(context); + return fromBasename(source, name, context.parseOptions()); + } + } + + @Override + public ConfigObject includeURL(ConfigIncludeContext context, URL url) { + ConfigObject obj = includeURLWithoutFallback(context, url); + + // now use the fallback includer if any and merge + // its result. + if (fallback != null && fallback instanceof ConfigIncluderURL) { + return obj.withFallback(((ConfigIncluderURL) fallback).includeURL(context, url)); + } else { + return obj; + } + } + + static ConfigObject includeURLWithoutFallback(final ConfigIncludeContext context, URL url) { + return ConfigFactory.parseURL(url, context.parseOptions()).root(); + } + + @Override + public ConfigObject includeFile(ConfigIncludeContext context, File file) { + ConfigObject obj = includeFileWithoutFallback(context, file); + + // now use the fallback includer if any and merge + // its result. + if (fallback != null && fallback instanceof ConfigIncluderFile) { + return obj.withFallback(((ConfigIncluderFile) fallback).includeFile(context, file)); + } else { + return obj; + } + } + + static ConfigObject includeFileWithoutFallback(final ConfigIncludeContext context, File file) { + return ConfigFactory.parseFileAnySyntax(file, context.parseOptions()).root(); + } + + @Override + public ConfigObject includeResources(ConfigIncludeContext context, String resource) { + ConfigObject obj = includeResourceWithoutFallback(context, resource); + + // now use the fallback includer if any and merge + // its result. + if (fallback != null && fallback instanceof ConfigIncluderClasspath) { + return obj.withFallback(((ConfigIncluderClasspath) fallback).includeResources(context, + resource)); + } else { + return obj; + } + } + + static ConfigObject includeResourceWithoutFallback(final ConfigIncludeContext context, + String resource) { + return ConfigFactory.parseResourcesAnySyntax(resource, context.parseOptions()).root(); + } + + @Override + public ConfigIncluder withFallback(ConfigIncluder fallback) { + if (this == fallback) { + throw new ConfigException.BugOrBroken("trying to create includer cycle"); + } else if (this.fallback == fallback) { + return this; + } else if (this.fallback != null) { + return new SimpleIncluder(this.fallback.withFallback(fallback)); + } else { + return new SimpleIncluder(fallback); + } + } + + interface NameSource { + ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions); + } + + static private class RelativeNameSource implements NameSource { + final private ConfigIncludeContext context; + + RelativeNameSource(ConfigIncludeContext context) { + this.context = context; + } + + @Override + public ConfigParseable nameToParseable(String name, ConfigParseOptions options) { + ConfigParseable p = context.relativeTo(name); + if (p == null) { + // avoid returning null + return Parseable + .newNotFound(name, "include was not found: '" + name + "'", options); + } else { + return p; + } + } + }; + + // this function is a little tricky because there are three places we're + // trying to use it; for 'include "basename"' in a .conf file, for + // loading app.{conf,json,properties} from classpath, and for + // loading app.{conf,json,properties} from the filesystem. + static ConfigObject fromBasename(NameSource source, String name, ConfigParseOptions options) { + ConfigObject obj; + if (name.endsWith(".conf") || name.endsWith(".json") || name.endsWith(".properties")) { + ConfigParseable p = source.nameToParseable(name, options); + + obj = p.parse(p.options().setAllowMissing(options.getAllowMissing())); + } else { + ConfigParseable confHandle = source.nameToParseable(name + ".conf", options); + ConfigParseable jsonHandle = source.nameToParseable(name + ".json", options); + ConfigParseable propsHandle = source.nameToParseable(name + ".properties", options); + boolean gotSomething = false; + List fails = new ArrayList(); + + ConfigSyntax syntax = options.getSyntax(); + + obj = SimpleConfigObject.empty(SimpleConfigOrigin.newSimple(name)); + if (syntax == null || syntax == ConfigSyntax.CONF) { + try { + obj = confHandle.parse(confHandle.options().setAllowMissing(false) + .setSyntax(ConfigSyntax.CONF)); + gotSomething = true; + } catch (ConfigException.IO e) { + fails.add(e); + } + } + + if (syntax == null || syntax == ConfigSyntax.JSON) { + try { + ConfigObject parsed = jsonHandle.parse(jsonHandle.options() + .setAllowMissing(false).setSyntax(ConfigSyntax.JSON)); + obj = obj.withFallback(parsed); + gotSomething = true; + } catch (ConfigException.IO e) { + fails.add(e); + } + } + + if (syntax == null || syntax == ConfigSyntax.PROPERTIES) { + try { + ConfigObject parsed = propsHandle.parse(propsHandle.options() + .setAllowMissing(false).setSyntax(ConfigSyntax.PROPERTIES)); + obj = obj.withFallback(parsed); + gotSomething = true; + } catch (ConfigException.IO e) { + fails.add(e); + } + } + + if (!options.getAllowMissing() && !gotSomething) { + if (ConfigImpl.traceLoadsEnabled()) { + // the individual exceptions should have been logged already + // with tracing enabled + ConfigImpl.trace("Did not find '" + name + + "' with any extension (.conf, .json, .properties); " + + "exceptions should have been logged above."); + } + + if (fails.isEmpty()) { + // this should not happen + throw new ConfigException.BugOrBroken( + "should not be reached: nothing found but no exceptions thrown"); + } else { + StringBuilder sb = new StringBuilder(); + for (Throwable t : fails) { + sb.append(t.getMessage()); + sb.append(", "); + } + sb.setLength(sb.length() - 2); + throw new ConfigException.IO(SimpleConfigOrigin.newSimple(name), sb.toString(), + fails.get(0)); + } + } else if (!gotSomething) { + if (ConfigImpl.traceLoadsEnabled()) { + ConfigImpl.trace("Did not find '" + name + + "' with any extension (.conf, .json, .properties); but '" + name + + "' is allowed to be missing. Exceptions from load attempts should have been logged above."); + } + } + } + + return obj; + } + + // the Proxy is a proxy for an application-provided includer that uses our + // default implementations when the application-provided includer doesn't + // have an implementation. + static private class Proxy implements FullIncluder { + final ConfigIncluder delegate; + + Proxy(ConfigIncluder delegate) { + this.delegate = delegate; + } + + @Override + public ConfigIncluder withFallback(ConfigIncluder fallback) { + // we never fall back + return this; + } + + @Override + public ConfigObject include(ConfigIncludeContext context, String what) { + return delegate.include(context, what); + } + + @Override + public ConfigObject includeResources(ConfigIncludeContext context, String what) { + if (delegate instanceof ConfigIncluderClasspath) + return ((ConfigIncluderClasspath) delegate).includeResources(context, what); + else + return includeResourceWithoutFallback(context, what); + } + + @Override + public ConfigObject includeURL(ConfigIncludeContext context, URL what) { + if (delegate instanceof ConfigIncluderURL) + return ((ConfigIncluderURL) delegate).includeURL(context, what); + else + return includeURLWithoutFallback(context, what); + } + + @Override + public ConfigObject includeFile(ConfigIncludeContext context, File what) { + if (delegate instanceof ConfigIncluderFile) + return ((ConfigIncluderFile) delegate).includeFile(context, what); + else + return includeFileWithoutFallback(context, what); + } + } + + static FullIncluder makeFull(ConfigIncluder includer) { + if (includer instanceof FullIncluder) + return (FullIncluder) includer; + else + return new Proxy(includer); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SubstitutionExpression.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SubstitutionExpression.java new file mode 100644 index 0000000..e8aab95 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/SubstitutionExpression.java @@ -0,0 +1,49 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +final class SubstitutionExpression { + + final private Path path; + final private boolean optional; + + SubstitutionExpression(Path path, boolean optional) { + this.path = path; + this.optional = optional; + } + + Path path() { + return path; + } + + boolean optional() { + return optional; + } + + SubstitutionExpression changePath(Path newPath) { + if (newPath == path) + return this; + else + return new SubstitutionExpression(newPath, optional); + } + + @Override + public String toString() { + return "${" + (optional ? "?" : "") + path.render() + "}"; + } + + @Override + public boolean equals(Object other) { + if (other instanceof SubstitutionExpression) { + SubstitutionExpression otherExp = (SubstitutionExpression) other; + return otherExp.path.equals(this.path) && otherExp.optional == this.optional; + } else { + return false; + } + } + + @Override + public int hashCode() { + int h = 41 * (41 + path.hashCode()); + h = 41 * (h + (optional ? 1 : 0)); + return h; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Token.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Token.java new file mode 100644 index 0000000..ee6dbee --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Token.java @@ -0,0 +1,87 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; + +class Token { + final private TokenType tokenType; + final private String debugString; + final private ConfigOrigin origin; + final private String tokenText; + + Token(TokenType tokenType, ConfigOrigin origin) { + this(tokenType, origin, null); + } + + Token(TokenType tokenType, ConfigOrigin origin, String tokenText) { + this(tokenType, origin, tokenText, null); + } + + Token(TokenType tokenType, ConfigOrigin origin, String tokenText, String debugString) { + this.tokenType = tokenType; + this.origin = origin; + this.debugString = debugString; + this.tokenText = tokenText; + } + + // this is used for singleton tokens like COMMA or OPEN_CURLY + static Token newWithoutOrigin(TokenType tokenType, String debugString, String tokenText) { + return new Token(tokenType, null, tokenText, debugString); + } + + final TokenType tokenType() { + return tokenType; + } + + public String tokenText() { return tokenText; } + + // this is final because we don't always use the origin() accessor, + // and we don't because it throws if origin is null + final ConfigOrigin origin() { + // code is only supposed to call origin() on token types that are + // expected to have an origin. + if (origin == null) + throw new ConfigException.BugOrBroken( + "tried to get origin from token that doesn't have one: " + this); + return origin; + } + + final int lineNumber() { + if (origin != null) + return origin.lineNumber(); + else + return -1; + } + + @Override + public String toString() { + if (debugString != null) + return debugString; + else + return tokenType.name(); + } + + protected boolean canEqual(Object other) { + return other instanceof Token; + } + + @Override + public boolean equals(Object other) { + if (other instanceof Token) { + // origin is deliberately left out + return canEqual(other) + && this.tokenType == ((Token) other).tokenType; + } else { + return false; + } + } + + @Override + public int hashCode() { + // origin is deliberately left out + return tokenType.hashCode(); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/TokenType.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/TokenType.java new file mode 100644 index 0000000..f3dd507 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/TokenType.java @@ -0,0 +1,24 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +enum TokenType { + START, + END, + COMMA, + EQUALS, + COLON, + OPEN_CURLY, + CLOSE_CURLY, + OPEN_SQUARE, + CLOSE_SQUARE, + VALUE, + NEWLINE, + UNQUOTED_TEXT, + IGNORED_WHITESPACE, + SUBSTITUTION, + PROBLEM, + COMMENT, + PLUS_EQUALS; +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Tokenizer.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Tokenizer.java new file mode 100644 index 0000000..e6d7a5c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Tokenizer.java @@ -0,0 +1,695 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax; + +final class Tokenizer { + // this exception should not leave this file + private static class ProblemException extends Exception { + private static final long serialVersionUID = 1L; + + final private Token problem; + + ProblemException(Token problem) { + this.problem = problem; + } + + Token problem() { + return problem; + } + } + + private static String asString(int codepoint) { + if (codepoint == '\n') + return "newline"; + else if (codepoint == '\t') + return "tab"; + else if (codepoint == -1) + return "end of file"; + else if (ConfigImplUtil.isC0Control(codepoint)) + return String.format("control character 0x%x", codepoint); + else + return String.format("%c", codepoint); + } + + /** + * Tokenizes a Reader. Does not close the reader; you have to arrange to do + * that after you're done with the returned iterator. + */ + static Iterator tokenize(ConfigOrigin origin, Reader input, ConfigSyntax flavor) { + return new TokenIterator(origin, input, flavor != ConfigSyntax.JSON); + } + + static String render(Iterator tokens) { + StringBuilder renderedText = new StringBuilder(); + while (tokens.hasNext()) { + renderedText.append(tokens.next().tokenText()); + } + return renderedText.toString(); + } + + private static class TokenIterator implements Iterator { + + private static class WhitespaceSaver { + // has to be saved inside value concatenations + private StringBuilder whitespace; + // may need to value-concat with next value + private boolean lastTokenWasSimpleValue; + + WhitespaceSaver() { + whitespace = new StringBuilder(); + lastTokenWasSimpleValue = false; + } + + void add(int c) { + whitespace.appendCodePoint(c); + } + + Token check(Token t, ConfigOrigin baseOrigin, int lineNumber) { + if (isSimpleValue(t)) { + return nextIsASimpleValue(baseOrigin, lineNumber); + } else { + return nextIsNotASimpleValue(baseOrigin, lineNumber); + } + } + + // called if the next token is not a simple value; + // discards any whitespace we were saving between + // simple values. + private Token nextIsNotASimpleValue(ConfigOrigin baseOrigin, int lineNumber) { + lastTokenWasSimpleValue = false; + return createWhitespaceTokenFromSaver(baseOrigin, lineNumber); + } + + // called if the next token IS a simple value, + // so creates a whitespace token if the previous + // token also was. + private Token nextIsASimpleValue(ConfigOrigin baseOrigin, + int lineNumber) { + Token t = createWhitespaceTokenFromSaver(baseOrigin, lineNumber); + if (!lastTokenWasSimpleValue) { + lastTokenWasSimpleValue = true; + } + return t; + } + + private Token createWhitespaceTokenFromSaver(ConfigOrigin baseOrigin, + int lineNumber) { + if (whitespace.length() > 0) { + Token t; + if (lastTokenWasSimpleValue) { + t = Tokens.newUnquotedText( + lineOrigin(baseOrigin, lineNumber), + whitespace.toString()); + } else { + t = Tokens.newIgnoredWhitespace(lineOrigin(baseOrigin, lineNumber), + whitespace.toString()); + } + whitespace.setLength(0); // reset + return t; + } + return null; + } + } + + final private SimpleConfigOrigin origin; + final private Reader input; + final private LinkedList buffer; + private int lineNumber; + private ConfigOrigin lineOrigin; + final private Queue tokens; + final private WhitespaceSaver whitespaceSaver; + final private boolean allowComments; + + TokenIterator(ConfigOrigin origin, Reader input, boolean allowComments) { + this.origin = (SimpleConfigOrigin) origin; + this.input = input; + this.allowComments = allowComments; + this.buffer = new LinkedList(); + lineNumber = 1; + lineOrigin = this.origin.withLineNumber(lineNumber); + tokens = new LinkedList(); + tokens.add(Tokens.START); + whitespaceSaver = new WhitespaceSaver(); + } + + + // this should ONLY be called from nextCharSkippingComments + // or when inside a quoted string, or when parsing a sequence + // like ${ or +=, everything else should use + // nextCharSkippingComments(). + private int nextCharRaw() { + if (buffer.isEmpty()) { + try { + return input.read(); + } catch (IOException e) { + throw new ConfigException.IO(origin, "read error: " + + e.getMessage(), e); + } + } else { + int c = buffer.pop(); + return c; + } + } + + private void putBack(int c) { + if (buffer.size() > 2) { + throw new ConfigException.BugOrBroken( + "bug: putBack() three times, undesirable look-ahead"); + } + buffer.push(c); + } + + static boolean isWhitespace(int c) { + return ConfigImplUtil.isWhitespace(c); + } + + static boolean isWhitespaceNotNewline(int c) { + return c != '\n' && ConfigImplUtil.isWhitespace(c); + } + + private boolean startOfComment(int c) { + if (c == -1) { + return false; + } else { + if (allowComments) { + if (c == '#') { + return true; + } else if (c == '/') { + int maybeSecondSlash = nextCharRaw(); + // we want to predictably NOT consume any chars + putBack(maybeSecondSlash); + if (maybeSecondSlash == '/') { + return true; + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + } + + // get next char, skipping non-newline whitespace + private int nextCharAfterWhitespace(WhitespaceSaver saver) { + for (;;) { + int c = nextCharRaw(); + + if (c == -1) { + return -1; + } else { + if (isWhitespaceNotNewline(c)) { + saver.add(c); + continue; + } else { + return c; + } + } + } + } + + private ProblemException problem(String message) { + return problem("", message, null); + } + + private ProblemException problem(String what, String message) { + return problem(what, message, null); + } + + private ProblemException problem(String what, String message, boolean suggestQuotes) { + return problem(what, message, suggestQuotes, null); + } + + private ProblemException problem(String what, String message, Throwable cause) { + return problem(lineOrigin, what, message, cause); + } + + private ProblemException problem(String what, String message, boolean suggestQuotes, + Throwable cause) { + return problem(lineOrigin, what, message, suggestQuotes, cause); + } + + private static ProblemException problem(ConfigOrigin origin, String what, + String message, + Throwable cause) { + return problem(origin, what, message, false, cause); + } + + private static ProblemException problem(ConfigOrigin origin, String what, String message, + boolean suggestQuotes, Throwable cause) { + if (what == null || message == null) + throw new ConfigException.BugOrBroken( + "internal error, creating bad ProblemException"); + return new ProblemException(Tokens.newProblem(origin, what, message, suggestQuotes, + cause)); + } + + private static ProblemException problem(ConfigOrigin origin, String message) { + return problem(origin, "", message, null); + } + + private static ConfigOrigin lineOrigin(ConfigOrigin baseOrigin, + int lineNumber) { + return ((SimpleConfigOrigin) baseOrigin).withLineNumber(lineNumber); + } + + // ONE char has always been consumed, either the # or the first /, but + // not both slashes + private Token pullComment(int firstChar) { + boolean doubleSlash = false; + if (firstChar == '/') { + int discard = nextCharRaw(); + if (discard != '/') + throw new ConfigException.BugOrBroken("called pullComment but // not seen"); + doubleSlash = true; + } + + StringBuilder sb = new StringBuilder(); + for (;;) { + int c = nextCharRaw(); + if (c == -1 || c == '\n') { + putBack(c); + if (doubleSlash) + return Tokens.newCommentDoubleSlash(lineOrigin, sb.toString()); + else + return Tokens.newCommentHash(lineOrigin, sb.toString()); + } else { + sb.appendCodePoint(c); + } + } + } + + // chars JSON allows a number to start with + static final String firstNumberChars = "0123456789-"; + // chars JSON allows to be part of a number + static final String numberChars = "0123456789eE+-."; + // chars that stop an unquoted string + static final String notInUnquotedText = "$\"{}[]:=,+#`^?!@*&\\"; + + // The rules here are intended to maximize convenience while + // avoiding confusion with real valid JSON. Basically anything + // that parses as JSON is treated the JSON way and otherwise + // we assume it's a string and let the parser sort it out. + private Token pullUnquotedText() { + ConfigOrigin origin = lineOrigin; + StringBuilder sb = new StringBuilder(); + int c = nextCharRaw(); + while (true) { + if (c == -1) { + break; + } else if (notInUnquotedText.indexOf(c) >= 0) { + break; + } else if (isWhitespace(c)) { + break; + } else if (startOfComment(c)) { + break; + } else { + sb.appendCodePoint(c); + } + + // we parse true/false/null tokens as such no matter + // what is after them, as long as they are at the + // start of the unquoted token. + if (sb.length() == 4) { + String s = sb.toString(); + if (s.equals("true")) + return Tokens.newBoolean(origin, true); + else if (s.equals("null")) + return Tokens.newNull(origin); + } else if (sb.length() == 5) { + String s = sb.toString(); + if (s.equals("false")) + return Tokens.newBoolean(origin, false); + } + + c = nextCharRaw(); + } + + // put back the char that ended the unquoted text + putBack(c); + + String s = sb.toString(); + return Tokens.newUnquotedText(origin, s); + } + + private Token pullNumber(int firstChar) throws ProblemException { + StringBuilder sb = new StringBuilder(); + sb.appendCodePoint(firstChar); + boolean containedDecimalOrE = false; + int c = nextCharRaw(); + while (c != -1 && numberChars.indexOf(c) >= 0) { + if (c == '.' || c == 'e' || c == 'E') + containedDecimalOrE = true; + sb.appendCodePoint(c); + c = nextCharRaw(); + } + // the last character we looked at wasn't part of the number, put it + // back + putBack(c); + String s = sb.toString(); + try { + if (containedDecimalOrE) { + // force floating point representation + return Tokens.newDouble(lineOrigin, Double.parseDouble(s), s); + } else { + // this should throw if the integer is too large for Long + return Tokens.newLong(lineOrigin, Long.parseLong(s), s); + } + } catch (NumberFormatException e) { + // not a number after all, see if it's an unquoted string. + for (char u : s.toCharArray()) { + if (notInUnquotedText.indexOf(u) >= 0) + throw problem(asString(u), "Reserved character '" + asString(u) + + "' is not allowed outside quotes", true /* suggestQuotes */); + } + // no evil chars so we just decide this was a string and + // not a number. + return Tokens.newUnquotedText(lineOrigin, s); + } + } + + private void pullEscapeSequence(StringBuilder sb, StringBuilder sbOrig) throws ProblemException { + int escaped = nextCharRaw(); + if (escaped == -1) + throw problem("End of input but backslash in string had nothing after it"); + + // This is needed so we return the unescaped escape characters back out when rendering + // the token + sbOrig.appendCodePoint('\\'); + sbOrig.appendCodePoint(escaped); + + switch (escaped) { + case '"': + sb.append('"'); + break; + case '\\': + sb.append('\\'); + break; + case '/': + sb.append('/'); + break; + case 'b': + sb.append('\b'); + break; + case 'f': + sb.append('\f'); + break; + case 'n': + sb.append('\n'); + break; + case 'r': + sb.append('\r'); + break; + case 't': + sb.append('\t'); + break; + case 'u': { + // kind of absurdly slow, but screw it for now + char[] a = new char[4]; + for (int i = 0; i < 4; ++i) { + int c = nextCharRaw(); + if (c == -1) + throw problem("End of input but expecting 4 hex digits for \\uXXXX escape"); + a[i] = (char) c; + } + String digits = new String(a); + sbOrig.append(a); + try { + sb.appendCodePoint(Integer.parseInt(digits, 16)); + } catch (NumberFormatException e) { + throw problem(digits, String.format( + "Malformed hex digits after \\u escape in string: '%s'", digits), e); + } + } + break; + default: + throw problem( + asString(escaped), + String.format( + "backslash followed by '%s', this is not a valid escape sequence (quoted strings use JSON escaping, so use double-backslash \\\\ for literal backslash)", + asString(escaped))); + } + } + + private void appendTripleQuotedString(StringBuilder sb, StringBuilder sbOrig) throws ProblemException { + // we are after the opening triple quote and need to consume the + // close triple + int consecutiveQuotes = 0; + for (;;) { + int c = nextCharRaw(); + + if (c == '"') { + consecutiveQuotes += 1; + } else if (consecutiveQuotes >= 3) { + // the last three quotes end the string and the others are + // kept. + sb.setLength(sb.length() - 3); + putBack(c); + break; + } else { + consecutiveQuotes = 0; + if (c == -1) + throw problem("End of input but triple-quoted string was still open"); + else if (c == '\n') { + // keep the line number accurate + lineNumber += 1; + lineOrigin = origin.withLineNumber(lineNumber); + } + } + + sb.appendCodePoint(c); + sbOrig.appendCodePoint(c); + } + } + + private Token pullQuotedString() throws ProblemException { + // the open quote has already been consumed + StringBuilder sb = new StringBuilder(); + + // We need a second string builder to keep track of escape characters. + // We want to return them exactly as they appeared in the original text, + // which means we will need a new StringBuilder to escape escape characters + // so we can also keep the actual value of the string. This is gross. + StringBuilder sbOrig = new StringBuilder(); + sbOrig.appendCodePoint('"'); + + while (true) { + int c = nextCharRaw(); + if (c == -1) + throw problem("End of input but string quote was still open"); + + if (c == '\\') { + pullEscapeSequence(sb, sbOrig); + } else if (c == '"') { + sbOrig.appendCodePoint(c); + break; + } else if (ConfigImplUtil.isC0Control(c)) { + throw problem(asString(c), "JSON does not allow unescaped " + asString(c) + + " in quoted strings, use a backslash escape"); + } else { + sb.appendCodePoint(c); + sbOrig.appendCodePoint(c); + } + } + + // maybe switch to triple-quoted string, sort of hacky... + if (sb.length() == 0) { + int third = nextCharRaw(); + if (third == '"') { + sbOrig.appendCodePoint(third); + appendTripleQuotedString(sb, sbOrig); + } else { + putBack(third); + } + + } + return Tokens.newString(lineOrigin, sb.toString(), sbOrig.toString()); + } + + private Token pullPlusEquals() throws ProblemException { + // the initial '+' has already been consumed + int c = nextCharRaw(); + if (c != '=') { + throw problem(asString(c), "'+' not followed by =, '" + asString(c) + + "' not allowed after '+'", true /* suggestQuotes */); + } + return Tokens.PLUS_EQUALS; + } + + private Token pullSubstitution() throws ProblemException { + // the initial '$' has already been consumed + ConfigOrigin origin = lineOrigin; + int c = nextCharRaw(); + if (c != '{') { + throw problem(asString(c), "'$' not followed by {, '" + asString(c) + + "' not allowed after '$'", true /* suggestQuotes */); + } + + boolean optional = false; + c = nextCharRaw(); + if (c == '?') { + optional = true; + } else { + putBack(c); + } + + WhitespaceSaver saver = new WhitespaceSaver(); + List expression = new ArrayList(); + + Token t; + do { + t = pullNextToken(saver); + + // note that we avoid validating the allowed tokens inside + // the substitution here; we even allow nested substitutions + // in the tokenizer. The parser sorts it out. + if (t == Tokens.CLOSE_CURLY) { + // end the loop, done! + break; + } else if (t == Tokens.END) { + throw problem(origin, + "Substitution ${ was not closed with a }"); + } else { + Token whitespace = saver.check(t, origin, lineNumber); + if (whitespace != null) + expression.add(whitespace); + expression.add(t); + } + } while (true); + + return Tokens.newSubstitution(origin, optional, expression); + } + + private Token pullNextToken(WhitespaceSaver saver) throws ProblemException { + int c = nextCharAfterWhitespace(saver); + if (c == -1) { + return Tokens.END; + } else if (c == '\n') { + // newline tokens have the just-ended line number + Token line = Tokens.newLine(lineOrigin); + lineNumber += 1; + lineOrigin = origin.withLineNumber(lineNumber); + return line; + } else { + Token t; + if (startOfComment(c)) { + t = pullComment(c); + } else { + switch (c) { + case '"': + t = pullQuotedString(); + break; + case '$': + t = pullSubstitution(); + break; + case ':': + t = Tokens.COLON; + break; + case ',': + t = Tokens.COMMA; + break; + case '=': + t = Tokens.EQUALS; + break; + case '{': + t = Tokens.OPEN_CURLY; + break; + case '}': + t = Tokens.CLOSE_CURLY; + break; + case '[': + t = Tokens.OPEN_SQUARE; + break; + case ']': + t = Tokens.CLOSE_SQUARE; + break; + case '+': + t = pullPlusEquals(); + break; + default: + t = null; + break; + } + + if (t == null) { + if (firstNumberChars.indexOf(c) >= 0) { + t = pullNumber(c); + } else if (notInUnquotedText.indexOf(c) >= 0) { + throw problem(asString(c), "Reserved character '" + asString(c) + + "' is not allowed outside quotes", true /* suggestQuotes */); + } else { + putBack(c); + t = pullUnquotedText(); + } + } + } + + if (t == null) + throw new ConfigException.BugOrBroken( + "bug: failed to generate next token"); + + return t; + } + } + + private static boolean isSimpleValue(Token t) { + if (Tokens.isSubstitution(t) || Tokens.isUnquotedText(t) + || Tokens.isValue(t)) { + return true; + } else { + return false; + } + } + + private void queueNextToken() throws ProblemException { + Token t = pullNextToken(whitespaceSaver); + Token whitespace = whitespaceSaver.check(t, origin, lineNumber); + if (whitespace != null) + tokens.add(whitespace); + + tokens.add(t); + } + + @Override + public boolean hasNext() { + return !tokens.isEmpty(); + } + + @Override + public Token next() { + Token t = tokens.remove(); + if (tokens.isEmpty() && t != Tokens.END) { + try { + queueNextToken(); + } catch (ProblemException e) { + tokens.add(e.problem()); + } + if (tokens.isEmpty()) + throw new ConfigException.BugOrBroken( + "bug: tokens queue should not be empty here"); + } + return t; + } + + @Override + public void remove() { + throw new UnsupportedOperationException( + "Does not make sense to remove items from token stream"); + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Tokens.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Tokens.java new file mode 100644 index 0000000..08762d0 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Tokens.java @@ -0,0 +1,521 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.List; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType; + +/* FIXME the way the subclasses of Token are private with static isFoo and accessors is kind of ridiculous. */ +final class Tokens { + static private class Value extends Token { + + final private AbstractConfigValue value; + + Value(AbstractConfigValue value) { + this(value, null); + } + + Value(AbstractConfigValue value, String origText) { + super(TokenType.VALUE, value.origin(), origText); + this.value = value; + } + + AbstractConfigValue value() { + return value; + } + + @Override + public String toString() { + if (value().resolveStatus() == ResolveStatus.RESOLVED) + return "'" + value().unwrapped() + "' (" + value.valueType().name() + ")"; + else + return "'' (" + value.valueType().name() + ")"; + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof Value; + } + + @Override + public boolean equals(Object other) { + return super.equals(other) && ((Value) other).value.equals(value); + } + + @Override + public int hashCode() { + return 41 * (41 + super.hashCode()) + value.hashCode(); + } + } + + static private class Line extends Token { + Line(ConfigOrigin origin) { + super(TokenType.NEWLINE, origin); + } + + @Override + public String toString() { + return "'\\n'@" + lineNumber(); + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof Line; + } + + @Override + public boolean equals(Object other) { + return super.equals(other) && ((Line) other).lineNumber() == lineNumber(); + } + + @Override + public int hashCode() { + return 41 * (41 + super.hashCode()) + lineNumber(); + } + + @Override + public String tokenText() { + return "\n"; + } + } + + // This is not a Value, because it requires special processing + static private class UnquotedText extends Token { + final private String value; + + UnquotedText(ConfigOrigin origin, String s) { + super(TokenType.UNQUOTED_TEXT, origin); + this.value = s; + } + + String value() { + return value; + } + + @Override + public String toString() { + return "'" + value + "'"; + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof UnquotedText; + } + + @Override + public boolean equals(Object other) { + return super.equals(other) + && ((UnquotedText) other).value.equals(value); + } + + @Override + public int hashCode() { + return 41 * (41 + super.hashCode()) + value.hashCode(); + } + + @Override + public String tokenText() { + return value; + } + } + + static private class IgnoredWhitespace extends Token { + final private String value; + + IgnoredWhitespace(ConfigOrigin origin, String s) { + super(TokenType.IGNORED_WHITESPACE, origin); + this.value = s; + } + + @Override + public String toString() { return "'" + value + "' (WHITESPACE)"; } + + @Override + protected boolean canEqual(Object other) { + return other instanceof IgnoredWhitespace; + } + + @Override + public boolean equals(Object other) { + return super.equals(other) + && ((IgnoredWhitespace) other).value.equals(value); + } + + @Override + public int hashCode() { + return 41 * (41 + super.hashCode()) + value.hashCode(); + } + + @Override + public String tokenText() { + return value; + } + } + + static private class Problem extends Token { + final private String what; + final private String message; + final private boolean suggestQuotes; + final private Throwable cause; + + Problem(ConfigOrigin origin, String what, String message, boolean suggestQuotes, + Throwable cause) { + super(TokenType.PROBLEM, origin); + this.what = what; + this.message = message; + this.suggestQuotes = suggestQuotes; + this.cause = cause; + } + + String what() { + return what; + } + + String message() { + return message; + } + + boolean suggestQuotes() { + return suggestQuotes; + } + + Throwable cause() { + return cause; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append('\''); + sb.append(what); + sb.append('\''); + sb.append(" ("); + sb.append(message); + sb.append(")"); + return sb.toString(); + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof Problem; + } + + @Override + public boolean equals(Object other) { + return super.equals(other) && ((Problem) other).what.equals(what) + && ((Problem) other).message.equals(message) + && ((Problem) other).suggestQuotes == suggestQuotes + && ConfigImplUtil.equalsHandlingNull(((Problem) other).cause, cause); + } + + @Override + public int hashCode() { + int h = 41 * (41 + super.hashCode()); + h = 41 * (h + what.hashCode()); + h = 41 * (h + message.hashCode()); + h = 41 * (h + Boolean.valueOf(suggestQuotes).hashCode()); + if (cause != null) + h = 41 * (h + cause.hashCode()); + return h; + } + } + + static private abstract class Comment extends Token { + final private String text; + + Comment(ConfigOrigin origin, String text) { + super(TokenType.COMMENT, origin); + this.text = text; + } + + final static class DoubleSlashComment extends Comment { + DoubleSlashComment(ConfigOrigin origin, String text) { + super(origin, text); + } + + @Override + public String tokenText() { + return "//" + super.text; + } + } + + final static class HashComment extends Comment { + HashComment(ConfigOrigin origin, String text) { + super(origin, text); + } + + @Override + public String tokenText() { + return "#" + super.text; + } + } + + String text() { + return text; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("'#"); + sb.append(text); + sb.append("' (COMMENT)"); + return sb.toString(); + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof Comment; + } + + @Override + public boolean equals(Object other) { + return super.equals(other) && ((Comment) other).text.equals(text); + } + + @Override + public int hashCode() { + int h = 41 * (41 + super.hashCode()); + h = 41 * (h + text.hashCode()); + return h; + } + } + + // This is not a Value, because it requires special processing + static private class Substitution extends Token { + final private boolean optional; + final private List value; + + Substitution(ConfigOrigin origin, boolean optional, List expression) { + super(TokenType.SUBSTITUTION, origin); + this.optional = optional; + this.value = expression; + } + + boolean optional() { + return optional; + } + + List value() { + return value; + } + + @Override + public String tokenText() { + return "${" + (this.optional? "?" : "") + Tokenizer.render(this.value.iterator()) + "}"; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (Token t : value) { + sb.append(t.toString()); + } + return "'${" + sb.toString() + "}'"; + } + + @Override + protected boolean canEqual(Object other) { + return other instanceof Substitution; + } + + @Override + public boolean equals(Object other) { + return super.equals(other) + && ((Substitution) other).value.equals(value); + } + + @Override + public int hashCode() { + return 41 * (41 + super.hashCode()) + value.hashCode(); + } + } + + static boolean isValue(Token token) { + return token instanceof Value; + } + + static AbstractConfigValue getValue(Token token) { + if (token instanceof Value) { + return ((Value) token).value(); + } else { + throw new ConfigException.BugOrBroken( + "tried to get value of non-value token " + token); + } + } + + static boolean isValueWithType(Token t, ConfigValueType valueType) { + return isValue(t) && getValue(t).valueType() == valueType; + } + + static boolean isNewline(Token token) { + return token instanceof Line; + } + + static boolean isProblem(Token token) { + return token instanceof Problem; + } + + static String getProblemWhat(Token token) { + if (token instanceof Problem) { + return ((Problem) token).what(); + } else { + throw new ConfigException.BugOrBroken("tried to get problem what from " + token); + } + } + + static String getProblemMessage(Token token) { + if (token instanceof Problem) { + return ((Problem) token).message(); + } else { + throw new ConfigException.BugOrBroken("tried to get problem message from " + token); + } + } + + static boolean getProblemSuggestQuotes(Token token) { + if (token instanceof Problem) { + return ((Problem) token).suggestQuotes(); + } else { + throw new ConfigException.BugOrBroken("tried to get problem suggestQuotes from " + + token); + } + } + + static Throwable getProblemCause(Token token) { + if (token instanceof Problem) { + return ((Problem) token).cause(); + } else { + throw new ConfigException.BugOrBroken("tried to get problem cause from " + token); + } + } + + static boolean isComment(Token token) { + return token instanceof Comment; + } + + static String getCommentText(Token token) { + if (token instanceof Comment) { + return ((Comment) token).text(); + } else { + throw new ConfigException.BugOrBroken("tried to get comment text from " + token); + } + } + + static boolean isUnquotedText(Token token) { + return token instanceof UnquotedText; + } + + static String getUnquotedText(Token token) { + if (token instanceof UnquotedText) { + return ((UnquotedText) token).value(); + } else { + throw new ConfigException.BugOrBroken( + "tried to get unquoted text from " + token); + } + } + + static boolean isIgnoredWhitespace(Token token) { + return token instanceof IgnoredWhitespace; + } + + static boolean isSubstitution(Token token) { + return token instanceof Substitution; + } + + static List getSubstitutionPathExpression(Token token) { + if (token instanceof Substitution) { + return ((Substitution) token).value(); + } else { + throw new ConfigException.BugOrBroken( + "tried to get substitution from " + token); + } + } + + static boolean getSubstitutionOptional(Token token) { + if (token instanceof Substitution) { + return ((Substitution) token).optional(); + } else { + throw new ConfigException.BugOrBroken("tried to get substitution optionality from " + + token); + } + } + + final static Token START = Token.newWithoutOrigin(TokenType.START, "start of file", ""); + final static Token END = Token.newWithoutOrigin(TokenType.END, "end of file", ""); + final static Token COMMA = Token.newWithoutOrigin(TokenType.COMMA, "','", ","); + final static Token EQUALS = Token.newWithoutOrigin(TokenType.EQUALS, "'='", "="); + final static Token COLON = Token.newWithoutOrigin(TokenType.COLON, "':'", ":"); + final static Token OPEN_CURLY = Token.newWithoutOrigin(TokenType.OPEN_CURLY, "'{'", "{"); + final static Token CLOSE_CURLY = Token.newWithoutOrigin(TokenType.CLOSE_CURLY, "'}'", "}"); + final static Token OPEN_SQUARE = Token.newWithoutOrigin(TokenType.OPEN_SQUARE, "'['", "["); + final static Token CLOSE_SQUARE = Token.newWithoutOrigin(TokenType.CLOSE_SQUARE, "']'", "]"); + final static Token PLUS_EQUALS = Token.newWithoutOrigin(TokenType.PLUS_EQUALS, "'+='", "+="); + + static Token newLine(ConfigOrigin origin) { + return new Line(origin); + } + + static Token newProblem(ConfigOrigin origin, String what, String message, + boolean suggestQuotes, Throwable cause) { + return new Problem(origin, what, message, suggestQuotes, cause); + } + + static Token newCommentDoubleSlash(ConfigOrigin origin, String text) { + return new Comment.DoubleSlashComment(origin, text); + } + + static Token newCommentHash(ConfigOrigin origin, String text) { + return new Comment.HashComment(origin, text); + } + + static Token newUnquotedText(ConfigOrigin origin, String s) { + return new UnquotedText(origin, s); + } + + static Token newIgnoredWhitespace(ConfigOrigin origin, String s) { + return new IgnoredWhitespace(origin, s); + } + + static Token newSubstitution(ConfigOrigin origin, boolean optional, List expression) { + return new Substitution(origin, optional, expression); + } + + static Token newValue(AbstractConfigValue value) { + return new Value(value); + } + static Token newValue(AbstractConfigValue value, String origText) { + return new Value(value, origText); + } + + static Token newString(ConfigOrigin origin, String value, String origText) { + return newValue(new ConfigString.Quoted(origin, value), origText); + } + + static Token newInt(ConfigOrigin origin, int value, String origText) { + return newValue(ConfigNumber.newNumber(origin, value, + origText), origText); + } + + static Token newDouble(ConfigOrigin origin, double value, + String origText) { + return newValue(ConfigNumber.newNumber(origin, value, + origText), origText); + } + + static Token newLong(ConfigOrigin origin, long value, String origText) { + return newValue(ConfigNumber.newNumber(origin, value, + origText), origText); + } + + static Token newNull(ConfigOrigin origin) { + return newValue(new ConfigNull(origin), "null"); + } + + static Token newBoolean(ConfigOrigin origin, boolean value) { + return newValue(new ConfigBoolean(origin, value), "" + value); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Unmergeable.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Unmergeable.java new file mode 100644 index 0000000..a59256c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/Unmergeable.java @@ -0,0 +1,16 @@ +/** + * Copyright (C) 2011-2012 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.impl; + +import java.util.Collection; + +/** + * Interface that tags a ConfigValue that is not mergeable until after + * substitutions are resolved. Basically these are special ConfigValue that + * never appear in a resolved tree, like {@link ConfigSubstitution} and + * {@link ConfigDelayedMerge}. + */ +interface Unmergeable { + Collection unmergedValues(); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/package.html b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/package.html new file mode 100644 index 0000000..52592b0 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/impl/package.html @@ -0,0 +1,25 @@ + + + + + + + + +

+Internal implementation details that can change ABI at any time. +

+ +

+Please check out the {@link com.typesafe.config.Config public API} instead, unless +you're interested in browsing implementation details. None of the ABI +under impl has any guarantees; it will change whenever someone +feels like changing it. If you feel you need access to something +in impl, please +file a feature request. +

+ + + diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/package.html b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/package.html new file mode 100644 index 0000000..8f5d9f4 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/package.html @@ -0,0 +1,58 @@ + + + + + + + + +

+An API for loading and using configuration files, see the project site +for more information. +

+ +

+Typically you would load configuration with a static method from {@link com.typesafe.config.ConfigFactory} and then use +it with methods in the {@link com.typesafe.config.Config} interface. Configuration may be in the form of JSON files, +Java properties, or HOCON files; you may also +build your own configuration in code or from your own file formats. +

+ +

+An application can simply call {@link com.typesafe.config.ConfigFactory#load()} and place +its configuration in "application.conf" on the classpath. +If you use the default configuration from {@link com.typesafe.config.ConfigFactory#load()} +there's no need to pass a configuration to your libraries +and frameworks, as long as they all default to this same default, which they should. +
Example application code: Java and Scala. +
Showing a couple of more special-purpose features, a more complex example: Java and Scala. +

+ +

+A library or framework should ship a file "reference.conf" in its jar, and allow an application to pass in a +{@link com.typesafe.config.Config} to be used for the library. If no {@link com.typesafe.config.Config} is provided, +call {@link com.typesafe.config.ConfigFactory#load()} +to get the default one. Typically a library might offer two constructors, one with a Config parameter +and one which uses {@link com.typesafe.config.ConfigFactory#load()}. +
Example library code: Java and Scala. +

+ +

+Check out the full examples directory on GitHub. +

+ +

+What else to read: +

    +
  • The overview documentation for interface {@link com.typesafe.config.Config}.
  • +
  • The README for the library.
  • +
  • If you want to use .conf files in addition to .json and .properties, + see the README for some short examples + and the full HOCON spec for the long version.
  • +
+

+ + + diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigDocument.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigDocument.java new file mode 100644 index 0000000..99855da --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigDocument.java @@ -0,0 +1,82 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.parser; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue; + +/** + * Represents an individual HOCON or JSON file, preserving all + * formatting and syntax details. This can be used to replace + * individual values and exactly render the original text of the + * input. + * + *

+ * Because this object is immutable, it is safe to use from multiple threads and + * there's no need for "defensive copies." + * + *

+ * Do not implement interface {@code ConfigDocument}; it should only be + * implemented by the config library. Arbitrary implementations will not work + * because the library internals assume a specific concrete implementation. + * Also, this interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface ConfigDocument { + /** + * Returns a new ConfigDocument that is a copy of the current ConfigDocument, + * but with the desired value set at the desired path. If the path exists, it will + * remove all duplicates before the final occurrence of the path, and replace the value + * at the final occurrence of the path. If the path does not exist, it will be added. If + * the document has an array as the root value, an exception will be thrown. + * + * @param path the path at which to set the desired value + * @param newValue the value to set at the desired path, represented as a string. This + * string will be parsed into a ConfigNode using the same options used to + * parse the entire document, and the text will be inserted + * as-is into the document. Leading and trailing comments, whitespace, or + * newlines are not allowed, and if present an exception will be thrown. + * If a concatenation is passed in for newValue but the document was parsed + * with JSON, the first value in the concatenation will be parsed and inserted + * into the ConfigDocument. + * @return a copy of the ConfigDocument with the desired value at the desired path + */ + ConfigDocument withValueText(String path, String newValue); + + /** + * Returns a new ConfigDocument that is a copy of the current + * ConfigDocument, but with the desired value set at the + * desired path. Works like {@link #withValueText(String, String)}, + * but takes a ConfigValue instead of a string. + * + * @param path the path at which to set the desired value + * @param newValue the value to set at the desired path, represented as a ConfigValue. + * The rendered text of the ConfigValue will be inserted into the + * ConfigDocument. + * @return a copy of the ConfigDocument with the desired value at the desired path + */ + ConfigDocument withValue(String path, ConfigValue newValue); + + /** + * Returns a new ConfigDocument that is a copy of the current ConfigDocument, but with + * all values at the desired path removed. If the path does not exist in the document, + * a copy of the current document will be returned. If there is an array at the root, an exception + * will be thrown. + * + * @param path the path to remove from the document + * @return a copy of the ConfigDocument with the desired value removed from the document. + */ + ConfigDocument withoutPath(String path); + + /** + * Returns a boolean indicating whether or not a ConfigDocument has a value at the desired path. + * null counts as a value for purposes of this check. + * @param path the path to check + * @return true if the path exists in the document, otherwise false + */ + boolean hasPath(String path); + + /** + * The original text of the input, modified if necessary with + * any replaced or added values. + * @return the modified original text + */ + String render(); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigDocumentFactory.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigDocumentFactory.java new file mode 100644 index 0000000..5a3bb4d --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigDocumentFactory.java @@ -0,0 +1,93 @@ +package com.drtshock.playervaults.lib.com.typesafe.config.parser; + +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException; +import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions; +import com.drtshock.playervaults.lib.com.typesafe.config.impl.Parseable; + +import java.io.File; +import java.io.Reader; + +/** + * Factory for creating {@link + * ConfigDocument} instances. + */ +public final class ConfigDocumentFactory { + + /** + * Parses a Reader into a ConfigDocument instance. + * + * @param reader + * the reader to parse + * @param options + * parse options to control how the reader is interpreted + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static ConfigDocument parseReader(Reader reader, ConfigParseOptions options) { + return Parseable.newReader(reader, options).parseConfigDocument(); + } + + /** + * Parses a reader into a Config instance as with + * {@link #parseReader(Reader,ConfigParseOptions)} but always uses the + * default parse options. + * + * @param reader + * the reader to parse + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static ConfigDocument parseReader(Reader reader) { + return parseReader(reader, ConfigParseOptions.defaults()); + } + + /** + * Parses a file into a ConfigDocument instance. + * + * @param file + * the file to parse + * @param options + * parse options to control how the file is interpreted + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static ConfigDocument parseFile(File file, ConfigParseOptions options) { + return Parseable.newFile(file, options).parseConfigDocument(); + } + + /** + * Parses a file into a ConfigDocument instance as with + * {@link #parseFile(File,ConfigParseOptions)} but always uses the + * default parse options. + * + * @param file + * the file to parse + * @return the parsed configuration + * @throws ConfigException on IO or parse errors + */ + public static ConfigDocument parseFile(File file) { + return parseFile(file, ConfigParseOptions.defaults()); + } + + /** + * Parses a string which should be valid HOCON or JSON. + * + * @param s string to parse + * @param options parse options + * @return the parsed configuration + */ + public static ConfigDocument parseString(String s, ConfigParseOptions options) { + return Parseable.newString(s, options).parseConfigDocument(); + } + + /** + * Parses a string (which should be valid HOCON or JSON). Uses the + * default parse options. + * + * @param s string to parse + * @return the parsed configuration + */ + public static ConfigDocument parseString(String s) { + return parseString(s, ConfigParseOptions.defaults()); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigNode.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigNode.java new file mode 100644 index 0000000..7d03b19 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/ConfigNode.java @@ -0,0 +1,35 @@ +/** + * Copyright (C) 2015 Typesafe Inc. + */ +package com.drtshock.playervaults.lib.com.typesafe.config.parser; + +/** + * A node in the syntax tree for a HOCON or JSON document. + * + *

+ * Note: at present there is no way to obtain an instance of this interface, so + * please ignore it. A future release will make syntax tree nodes available in + * the public API. If you are interested in working on it, please see: https://github.com/lightbend/config/issues/300 + * + *

+ * Because this object is immutable, it is safe to use from multiple threads and + * there's no need for "defensive copies." + * + *

+ * Do not implement interface {@code ConfigNode}; it should only be + * implemented by the config library. Arbitrary implementations will not work + * because the library internals assume a specific concrete implementation. + * Also, this interface is likely to grow new methods over time, so third-party + * implementations will break. + */ +public interface ConfigNode { + /** + * The original text of the input which was used to form this particular + * node. + * + * @return the original text used to form this node as a String + */ + public String render(); +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/package.html b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/package.html new file mode 100644 index 0000000..b0e7b3c --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/lib/com/typesafe/config/parser/package.html @@ -0,0 +1,33 @@ + + + + + + + + +

+This package supplies a raw parser and syntax tree for individual HOCON and JSON +files. You do not want this package for everyday config in your app: see +the com.typesafe.config package instead. You would use the raw +parser if you're doing something like reading, modifying, and re-saving a config +file. For info on the main config API this parser is a part of, +see the project site. +

+ +

+ For working with the raw syntax tree, some important classes are: +

    +
  • {@link com.typesafe.config.parser.ConfigDocument} - a loaded HOCON + or JSON document
  • +
  • {@link com.typesafe.config.parser.ConfigDocumentFactory} - + static methods to instantiate a document
  • +
  • {@link com.typesafe.config.parser.ConfigNode} - syntax node + in a document
  • +
+

+ + + diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/Listeners.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/Listeners.java new file mode 100644 index 0000000..cb0ed8e --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/Listeners.java @@ -0,0 +1,175 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.listeners; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.vaultmanagement.VaultManager; +import com.drtshock.playervaults.vaultmanagement.VaultViewInfo; +import org.bukkit.Bukkit; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.stream.Collectors; + +public class Listeners implements Listener { + + public final PlayerVaults plugin; + private final VaultManager vaultManager = VaultManager.getInstance(); + + public Listeners(PlayerVaults playerVaults) { + this.plugin = playerVaults; + } + + public void saveVault(Player player, Inventory inventory) { + if (plugin.getInVault().containsKey(player.getUniqueId().toString())) { + + Inventory inv = Bukkit.createInventory(null, inventory.getSize()); + inv.setContents(inventory.getContents().clone()); + + PlayerVaults.debug(inventory.getType() + " " + inventory.getClass().getSimpleName()); + if (inventory.getViewers().size() <= 1) { + PlayerVaults.debug("Saving!"); + VaultViewInfo info = plugin.getInVault().get(player.getUniqueId().toString()); + vaultManager.saveVault(inv, info.getVaultName(), info.getNumber()); + plugin.getOpenInventories().remove(info.toString()); + + VaultManager.getInstance().getVaultCache().cacheVault(player.getUniqueId(), info.getNumber(), inventory); + } else { + PlayerVaults.debug("Other viewers found, not saving! " + inventory.getViewers().stream().map(HumanEntity::getName).collect(Collectors.joining(" "))); + } + + plugin.getInVault().remove(player.getUniqueId().toString()); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (event.getCause() == PlayerTeleportEvent.TeleportCause.UNKNOWN) { + return; + } + Player p = event.getPlayer(); + // The player will either quit, die, or close the inventory at some point + if (plugin.getInVault().containsKey(p.getUniqueId().toString())) { + return; + } + saveVault(p, p.getOpenInventory().getTopInventory()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onQuit(PlayerQuitEvent event) { + saveVault(event.getPlayer(), event.getPlayer().getOpenInventory().getTopInventory()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onDeath(PlayerDeathEvent event) { + saveVault(event.getEntity(), event.getEntity().getOpenInventory().getTopInventory()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onClose(InventoryCloseEvent event) { + saveVault((Player) event.getPlayer(), event.getInventory()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInteractEntity(PlayerInteractEntityEvent event) { + Player player = event.getPlayer(); + EntityType type = event.getRightClicked().getType(); + if ((type == EntityType.VILLAGER || type == EntityType.MINECART) && PlayerVaults.getInstance().getInVault().containsKey(player.getUniqueId().toString())) { + event.setCancelled(true); + } + } + + @EventHandler(ignoreCancelled = true) + public void onClick(InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) { + return; + } + + Player player = (Player) event.getWhoClicked(); + + Inventory clickedInventory = event.getClickedInventory(); + if (clickedInventory != null) { + VaultViewInfo info = PlayerVaults.getInstance().getInVault().get(player.getUniqueId().toString()); + if (info != null) { + int num = info.getNumber(); + String inventoryTitle = event.getView().getTitle(); + String title = this.plugin.getVaultTitle(String.valueOf(num)); + if (inventoryTitle.equalsIgnoreCase(title)) { + ItemStack[] items = new ItemStack[2]; + items[0] = event.getCurrentItem(); + if (event.getHotbarButton() > -1 && event.getWhoClicked().getInventory().getItem(event.getHotbarButton()) != null) { + items[1] = event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); + } + + for (ItemStack item : items) { + if (item == null) { + continue; + } + if (!player.hasPermission("playervaults.bypassblockeditems") && PlayerVaults.getInstance().isBlockedMaterial(item.getType())) { + event.setCancelled(true); + this.plugin.getTL().blockedItem().title().with("item", item.getType().name()).send(player); + return; + } + } + } + } + } + } + + @EventHandler(ignoreCancelled = true) + public void onDrag(InventoryDragEvent event) { + if (!(event.getWhoClicked() instanceof Player)) { + return; + } + + Player player = (Player) event.getWhoClicked(); + + Inventory clickedInventory = event.getInventory(); + if (clickedInventory != null) { + VaultViewInfo info = PlayerVaults.getInstance().getInVault().get(player.getUniqueId().toString()); + if (info != null) { + int num = info.getNumber(); + String inventoryTitle = event.getView().getTitle(); + String title = this.plugin.getVaultTitle(String.valueOf(num)); + if ((inventoryTitle != null && inventoryTitle.equalsIgnoreCase(title)) && event.getNewItems() != null) { + for (ItemStack item : event.getNewItems().values()) { + if (!player.hasPermission("playervaults.bypassblockeditems") && PlayerVaults.getInstance().isBlockedMaterial(item.getType())) { + event.setCancelled(true); + this.plugin.getTL().blockedItem().title().with("item", item.getType().name()).send(player); + return; + } + } + } + } + } + } +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/SignListener.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/SignListener.java new file mode 100644 index 0000000..cc33ab9 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/SignListener.java @@ -0,0 +1,191 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.listeners; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.vaultmanagement.VaultOperations; +import com.drtshock.playervaults.vaultmanagement.VaultViewInfo; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.InventoryHolder; + +public class SignListener implements Listener { + private final PlayerVaults plugin; + + /** + * TODO: Some of these events can be lag inducing (specifically: interactions & block breaking), + * perhaps we should try to optimize these listeners at some point? + */ + + public SignListener(PlayerVaults plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + if (!PlayerVaults.getInstance().getConf().isSigns()) { + return; + } + Player player = event.getPlayer(); + if (player.isSleeping() || player.isDead() || !player.isOnline()) { + return; + } + Block block = event.getClickedBlock(); + if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { + if (PlayerVaults.getInstance().getInVault().containsKey(player.getUniqueId().toString())) { + // Different inventories that we don't want the player to open. + if (isInvalidBlock(block)) { + event.setCancelled(true); + } + } + } + if (PlayerVaults.getInstance().getSetSign().containsKey(player.getName())) { + int i = PlayerVaults.getInstance().getSetSign().get(player.getName()).getChest(); + boolean self = PlayerVaults.getInstance().getSetSign().get(player.getName()).isSelf(); + String owner = self ? null : PlayerVaults.getInstance().getSetSign().get(player.getName()).getOwner(); + PlayerVaults.getInstance().getSetSign().remove(player.getName()); + event.setCancelled(true); + if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK) { + if (block != null && plugin.isSign(block.getType())) { + Sign s = (Sign) block.getState(); + Location l = s.getLocation(); + String world = l.getWorld().getName(); + int x = l.getBlockX(); + int y = l.getBlockY(); + int z = l.getBlockZ(); + if (self) { + plugin.getSigns().set(world + ";;" + x + ";;" + y + ";;" + z + ".self", true); + } else { + plugin.getSigns().set(world + ";;" + x + ";;" + y + ";;" + z + ".owner", owner); + } + plugin.getSigns().set(world + ";;" + x + ";;" + y + ";;" + z + ".chest", i); + plugin.saveSigns(); + this.plugin.getTL().setSign().title().send(player); + } else { + this.plugin.getTL().notASign().title().send(player); + } + } else { + this.plugin.getTL().notASign().title().send(player); + } + return; + } + if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { + if (block != null && plugin.isSign(block.getType())) { + Location l = block.getLocation(); + String world = l.getWorld().getName(); + int x = l.getBlockX(); + int y = l.getBlockY(); + int z = l.getBlockZ(); + if (plugin.getSigns().getKeys(false).contains(world + ";;" + x + ";;" + y + ";;" + z)) { + PlayerVaults.debug("Player " + player.getName() + " clicked sign at world(" + x + "," + y + "," + z + ")"); + if (PlayerVaults.getInstance().getInVault().containsKey(player.getUniqueId().toString())) { + // don't let them open another vault. + PlayerVaults.debug("Player " + player.getName() + " denied sign vault because already in a vault!"); + return; + } + int num = PlayerVaults.getInstance().getSigns().getInt(world + ";;" + x + ";;" + y + ";;" + z + ".chest", 1); + String numS = String.valueOf(num); + if (player.hasPermission("playervaults.signs.use") || player.hasPermission("playervaults.signs.bypass")) { + boolean self = PlayerVaults.getInstance().getSigns().getBoolean(world + ";;" + x + ";;" + y + ";;" + z + ".self", false); + String owner = self ? player.getName() : PlayerVaults.getInstance().getSigns().getString(world + ";;" + x + ";;" + y + ";;" + z + ".owner"); + PlayerVaults.debug("Player " + player.getName() + " wants to open a " + (self ? "self" : "non-self (" + owner + ")") + " sign vault"); + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(owner != null ? owner : event.getPlayer().getName()); // Not best way but :\ + if (offlinePlayer == null || (!offlinePlayer.isOnline() && !offlinePlayer.hasPlayedBefore())) { + PlayerVaults.debug("Denied sign vault for never-seen-before owner " + owner); + this.plugin.getTL().vaultDoesNotExist().title().send(player); + return; + } + if (self) { + // We already checked that they can use signs, now lets check if they have this many vaults. + if (VaultOperations.openOwnVault(player, numS, false)) { + PlayerVaults.getInstance().getInVault().put(player.getUniqueId().toString(), new VaultViewInfo(player.getUniqueId().toString(), num)); + } else { + PlayerVaults.debug("Player " + player.getName() + " failed to open sign vault!"); + return; + } + } else { + if (!VaultOperations.openOtherVault(player, owner, numS, false)) { + PlayerVaults.debug("Player " + player.getName() + " failed to open sign vault!"); + return; + } + } + PlayerVaults.debug("Player " + player.getName() + " succeeded in opening sign vault"); + event.setCancelled(true); + this.plugin.getTL().openWithSign().title().with("vault", String.valueOf(num)).with("player", owner).send(player); + } else { + PlayerVaults.debug("Player " + player.getName() + " no sign perms!"); + this.plugin.getTL().noPerms().title().send(player); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityChangeBlock(EntityChangeBlockEvent event) { + if (!PlayerVaults.getInstance().getConf().isSigns()) { + return; + } + blockChangeCheck(event.getBlock().getLocation()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + if (!PlayerVaults.getInstance().getConf().isSigns()) { + return; + } + blockChangeCheck(event.getBlock().getLocation()); + } + + /** + * Check if the location given is a sign, and if so, remove it from the signs.yml file + * + * @param location The location to check + */ + public void blockChangeCheck(Location location) { + if (plugin.getSigns().getKeys(false).isEmpty()) { + return; // Save us a check. + } + + String world = location.getWorld().getName(); + int x = location.getBlockX(); + int y = location.getBlockY(); + int z = location.getBlockZ(); + if (plugin.getSigns().getKeys(false).contains(world + ";;" + x + ";;" + y + ";;" + z)) { + plugin.getSigns().set(world + ";;" + x + ";;" + y + ";;" + z, null); + plugin.saveSigns(); + } + } + + private boolean isInvalidBlock(Block block) { + String type = block.getType().name(); + return block.getState() instanceof InventoryHolder || type.contains("ENCHANT") || type.equals("ENDER_CHEST"); + } +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/VaultPreloadListener.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/VaultPreloadListener.java new file mode 100644 index 0000000..66c76d8 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/listeners/VaultPreloadListener.java @@ -0,0 +1,51 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.listeners; + +import com.drtshock.playervaults.PlayerVaults; +import com.drtshock.playervaults.vaultmanagement.VaultManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.UUID; + +public class VaultPreloadListener implements Listener { + + final VaultManager vm = VaultManager.getInstance(); + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(PlayerJoinEvent event) { + final UUID uuid = event.getPlayer().getUniqueId(); + new BukkitRunnable() { + @Override + public void run() { + vm.cachePlayerVaultFile(uuid.toString()); + } + }.runTaskAsynchronously(PlayerVaults.getInstance()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerQuit(PlayerQuitEvent event) { + vm.removeCachedPlayerVaultFile(event.getPlayer().getUniqueId().toString()); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/tasks/Cleanup.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/tasks/Cleanup.java new file mode 100644 index 0000000..4483293 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/tasks/Cleanup.java @@ -0,0 +1,52 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.tasks; + +import com.drtshock.playervaults.PlayerVaults; + +import java.io.File; + +public class Cleanup implements Runnable { + + private final long diff; + + public Cleanup(long diff) { + this.diff = diff * 86400000L; + } + + @Override + public void run() { + File directory = PlayerVaults.getInstance().getVaultData(); + if (!directory.exists()) { + // folder doesn't exist, don't run + return; + } + + long time = System.currentTimeMillis(); + for (File file : directory.listFiles()) { + if (file.isDirectory()) { + continue; + } + if (time - file.lastModified() > diff) { + PlayerVaults.getInstance().getLogger().info("Deleting vault file (cleanup): " + file.getName()); + file.delete(); + } + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/utils/CC.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/utils/CC.java new file mode 100644 index 0000000..c9d858b --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/utils/CC.java @@ -0,0 +1,9 @@ +package com.drtshock.playervaults.utils; + +import org.bukkit.ChatColor; + +public class CC { + public static String translate(String string) { + return ChatColor.translateAlternateColorCodes('&', string); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/CachedVaultStorage.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/CachedVaultStorage.java new file mode 100644 index 0000000..60089b4 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/CachedVaultStorage.java @@ -0,0 +1,121 @@ +package com.drtshock.playervaults.vaultmanagement; + +import com.drtshock.playervaults.PlayerVaults; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +/** + * Used to store vaults temporarily after they've been opened. + */ +public class CachedVaultStorage { + private static final long TIME_UNTIL_EXPIRY = 30000L; + + private final Map vaultCache; + + private BukkitTask expiryTask; + + public CachedVaultStorage() + { + this.vaultCache = Maps.newHashMap(); + + this.runExpiryTask(); + } + + public void shutdown() + { + expiryTask.cancel(); + } + + public synchronized void cacheVault(UUID owner, int vaultNum, Inventory vault) + { + VaultStorage vaultStorage = this.vaultCache.computeIfAbsent(owner, (key) -> new VaultStorage(owner)); + + vaultStorage.getVaultStorage().put(vaultNum, vault); + + vaultStorage.updateLastActiveTime(); + } + + public synchronized Optional getCachedVault(UUID owner, int vaultNum) + { + if(!vaultCache.containsKey(owner)) + return Optional.empty(); + + VaultStorage storage = vaultCache.get(owner); + + if(!storage.getVaultStorage().containsKey(vaultNum)) + return Optional.empty(); + + return Optional.of(storage.getVaultStorage().get(vaultNum)); + } + + private void runExpiryTask() + { + //This is initialized outside of the async method to CPU time. + List toRemoveList = Lists.newArrayList(); + + expiryTask = new BukkitRunnable(){ + @Override + public void run() + { + if(vaultCache.isEmpty()) + return; + + long timeNow = System.currentTimeMillis(); + + synchronized (CachedVaultStorage.this) + { + vaultCache.forEach((key, value) -> { + if(timeNow - value.getLastActiveTime() > TIME_UNTIL_EXPIRY) + toRemoveList.add(key); + }); + + toRemoveList.forEach(vaultCache::remove); + } + + toRemoveList.clear(); + } + }.runTaskTimerAsynchronously(PlayerVaults.getInstance(), 0, 300); + } + + private static class VaultStorage { + private final UUID owner; + + private final Map vaultStorage; + + private long lastActiveTime; + + public VaultStorage(UUID player) + { + this.owner = player; + + this.vaultStorage = Maps.newHashMap(); + + this.lastActiveTime = System.currentTimeMillis(); + } + + public UUID getOwner() { + return owner; + } + + public Map getVaultStorage() { + return vaultStorage; + } + + public long getLastActiveTime() { + return lastActiveTime; + } + + public void updateLastActiveTime() { + this.lastActiveTime = System.currentTimeMillis(); + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/CardboardBoxSerialization.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/CardboardBoxSerialization.java new file mode 100644 index 0000000..d617a66 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/CardboardBoxSerialization.java @@ -0,0 +1,67 @@ +package com.drtshock.playervaults.vaultmanagement; + +import com.drtshock.playervaults.PlayerVaults; +import org.bukkit.Material; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.kitteh.cardboardbox.CardboardBox; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.logging.Level; + +public class CardboardBoxSerialization { + public static String toStorage(Inventory inventory, String target) { + try { + return Base64Coder.encodeLines(writeInventory(inventory.getContents())); + } catch (IOException e) { + throw PlayerVaults.getInstance().addException(new IllegalStateException("Failed to save items for " + target, e)); + } + } + + public static ItemStack[] fromStorage(String data, String target) { + if (data == null || data.isEmpty()) { + ItemStack[] i = new ItemStack[6 * 9]; + for (int x = 0; x < i.length; x++) { + i[x] = new ItemStack(Material.AIR); + } + return i; + } + try { + return readInventory(Base64Coder.decodeLines(data)); + } catch (IOException e) { + PlayerVaults.getInstance().addException(new IllegalStateException("Failed to save items for " + target, e)); + PlayerVaults.getInstance().getLogger().log(Level.SEVERE, "Failed to load items for " + target, e); + return null; + } + } + + public static byte[] writeInventory(ItemStack[] contents) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(bytes); + out.writeInt(contents.length); + for (ItemStack content : contents) { + byte[] item = CardboardBox.serializeItem(content); + out.writeInt(item.length); + out.write(item); + } + out.close(); + return bytes.toByteArray(); + } + + private static ItemStack[] readInventory(byte[] data) throws IOException { + DataInputStream input = new DataInputStream(new ByteArrayInputStream(data)); + ItemStack[] contents = new ItemStack[input.readInt()]; + for (int i = 0; i < contents.length; i++) { + int len = input.readInt(); + byte[] itemBytes = new byte[len]; + input.readFully(itemBytes); + contents[i] = CardboardBox.deserializeItem(itemBytes); + } + return contents; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/EconomyOperations.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/EconomyOperations.java new file mode 100644 index 0000000..1ca3f35 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/EconomyOperations.java @@ -0,0 +1,147 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.vaultmanagement; + +import com.drtshock.playervaults.PlayerVaults; +import net.milkbowl.vault.economy.Economy; +import net.milkbowl.vault.economy.EconomyResponse; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.RegisteredServiceProvider; + +import java.io.File; + +/** + * A class that handles all economy operations. + */ +public class EconomyOperations { + + private static Economy economy; + + public static boolean setup() { + economy = null; + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") != null) { + RegisteredServiceProvider provider = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (provider != null) { + economy = provider.getProvider(); + return true; + } + } + return false; + } + + public static String getName() { + return economy == null ? "NONE" : economy.getName(); + } + + public static String getPermsName() { + RegisteredServiceProvider provider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + if (provider != null) { + Permission perm = provider.getProvider(); + return perm.getName(); + } + return null; + } + + /** + * Have a player pay to open a vault. + * + * @param player The player to pay. + * @param number The vault number to open. + * @return The transaction success. + */ + public static boolean payToOpen(Player player, int number) { + if (!PlayerVaults.getInstance().isEconomyEnabled() || player.hasPermission("playervaults.free")) { + return true; + } + + if (!VaultManager.getInstance().vaultExists(player.getUniqueId().toString(), number)) { + return payToCreate(player); + } else { + if (PlayerVaults.getInstance().getConf().getEconomy().getFeeToOpen() == 0) { + return true; + } + double cost = PlayerVaults.getInstance().getConf().getEconomy().getFeeToOpen(); + EconomyResponse resp = economy.withdrawPlayer(player, cost); + if (resp.transactionSuccess()) { + PlayerVaults.getInstance().getTL().costToOpen().title().with("price", cost + "").send(player); + return true; + } + } + + return false; + } + + /** + * Have a player pay to create a vault. + * + * @param player The player to pay. + * @return The transaction success + */ + public static boolean payToCreate(Player player) { + if (!PlayerVaults.getInstance().isEconomyEnabled() || PlayerVaults.getInstance().getConf().getEconomy().getFeeToCreate() == 0 || player.hasPermission("playervaults.free")) { + return true; + } + + double cost = PlayerVaults.getInstance().getConf().getEconomy().getFeeToCreate(); + EconomyResponse resp = economy.withdrawPlayer(player, cost); + if (resp.transactionSuccess()) { + PlayerVaults.getInstance().getTL().costToCreate().title().with("price", cost + "").send(player); + return true; + } + + return false; + } + + /** + * Have a player get his money back when vault is deleted. + * + * @param player The player to receive the money. + * @param number The vault number to delete. + * @return The transaction success. + */ + public static boolean refundOnDelete(Player player, int number) { + if (!PlayerVaults.getInstance().isEconomyEnabled() || PlayerVaults.getInstance().getConf().getEconomy().getRefundOnDelete() == 0 || player.hasPermission("playervaults.free")) { + return true; + } + + File playerFile = new File(PlayerVaults.getInstance().getVaultData(), player.getUniqueId().toString() + ".yml"); + if (playerFile.exists()) { + YamlConfiguration playerData = YamlConfiguration.loadConfiguration(playerFile); + if (playerData.getString("vault" + number) == null) { + PlayerVaults.getInstance().getTL().vaultDoesNotExist().title().send(player); + return false; + } + } else { + PlayerVaults.getInstance().getTL().vaultDoesNotExist().title().send(player); + return false; + } + + double cost = PlayerVaults.getInstance().getConf().getEconomy().getRefundOnDelete(); + EconomyResponse resp = economy.depositPlayer(player, cost); + if (resp.transactionSuccess()) { + PlayerVaults.getInstance().getTL().refundAmount().title().with("price", cost + "").send(player); + return true; + } + + return false; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/Serialization.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/Serialization.java new file mode 100644 index 0000000..27d3469 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/Serialization.java @@ -0,0 +1,161 @@ +package com.drtshock.playervaults.vaultmanagement; + +import java.util.*; +import org.bukkit.*; +import org.bukkit.inventory.*; +import org.json.simple.*; +import org.bukkit.configuration.serialization.*; + +public class Serialization +{ + @Deprecated + public static Map toMap(final JSONObject jsonObject) { + final HashMap hashMap = new HashMap(); + if (jsonObject == null) { + return hashMap; + } + for (final Object next : jsonObject.keySet()) { + hashMap.put(next.toString(), fromJson(jsonObject.get(next))); + } + return hashMap; + } + + @Deprecated + private static Object fromJson(final Object o) { + if (o == null) { + return null; + } + if (o instanceof JSONObject) { + return toMap((JSONObject)o); + } + if (o instanceof JSONArray) { + return toList((JSONArray)o); + } + return o; + } + + @Deprecated + public static List toList(final JSONArray jsonArray) { + final ArrayList list = new ArrayList(); + final Iterator iterator = jsonArray.iterator(); + while (iterator.hasNext()) { + list.add(fromJson(iterator.next())); + } + return list; + } + + @Deprecated + public static List toString(Inventory paramInventory) { + ArrayList arrayList = new ArrayList(); + ArrayList arrayList1 = new ArrayList(); + Collections.addAll(arrayList1, paramInventory.getContents()); + for (ConfigurationSerializable configurationSerializable : arrayList1) { + if (configurationSerializable == null) { + arrayList.add("null"); + continue; + } + arrayList.add((new JSONObject(serialize(configurationSerializable))).toString()); + } + return arrayList; + } + @Deprecated + public static Inventory toInventory(final List list, final int n, final int n2, final String s) { + final VaultHolder vaultHolder = new VaultHolder(n); + final Inventory inventory = Bukkit.createInventory((InventoryHolder)vaultHolder, n2, s); + vaultHolder.setInventory(inventory); + final ArrayList list2 = new ArrayList(); + for (final String s2 : list) { + if (s2.equalsIgnoreCase("null")) { + list2.add(null); + } + else { + list2.add((ItemStack)deserialize(toMap((JSONObject)JSONValue.parse(s2)))); + } + } + final ItemStack[] contents = new ItemStack[list2.size()]; + for (int i = 0; i < list2.size(); ++i) { + contents[i] = (ItemStack)list2.get(i); + } + inventory.setContents(contents); + return inventory; + } + + @Deprecated + public static Map serialize(final ConfigurationSerializable configurationSerializable) { + final Map handleSerialization = handleSerialization(configurationSerializable.serialize()); + handleSerialization.put("==", ConfigurationSerialization.getAlias((Class)configurationSerializable.getClass())); + return handleSerialization; + } + + @Deprecated + private static Map handleSerialization(Map paramMap) { + Map map = recreateMap(paramMap); + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() instanceof ConfigurationSerializable) { + entry.setValue(serialize((ConfigurationSerializable)entry.getValue())); + continue; + } + if (entry.getValue() instanceof Iterable) { + ArrayList> arrayList = new ArrayList(); + for (Map map1 : (Iterable>)entry.getValue()) { + if (map1 instanceof ConfigurationSerializable) + map1 = serialize((ConfigurationSerializable)map1); + arrayList.add(map1); + } + entry.setValue(arrayList); + continue; + } + if (entry.getValue() instanceof Map) + entry.setValue(handleSerialization((Map)entry.getValue())); + } + return map; + } + + @Deprecated + public static Map recreateMap(final Map m) { + return new HashMap(m); + } + + public static Object deserialize(Map paramMap) { + for (Map.Entry entry : paramMap.entrySet()) { + if (entry.getValue() instanceof Map) { + entry.setValue(deserialize((Map)entry.getValue())); + continue; + } + if (entry.getValue() instanceof Iterable) { + entry.setValue(convertIterable((Iterable)entry.getValue())); + continue; + } + if (entry.getValue() instanceof Number) + entry.setValue(convertNumber((Number)entry.getValue())); + } + return paramMap.containsKey("==") ? ConfigurationSerialization.deserializeObject(paramMap) : paramMap; + } + + private static List convertIterable(final Iterable iterable) { + final ArrayList list = new ArrayList(); + for (Object o : iterable) { + if (o instanceof Map) { + o = deserialize((Map)o); + } + else if (o instanceof List) { + o = convertIterable((Iterable)o); + } + else if (o instanceof Number) { + o = convertNumber((Number)o); + } + list.add((Number)o); + } + return list; + } + + private static Number convertNumber(final Number n) { + if (n instanceof Long) { + final Long n2 = (Long)n; + if (n2 == n2.intValue()) { + return n2.intValue(); + } + } + return n; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultHolder.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultHolder.java new file mode 100644 index 0000000..651335d --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultHolder.java @@ -0,0 +1,63 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.vaultmanagement; + +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a VaultHolder to assist in detection of Player Vaults from other plugins. + */ +public class VaultHolder implements InventoryHolder { + + private Inventory inventory; + private final int vaultNumber; + + /** + * Creates a new vault holder + * + * @param vaultNumber the vault number this holder is using + */ + public VaultHolder(int vaultNumber) { + this.vaultNumber = vaultNumber; + } + + /** + * Gets the vault number this holder is currently using + * + * @return the vault number + */ + public int getVaultNumber() { + return vaultNumber; + } + + @Override + public Inventory getInventory() { + return inventory; + } + + /** + * Sets the inventory this vault holder holds + * + * @param inventory the inventory, may be null + */ + public void setInventory(Inventory inventory) { + this.inventory = inventory; + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultManager.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultManager.java new file mode 100644 index 0000000..397d524 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultManager.java @@ -0,0 +1,393 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.vaultmanagement; + +import com.drtshock.playervaults.PlayerVaults; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + +public class VaultManager { + + private static final String VAULTKEY = "vault%d"; + private static VaultManager instance; + private final File directory = PlayerVaults.getInstance().getVaultData(); + private final Map cachedVaultFiles = new ConcurrentHashMap<>(); + private final PlayerVaults plugin; + private final CachedVaultStorage vaultCache; + + public VaultManager(PlayerVaults plugin) { + this.plugin = plugin; + + instance = this; + + this.vaultCache = new CachedVaultStorage(); + } + + /** + * Gets the vault cache for this vault manager. + * @return the vault cache + */ + public CachedVaultStorage getVaultCache() { + return vaultCache; + } + + /** + * Get the instance of this class. + * + * @return - instance of this class. + */ + public static VaultManager getInstance() { + return instance; + } + + /** + * Saves the inventory to the specified player and vault number. + * + * @param inventory The inventory to be saved. + * @param target The player of whose file to save to. + * @param number The vault number. + */ + public void saveVault(Inventory inventory, String target, int number) { + YamlConfiguration yaml = getPlayerVaultFile(target, true); + int size = VaultOperations.getMaxVaultSize(target); + String serialized = CardboardBoxSerialization.toStorage(inventory, target); + yaml.set(String.format(VAULTKEY, number), serialized); + saveFileSync(target, yaml); + } + + /** + * Load the player's vault and return it. + * + * @param player The holder of the vault. + * @param number The vault number. + */ + public Inventory loadOwnVault(Player player, int number, int size) { + if (size % 9 != 0) { + size = PlayerVaults.getInstance().getDefaultVaultSize(); + } + + PlayerVaults.debug("Loading self vault for " + player.getName() + " (" + player.getUniqueId() + ')'); + + String title = PlayerVaults.getInstance().getVaultTitle(String.valueOf(number)); + VaultViewInfo info = new VaultViewInfo(player.getUniqueId().toString(), number); + if (PlayerVaults.getInstance().getOpenInventories().containsKey(info.toString())) { + PlayerVaults.debug("Already open"); + return PlayerVaults.getInstance().getOpenInventories().get(info.toString()); + } + + Optional cachedVault = getVaultCache().getCachedVault(player.getUniqueId(), number); + + if(cachedVault.isPresent()) + { + return cachedVault.get(); + } + + YamlConfiguration playerFile = getPlayerVaultFile(player.getUniqueId().toString(), true); + VaultHolder vaultHolder = new VaultHolder(number); + if (playerFile.getString(String.format(VAULTKEY, number)) == null) { + PlayerVaults.debug("No vault matching number"); + Inventory inv = Bukkit.createInventory(vaultHolder, size, title); + vaultHolder.setInventory(inv); + return inv; + } else { + return getInventory(vaultHolder, player.getUniqueId().toString(), playerFile, size, number, title); + } + } + + /** + * Load the player's vault and return it. + * + * @param name The holder of the vault. + * @param number The vault number. + */ + public Inventory loadOtherVault(String name, int number, int size) { + if (size % 9 != 0) { + size = PlayerVaults.getInstance().getDefaultVaultSize(); + } + + PlayerVaults.debug("Loading other vault for " + name); + + String holder = name; + + try { + UUID uuid = UUID.fromString(name); + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); + holder = offlinePlayer.getUniqueId().toString(); + } catch (Exception e) { + // Not a player + } + + String title = PlayerVaults.getInstance().getVaultTitle(String.valueOf(number)); + VaultViewInfo info = new VaultViewInfo(name, number); + Inventory inv; + VaultHolder vaultHolder = new VaultHolder(number); + if (PlayerVaults.getInstance().getOpenInventories().containsKey(info.toString())) { + PlayerVaults.debug("Already open"); + inv = PlayerVaults.getInstance().getOpenInventories().get(info.toString()); + } else { + YamlConfiguration playerFile = getPlayerVaultFile(holder, true); + Inventory i = getInventory(vaultHolder, holder, playerFile, size, number, title); + if (i == null) { + return null; + } else { + inv = i; + } + PlayerVaults.getInstance().getOpenInventories().put(info.toString(), inv); + } + return inv; + } + + /** + * Get an inventory from file. Returns null if the inventory doesn't exist. SHOULD ONLY BE USED INTERNALLY + * + * @param playerFile the YamlConfiguration file. + * @param size the size of the vault. + * @param number the vault number. + * @return inventory if exists, otherwise null. + */ + private Inventory getInventory(InventoryHolder owner, String ownerName, YamlConfiguration playerFile, int size, int number, String title) { + Inventory inventory = Bukkit.createInventory(owner, size, title); + + String data = playerFile.getString(String.format(VAULTKEY, number)); + ItemStack[] deserialized = CardboardBoxSerialization.fromStorage(data, ownerName); + if (deserialized == null) { + PlayerVaults.debug("Loaded vault for " + ownerName + " as null"); + return inventory; + } + + // Check if deserialized has more used slots than the limit here. + // Happens on change of permission or if people used the broken version. + // In this case, players will lose items. + if (deserialized.length > size) { + PlayerVaults.debug("Loaded vault for " + ownerName + " and got " + deserialized.length + " items for allowed size of " + size+". Attempting to rescue!"); + for (ItemStack stack : deserialized) { + if (stack != null) { + inventory.addItem(stack); + } + } + } else { + inventory.setContents(deserialized); + } + + PlayerVaults.debug("Loaded vault"); + return inventory; + } + + /** + * Gets an inventory without storing references to it. Used for dropping a players inventories on death. + * + * @param holder The holder of the vault. + * @param number The vault number. + * @return The inventory of the specified holder and vault number. Can be null. + */ + public Inventory getVault(String holder, int number) { + YamlConfiguration playerFile = getPlayerVaultFile(holder, true); + String serialized = playerFile.getString(String.format(VAULTKEY, number)); + ItemStack[] contents = CardboardBoxSerialization.fromStorage(serialized, holder); + Inventory inventory = Bukkit.createInventory(null, contents.length, holder + " vault " + number); + inventory.setContents(contents); + return inventory; + } + + /** + * Checks if a vault exists. + * + * @param holder holder of the vault. + * @param number vault number. + * @return true if the vault file and vault number exist in that file, otherwise false. + */ + public boolean vaultExists(String holder, int number) { + File file = new File(directory, holder + ".yml"); + if (!file.exists()) { + return false; + } + + return getPlayerVaultFile(holder, true).contains(String.format(VAULTKEY, number)); + } + + /** + * Gets the numbers belonging to all their vaults. + * + * @param holder holder + * @return a set of Integers, which are player's vaults' numbers (fuck grammar). + */ + public Set getVaultNumbers(String holder) { + Set vaults = new HashSet<>(); + YamlConfiguration file = getPlayerVaultFile(holder, true); + if (file == null) { + return vaults; + } + + for (String s : file.getKeys(false)) { + try { + // vault% + int number = Integer.parseInt(s.substring(4)); + vaults.add(number); + } catch (NumberFormatException e) { + // silent + } + } + + + return vaults; + } + + public void deleteAllVaults(String holder) { + removeCachedPlayerVaultFile(holder); + deletePlayerVaultFile(holder); + } + + /** + * Deletes a players vault. + * + * @param sender The sender of whom to send messages to. + * @param holder The vault holder. + * @param number The vault number. + */ + public void deleteVault(CommandSender sender, final String holder, final int number) { + new BukkitRunnable() { + @Override + public void run() { + File file = new File(directory, holder + ".yml"); + if (!file.exists()) { + return; + } + + YamlConfiguration playerFile = YamlConfiguration.loadConfiguration(file); + if (file.exists()) { + playerFile.set(String.format(VAULTKEY, number), null); + if (cachedVaultFiles.containsKey(holder)) { + cachedVaultFiles.put(holder, playerFile); + } + try { + playerFile.save(file); + } catch (IOException ignored) { + } + } + } + }.runTaskAsynchronously(PlayerVaults.getInstance()); + + OfflinePlayer player = Bukkit.getPlayer(holder); + if (player != null) { + if (sender.getName().equalsIgnoreCase(player.getName())) { + this.plugin.getTL().deleteVault().title().with("vault", String.valueOf(number)).send(sender); + } else { + this.plugin.getTL().deleteOtherVault().title().with("vault", String.valueOf(number)).with("player", player.getName()).send(sender); + } + } + + String vaultName = sender instanceof Player ? ((Player) sender).getUniqueId().toString() : holder; + PlayerVaults.getInstance().getOpenInventories().remove(new VaultViewInfo(vaultName, number).toString()); + } + + // Should only be run asynchronously + public void cachePlayerVaultFile(String holder) { + YamlConfiguration config = this.loadPlayerVaultFile(holder, false); + if (config != null) { + this.cachedVaultFiles.put(holder, config); + } + } + + public void removeCachedPlayerVaultFile(String holder) { + cachedVaultFiles.remove(holder); + } + + /** + * Get the holder's vault file. Create if doesn't exist. + * + * @param holder The vault holder. + * @return The holder's vault config file. + */ + public YamlConfiguration getPlayerVaultFile(String holder, boolean createIfNotFound) { + if (cachedVaultFiles.containsKey(holder)) { + return cachedVaultFiles.get(holder); + } + return loadPlayerVaultFile(holder, createIfNotFound); + } + + public YamlConfiguration loadPlayerVaultFile(String holder) { + return this.loadPlayerVaultFile(holder, true); + } + + /** + * Attempt to delete a vault file. + * + * @param holder UUID of the holder. + */ + public void deletePlayerVaultFile(String holder) { + File file = new File(this.directory, holder + ".yml"); + if (file.exists()) { + file.delete(); + } + } + + public YamlConfiguration loadPlayerVaultFile(String uniqueId, boolean createIfNotFound) { + if (!this.directory.exists()) { + this.directory.mkdir(); + } + + File file = new File(this.directory, uniqueId + ".yml"); + if (!file.exists()) { + if (createIfNotFound) { + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + return null; + } + } + + return YamlConfiguration.loadConfiguration(file); + } + + public void saveFileSync(final String holder, final YamlConfiguration yaml) { + if (cachedVaultFiles.containsKey(holder)) { + cachedVaultFiles.put(holder, yaml); + } + + final boolean backups = PlayerVaults.getInstance().isBackupsEnabled(); + final File backupsFolder = PlayerVaults.getInstance().getBackupsFolder(); + final File file = new File(directory, holder + ".yml"); + if (file.exists() && backups) { + file.renameTo(new File(backupsFolder, holder + ".yml")); + } + try { + yaml.save(file); + } catch (IOException e) { + PlayerVaults.getInstance().addException(new IllegalStateException("Failed to save vault file for: " + holder, e)); + PlayerVaults.getInstance().getLogger().log(Level.SEVERE, "Failed to save vault file for: " + holder, e); + } + PlayerVaults.debug("Saved vault for " + holder); + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultOperations.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultOperations.java new file mode 100644 index 0000000..7f4b42d --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultOperations.java @@ -0,0 +1,366 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.vaultmanagement; + +import com.drtshock.playervaults.PlayerVaults; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; + +public class VaultOperations { + + private static final AtomicBoolean LOCKED = new AtomicBoolean(false); + + /** + * Gets whether or not player vaults are locked + * + * @return true if locked, false otherwise + */ + public static boolean isLocked() { + return LOCKED.get(); + } + + /** + * Sets whether or not player vaults are locked. If set to true, this will kick anyone who is currently using their + * vaults out. + * + * @param locked true for locked, false otherwise + */ + public static void setLocked(boolean locked) { + LOCKED.set(locked); + + if (locked) { + for (Player player : PlayerVaults.getInstance().getServer().getOnlinePlayers()) { + if (player.getOpenInventory() != null) { + InventoryView view = player.getOpenInventory(); + if (view.getTopInventory().getHolder() instanceof VaultHolder) { + player.closeInventory(); + PlayerVaults.getInstance().getTL().locked().title().send(player); + } + } + } + } + } + + /** + * Check whether or not the player has permission to open the requested vault. + * + * @param sender The person to check. + * @param number The vault number. + * @return Whether or not they have permission. + */ + public static boolean checkPerms(CommandSender sender, int number) { + if (sender.hasPermission("playervaults.amount." + number)) { + return true; + } + for (int x = number; x <= PlayerVaults.getInstance().getMaxVaultAmountPermTest(); x++) { + if (sender.hasPermission("playervaults.amount." + x)) { + return true; + } + } + return false; + } + + /** + * Get the max size vault a player is allowed to have. + * + * @param name that is having his permissions checked. + * @return max size as integer. If no max size is set then it will default to the configured default. + */ + public static int getMaxVaultSize(String name) { + try { + UUID uuid = UUID.fromString(name); + return getMaxVaultSize(Bukkit.getOfflinePlayer(uuid)); + } catch (Exception e) { + // Not a UUID + } + + return PlayerVaults.getInstance().getDefaultVaultSize(); + } + + /** + * Get the max size vault a player is allowed to have. + * + * @param player that is having his permissions checked. + * @return max size as integer. If no max size is set then it will default to the configured default. + */ + public static int getMaxVaultSize(OfflinePlayer player) { + if (player == null || !player.isOnline()) { + return 6 * 9; + } + for (int i = 6; i != 0; i--) { + if (player.getPlayer().hasPermission("playervaults.size." + i)) { + return i * 9; + } + } + return PlayerVaults.getInstance().getDefaultVaultSize(); + } + + /** + * Open a player's own vault. + * + * @param player The player to open to. + * @param arg The vault number to open. + * @return Whether or not the player was allowed to open it. + */ + public static boolean openOwnVault(Player player, String arg) { + return openOwnVaultE(player, arg, false, true); + } + + public static boolean openOwnVaultSign(Player player, String arg) { + return openOwnVaultE(player, arg, true, false); + } + + private static boolean openOwnVaultE(Player player, String arg, boolean free, boolean send) { + if (isLocked()) { + return false; + } + if (player.isSleeping() || player.isDead() || !player.isOnline()) { + return false; + } + int number; + try { + number = Integer.parseInt(arg); + if (number < 1) { + return false; + } + } catch (NumberFormatException nfe) { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(player); + return false; + } + + if (checkPerms(player, number)) { + if (free || EconomyOperations.payToOpen(player, number)) { + Inventory inv = VaultManager.getInstance().loadOwnVault(player, number, getMaxVaultSize(player)); + if (inv == null) { + PlayerVaults.debug(String.format("Failed to open null vault %d for %s. This is weird.", number, player.getName())); + return false; + } + + player.openInventory(inv); + + // Check if the inventory was actually opened + if (player.getOpenInventory().getTopInventory() instanceof CraftingInventory || player.getOpenInventory().getTopInventory() == null) { + PlayerVaults.debug(String.format("Cancelled opening vault %s for %s from an outside source.", arg, player.getName())); + return false; // inventory open event was cancelled. + } + + VaultViewInfo info = new VaultViewInfo(player.getUniqueId().toString(), number); + PlayerVaults.getInstance().getOpenInventories().put(info.toString(), inv); + + if (send) { + PlayerVaults.getInstance().getTL().openVault().title().with("vault", arg).send(player); + } + return true; + } else { + PlayerVaults.getInstance().getTL().insufficientFunds().title().send(player); + return false; + } + } else { + PlayerVaults.getInstance().getTL().noPerms().title().send(player); + } + return false; + } + + /** + * Open a player's own vault. If player is using a command, they'll need the required permission. + * + * @param player The player to open to. + * @param arg The vault number to open. + * @param isCommand - if player is opening via a command or not. + * @return Whether or not the player was allowed to open it. + */ + public static boolean openOwnVault(Player player, String arg, boolean isCommand) { + if (!isCommand || player.hasPermission("playervaults.commands.use")) { + return openOwnVault(player, arg); + } + PlayerVaults.getInstance().getTL().noPerms().title().send(player); + return false; + } + + /** + * Open another player's vault. + * + * @param player The player to open to. + * @param vaultOwner The name of the vault owner. + * @param arg The vault number to open. + * @return Whether or not the player was allowed to open it. + */ + public static boolean openOtherVault(Player player, String vaultOwner, String arg) { + return openOtherVault(player, vaultOwner, arg, true); + } + + public static boolean openOtherVault(Player player, String vaultOwner, String arg, boolean send) { + if (isLocked()) { + return false; + } + + if (player.isSleeping() || player.isDead() || !player.isOnline()) { + return false; + } + + long time = System.currentTimeMillis(); + + int number = 0; + try { + number = Integer.parseInt(arg); + if (number < 1) { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(player); + return false; + } + } catch (NumberFormatException nfe) { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(player); + } + + Inventory inv = VaultManager.getInstance().loadOtherVault(vaultOwner, number, getMaxVaultSize(vaultOwner)); + String name = vaultOwner; + try { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(vaultOwner)); + name = offlinePlayer.getName(); + } catch (Exception e) { + // not a player + } + + if (inv == null) { + PlayerVaults.getInstance().getTL().vaultDoesNotExist().title().send(player); + } else { + player.openInventory(inv); + + // Check if the inventory was actually opened + if (player.getOpenInventory().getTopInventory() instanceof CraftingInventory || player.getOpenInventory().getTopInventory() == null) { + PlayerVaults.debug(String.format("Cancelled opening vault %s for %s from an outside source.", arg, player.getName())); + return false; // inventory open event was cancelled. + } + if (send) { + PlayerVaults.getInstance().getTL().openOtherVault().title().with("vault", arg).with("player", name).send(player); + } + PlayerVaults.debug("opening other vault", time); + + // Need to set ViewInfo for a third party vault for the opening player. + VaultViewInfo info = new VaultViewInfo(vaultOwner, number); + PlayerVaults.getInstance().getInVault().put(player.getUniqueId().toString(), info); + PlayerVaults.getInstance().getOpenInventories().put(player.getUniqueId().toString(), inv); + return true; + } + + PlayerVaults.debug("opening other vault returning false", time); + return false; + } + + /** + * Delete a player's own vault. + * + * @param player The player to delete. + * @param arg The vault number to delete. + */ + public static void deleteOwnVault(Player player, String arg) { + if (isLocked()) { + return; + } + if (isNumber(arg)) { + int number = 0; + try { + number = Integer.parseInt(arg); + if (number == 0) { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(player); + return; + } + } catch (NumberFormatException nfe) { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(player); + } + + if (EconomyOperations.refundOnDelete(player, number)) { + VaultManager.getInstance().deleteVault(player, player.getUniqueId().toString(), number); + PlayerVaults.getInstance().getTL().deleteVault().title().with("vault", arg).send(player); + } + + } else { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(player); + } + } + + /** + * Delete a player's vault. + * + * @param sender The sender executing the deletion. + * @param holder The user to whom the deleted vault belongs. + * @param arg The vault number to delete. + */ + public static void deleteOtherVault(CommandSender sender, String holder, String arg) { + if (isLocked()) { + return; + } + if (sender.hasPermission("playervaults.delete")) { + if (isNumber(arg)) { + int number = 0; + try { + number = Integer.parseInt(arg); + if (number == 0) { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(sender); + return; + } + } catch (NumberFormatException nfe) { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(sender); + } + + VaultManager.getInstance().deleteVault(sender, holder, number); + PlayerVaults.getInstance().getTL().deleteOtherVault().title().with("vault", arg).with("player", holder).send(sender); + } else { + PlayerVaults.getInstance().getTL().mustBeNumber().title().send(sender); + } + } else { + PlayerVaults.getInstance().getTL().noPerms().title().send(sender); + } + } + + /** + * Delete all of a player's vaults + * + * @param sender The sender executing the deletion. + * @param holder The user to whom the deleted vault belongs. + */ + public static void deleteOtherAllVaults(CommandSender sender, String holder) { + if (isLocked() || holder == null) { + return; + } + + if (sender.hasPermission("playervaults.delete.all")) { + VaultManager.getInstance().deleteAllVaults(holder); + PlayerVaults.getInstance().getLogger().info(String.format("%s deleted ALL vaults belonging to %s", sender.getName(), holder)); + } else { + PlayerVaults.getInstance().getTL().noPerms().title().send(sender); + } + } + + private static boolean isNumber(String check) { + try { + Integer.parseInt(check); + return true; + } catch (NumberFormatException e) { + return false; + } + } +} diff --git a/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultViewInfo.java b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultViewInfo.java new file mode 100644 index 0000000..756b9d2 --- /dev/null +++ b/PlayerVaultsX/src/main/java/com/drtshock/playervaults/vaultmanagement/VaultViewInfo.java @@ -0,0 +1,61 @@ +/* + * PlayerVaultsX + * Copyright (C) 2013 Trent Hensler + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.drtshock.playervaults.vaultmanagement; + +/** + * A class that stores information about a vault viewing including the holder of the vault, and the vault number. + */ +public class VaultViewInfo { + + final String vaultName; + final int number; + + /** + * Makes a VaultViewInfo object. Used for opening a vault owned by the opener. + * + * @param i vault number. + */ + public VaultViewInfo(String vaultName, int i) { + this.number = i; + this.vaultName = vaultName; + } + + /** + * Get the holder of the vault. + * + * @return The holder of the vault. + */ + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the vault number. + * + * @return The vault number. + */ + public int getNumber() { + return this.number; + } + + @Override + public String toString() { + return this.vaultName + " " + this.number; + } +} \ No newline at end of file diff --git a/PlayerVaultsX/src/main/resources/credit/apache2-license.txt b/PlayerVaultsX/src/main/resources/credit/apache2-license.txt new file mode 100644 index 0000000..e25e752 --- /dev/null +++ b/PlayerVaultsX/src/main/resources/credit/apache2-license.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/PlayerVaultsX/src/main/resources/credit/credit.txt b/PlayerVaultsX/src/main/resources/credit/credit.txt new file mode 100644 index 0000000..397294e --- /dev/null +++ b/PlayerVaultsX/src/main/resources/credit/credit.txt @@ -0,0 +1,28 @@ +This project overall is licensed under the GNU GENERAL PUBLIC LICENSE version 3 +and can be found at https://github.com/drtshock/PlayerVaults + +This project source also contains a lightly modified Typesafe Config, +which is licensed under the Apache License, Version 2.0 +and original source can be found at https://github.com/lightbend/config/ + +Shaded libraries into the jar include: + +Adventure +MIT License +A text library. Specifically, adventure-platform-bukkit and adventure-text-minimessage are included +https://github.com/KyoriPowered + +Cardboard Box +GPLv3 +A storage helper. +https://github.com/KittehOrg/CardboardBox + +PasteGGAPI +MIT License +Java API for using paste.gg +https://github.com/KittehOrg/PasteGGAPI + +Google Gson +Apache License, Version 2.0 +JSON handling +https://github.com/google/gson diff --git a/PlayerVaultsX/src/main/resources/credit/gplv3-license.txt b/PlayerVaultsX/src/main/resources/credit/gplv3-license.txt new file mode 100644 index 0000000..47d403b --- /dev/null +++ b/PlayerVaultsX/src/main/resources/credit/gplv3-license.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + PlayerVaultsX Copyright (C) 2013 Trent Hensler + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/PlayerVaultsX/src/main/resources/lang.yml b/PlayerVaultsX/src/main/resources/lang.yml new file mode 100644 index 0000000..aad5141 --- /dev/null +++ b/PlayerVaultsX/src/main/resources/lang.yml @@ -0,0 +1,39 @@ +# Use & for color codes. +# %p is where the player name will get inserted. +# %v is where the vault number will get inserted. +# %price is the price. +# %number is the vault number +# %converted is the number of vaults converted (where applicable) +# %m will be replaced by the blacklisted material (where applicable) +# Made with love :) + +title-name: "&4[&fPlayerVaultsX&4]:" +open-vault: "&fOpening vault &a%v" +open-other-vault: "&fOpening vault &a%v &fof &a%p" +delete-vault: "&fDeleted vault &a%v" +delete-other-vault: "&fDeleted vault &a%v &fof &a%p" +delete-other-vault-all: "&4Deleted all vaults belonging to &a%p" +player-only: "&cSorry but that can only be run by a player!" +must-be-number: "&cYou need to specify a valid number." +invalid-args: "&cInvalid args!" +no-permissions: "&cYou don''t have permission for that!" +insufficient-funds: "&cYou don''t have enough money for that!" +refund-amount: "&fYou were refunded &a%price &ffor deleting that vault." +cost-to-create: "&fYou were charged &c%price &ffor creating a vault." +cost-to-open: "&fYou were charged &c%price &ffor opening that vault." +vault-title: "&4Vault #%number" +existing-vaults: "&f%p has vaults: &a%v" +no-owner-found: "&cCannot find vault owner: &a%p" +plugin-not-found: "&cNo converter found for that plugin." +conversion-complete: "&aConverted %converted players to PlayerVaults" +conversion-background: "&fConversion has been forked to the background. See console for updates." +vaults-locked: "&cVaults are currently locked while conversion occurs. Please try again in a moment!" +help: "/pv " +blocked-item: "&6%m &cis blocked from vaults." +signs-disabled: "&cVault signs are currently disabled." +blocked-bad-item: "&cThis item is not allowed in a vault." +vault-does-not-exist: "&cThat vault does not exist!" +click-a-sign: "&fNow click a sign!" +not-a-sign: "&cYou must click a sign!" +set-sign-success: "&fYou have successfully set a PlayerVault access sign!" +open-with-sign: "&fOpening vault &a%v &fof &a%p" diff --git a/PlayerVaultsX/src/main/resources/lang/bulgarian.yml b/PlayerVaultsX/src/main/resources/lang/bulgarian.yml new file mode 100644 index 0000000..e2ac380 --- /dev/null +++ b/PlayerVaultsX/src/main/resources/lang/bulgarian.yml @@ -0,0 +1,39 @@ +# Използвайте & за цветни съобщения. +# %p се замества с името на играч. +# %v се замества с общия брой сейфове на играча +# %price се замества с цената на сейфа. +# %number се замества с номера на текущия сейф +# %converted е броя конвертирани сейфове (където е приложимо) +# %m ще бъдат заменени от материала на черния списък (където е приложимо) +# Направено с любов :) + +title-name: "&4[&fPlayerVaults&4]:" +open-vault: "&fОтваряме сейф &a%v" +open-other-vault: "&fОтваряме сейф &a%v &fна &a%p" +delete-vault: "&fИзтрихме сейф &a%v" +delete-other-vault: "&fИзтрихме сейф &a%v &fна &a%p" +delete-other-vault-all: "&4Deleted all vaults belonging to &a%p" +player-only: "&cСъжаляваме, но тази команда може да се използва само от играчи!" +must-be-number: "&cТрябва да посочите номер от 1 до 99" +invalid-args: "&cНевалидни аргументи!" +no-permissions: "&cНямате права за тази операция!" +insufficient-funds: "&cНямате достатъчно пари за тази операция!" +refund-amount: "&fВърнахме ви &a%price &fза изтриването на този сейф." +cost-to-create: "&fБяхте таксувани &c%price &fза създаването на този сейф." +cost-to-open: "&fБяхте таксувани &c%price &fза отварянето на този сейф." +vault-title: "&4Сейф #%number" +existing-vaults: "&f%p има &a%v &fсейфа" +no-owner-found: "&cCannot find vault owner: &a%p" +plugin-not-found: "&cНямаме конвертор за този плъгин." +conversion-complete: "&aКонвертирахме %converted играч(а) към PlayerVaults" +conversion-background: "&fЗапочнахме конвертирането на заден план. Следете конзолата за статуса на операцията." +vaults-locked: "&cСейфовете са заключени докато тече конвертиране. Моля, опитайте пак по-късно!" +help: "/pv <номер>" +blocked-item: "&6%m &cне може да се слага в сейфове." +signs-disabled: "&cVault signs are currently disabled." +blocked-bad-item: "&cThis item is not allowed in a vault." +vault-does-not-exist: "&cThat vault does not exist!" +click-a-sign: "&fNow click a sign!" +not-a-sign: "&cYou must click a sign!" +set-sign-success: "&fYou have successfully set a PlayerVault access sign!" +open-with-sign: "&fOpening vault &a%v &fof &a%p" diff --git a/PlayerVaultsX/src/main/resources/lang/danish.yml b/PlayerVaultsX/src/main/resources/lang/danish.yml new file mode 100644 index 0000000..a7b6c16 --- /dev/null +++ b/PlayerVaultsX/src/main/resources/lang/danish.yml @@ -0,0 +1,39 @@ +# Use & for color codes. +# %p is where the player name will get inserted. +# %v is where the vault number will get inserted. +# %price is the price. +# %number is the vault number +# %converted is the number of vaults converted (where applicable) +# %m will be replaced by the blacklisted material (where applicable) +# Made with love :) + +title-name: "&4[&fPlayerVaultsX&4]:" +open-vault: "&fÅbner vault &a%v" +open-other-vault: "&fÅbner vault &a%v &fof &a%p" +delete-vault: "&fSlettede vault &a%v" +delete-other-vault: "&fSlettede vault &a%v &fof &a%p" +delete-other-vault-all: "&4Deleted all vaults belonging to &a%p" +player-only: "&cUndskyld, men dette kan kun gøres af en spiller!" +must-be-number: "&cDu skal skrive et nummer mellem 1-99" +invalid-args: "&cUgyldige argumenter!" +no-permissions: "&cDu har ikke adgang til dette!" +insufficient-funds: "&cDu har ikke nok penge til dette!" +refund-amount: "&fDu blev tilbagebetalt &a%price &ffor sletning af vaulten." +cost-to-create: "&fDu betalte &c%price &ffor at lave vaulten." +cost-to-open: "&fDu betalte &c%price &ffor at åbne vaulten." +vault-title: "&4Vault #%number" +existing-vaults: "&f%p har vaults: &a%v" +no-owner-found: "&cKan ikke finde &a%p" +plugin-not-found: "&cKunne ikke konventere dette plugin." +conversion-complete: "&aKonventerede %converted players to PlayerVaults" +conversion-background: "&fKonventering er blevet kløvet til at køre i baggrunden. Se i konsolen for opdateringer." +vaults-locked: "&cVaults er i øjeblikket låst, imens konventeringen er iganværende. Prøv igen om lidt." +help: "/pv " +blocked-item: "&6%m &cer blokeret fra vaults." +signs-disabled: "&cVault signs are currently disabled." +blocked-bad-item: "&cThis item is not allowed in a vault." +vault-does-not-exist: "&cThat vault does not exist!" +click-a-sign: "&fNow click a sign!" +not-a-sign: "&cYou must click a sign!" +set-sign-success: "&fYou have successfully set a PlayerVault access sign!" +open-with-sign: "&fOpening vault &a%v &fof &a%p" diff --git a/PlayerVaultsX/src/main/resources/lang/dutch.yml b/PlayerVaultsX/src/main/resources/lang/dutch.yml new file mode 100644 index 0000000..d2c4b56 --- /dev/null +++ b/PlayerVaultsX/src/main/resources/lang/dutch.yml @@ -0,0 +1,39 @@ +# Gebruik & voor kleurcodes. +# %p is waar de naam van de speler wordt ingevoegd. +# %v is waar het kluisnummer wordt ingevoegd. +# %price is de prijs. +# %number is het kluisnummer +# %converted is het aantal geconverteerde kluizen (where applicable) +# %m wordt vervangen door het op de zwarte lijst geplaatste materiaal (where applicable) +# Gemaakt met liefde :) + +title-name: "&4[&fPlayerVaults&4]:" +open-vault: "&fVault &a%v openen" +open-other-vault: "&fVault &a%v &van &a%p openen" +delete-vault: "&fVault &a%v verwijderd" +delete-other-vault: "&fVault &a%v &fvan &a%p verwijderd" +delete-other-vault-all: "&4Deleted all vaults belonging to &a%p" +player-only: "&cDit commando kan alleen door spelers gebruikt worden!" +must-be-number: "&cJe moet een nummer tussen 1 en 99 aanduiden" +invalid-args: "&cOngeldige argumenten!" +no-permissions: "&cJe hebt hier geen toestemming voor!" +insufficient-funds: "&cJe hebt hier niet genoeg geld voor!" +refund-amount: "&fje bent &a%price terugbetaald &fvoor het verwijderen van die vault." +cost-to-create: "&fje bent &c%price aangerekend &fvoor deze vault te creëren." +cost-to-open: "&fJe bent &c%price aangerekend &fvoor het openen van deze vault." +vault-title: "&4Vault #%number" +existing-vaults: "&f%p heeft vault: &a%v" +no-owner-found: "&cCannot find vault owner: &a%p" +plugin-not-found: "&cGeen converter gevonden voor die plugin." +conversion-complete: "&aEr zijn %converted spelers naar PlayerVaults geconverteerd" +conversion-background: "&fHet converteren is naar de achtergrond geplaatst. Check de console voor de status van het converteren" +vaults-locked: "&cVaults zijn op dit moment op slot terwijl het wordt geconverteerd. Probeer het later opnieuw!" +help: "/pv " +blocked-item: "&6%m &cis geblokkeer van vaults." +signs-disabled: "&cVault signs are currently disabled." +blocked-bad-item: "&cThis item is not allowed in a vault." +vault-does-not-exist: "&cThat vault does not exist!" +click-a-sign: "&fNow click a sign!" +not-a-sign: "&cYou must click a sign!" +set-sign-success: "&fYou have successfully set a PlayerVault access sign!" +open-with-sign: "&fOpening vault &a%v &fof &a%p" diff --git a/PlayerVaultsX/src/main/resources/lang/english.yml b/PlayerVaultsX/src/main/resources/lang/english.yml new file mode 100644 index 0000000..898c3eb --- /dev/null +++ b/PlayerVaultsX/src/main/resources/lang/english.yml @@ -0,0 +1,39 @@ +# Use & for color codes. +# %p is where the player name will get inserted. +# %v is where the vault number will get inserted. +# %price is the price. +# %number is the vault number +# %converted is the number of vaults converted (where applicable) +# %m will be replaced by the blacklisted material (where applicable) +# Made with love :) + +title-name: "&4[&fPlayerVaultsX&4]:" +open-vault: "&fOpening vault &a%v" +open-other-vault: "&fOpening vault &a%v &fof &a%p" +delete-vault: "&fDeleted vault &a%v" +delete-other-vault: "&fDeleted vault &a%v &fof &a%p" +delete-other-vault-all: "&4Deleted all vaults belonging to &a%p" +player-only: "&cSorry but that can only be run by a player!" +must-be-number: "&cYou need to specify a valid number." +invalid-args: "&cInvalid args!" +no-permissions: "&cYou don't have permission for that!" +insufficient-funds: "&cYou don't have enough money for that!" +refund-amount: "&fYou were refunded &a%price &ffor deleting that vault." +cost-to-create: "&fYou were charged &c%price &ffor creating a vault." +cost-to-open: "&fYou were charged &c%price &ffor opening that vault." +vault-title: "&4Vault #%number" +existing-vaults: "&f%p has vaults: &a%v" +no-owner-found: "&cCannot find vault owner: &a%p" +plugin-not-found: "&cNo converter found for that plugin." +conversion-complete: "&aConverted %converted players to PlayerVaults" +conversion-background: "&fConversion has been forked to the background. See console for updates." +vaults-locked: "&cVaults are currently locked while conversion occurs. Please try again in a moment!" +help: "/pv " +blocked-item: "&6%m &cis blocked from vaults." +signs-disabled: "&cVault signs are currently disabled." +blocked-bad-item: "&cThis item is not allowed in a vault." +vault-does-not-exist: "&cThat vault does not exist!" +click-a-sign: "&fNow click a sign!" +not-a-sign: "&cYou must click a sign!" +set-sign-success: "&fYou have successfully set a PlayerVault access sign!" +open-with-sign: "&fOpening vault &a%v &fof &a%p" diff --git a/PlayerVaultsX/src/main/resources/lang/german.yml b/PlayerVaultsX/src/main/resources/lang/german.yml new file mode 100644 index 0000000..5a82c1b --- /dev/null +++ b/PlayerVaultsX/src/main/resources/lang/german.yml @@ -0,0 +1,39 @@ +# Nutze & für Farbcodes. +# Bei %p wird der Spielername eingefügt. +# Bei %v wird die Tresornummer eingefügt. +# %price ist der Preis. +# %number ist die Tresornummer. +# %converted ist die Nummer an Tresoren, die konvertiert wurden (sofern möglich) +# %m wird durch das Blacklist-Material ersetzt (sofern möglich) +# Mit Liebe gemacht :) + +title-name: "&4[&fPlayerVaultsX&4]:" +open-vault: "&fÖffne Tresor &a%v" +open-other-vault: "&fÖffne Tresor &a%v &fvon &a%p" +delete-vault: "&fLösche Tresor &a%v" +delete-other-vault: "&fLösche Tresor &a%v &fvon &a%p" +delete-other-vault-all: "&4Deleted all vaults belonging to &a%p" +player-only: "&cSorry, dies kann nur durch Spieler durchgeführt werden!" +must-be-number: "&cDu musst eine Nummer zwischen 1-99 eingeben" +invalid-args: "&cUnzulässige Argumente!" +no-permissions: "&cDu hast keine Berechtigung dafür!" +insufficient-funds: "&cDu hast nicht genug Geld dafür!" +refund-amount: "&fDir wurden &a%price &ffür das Löschen des Tresors zurückgegeben." +cost-to-create: "&fDir wurden &c%price &ffür das Erstellen des Tresors berechnet." +cost-to-open: "&fDir wurden von &c%price &ffür das Öffnen des Tresors berechnet." +vault-title: "&4Tresor #%number" +existing-vaults: "&f%p hat folgende Tresore: &a%v" +no-owner-found: "&cCannot find vault owner: &a%p" +plugin-not-found: "&cKeinen Converter für das Plugin gefunden" +conversion-complete: "&%converted Spieler zu PlayerVaults konvertiert" +conversion-background: "&fKonvertierung wurde im Hintergrund genauer gezeigt. Schaue in die Konsole für mehr Details." +vaults-locked: "&cTresore sind gerade wegen einer Konvertierung verschlossen. Versuche es in einem Moment nocheinmal!" +help: "/pv " +blocked-item: "&6%m &cist von Tresoren geblockt." +signs-disabled: "&cVault signs are currently disabled." +blocked-bad-item: "&cThis item is not allowed in a vault." +vault-does-not-exist: "&cThat vault does not exist!" +click-a-sign: "&fNow click a sign!" +not-a-sign: "&cYou must click a sign!" +set-sign-success: "&fYou have successfully set a PlayerVault access sign!" +open-with-sign: "&fOpening vault &a%v &fof &a%p" diff --git a/PlayerVaultsX/src/main/resources/lang/russian.yml b/PlayerVaultsX/src/main/resources/lang/russian.yml new file mode 100644 index 0000000..a22a3b5 --- /dev/null +++ b/PlayerVaultsX/src/main/resources/lang/russian.yml @@ -0,0 +1,39 @@ +# Используйте знак «&» для кода цвета в сообщениях. +# "%p" будет заменено ником игрока. +# "%v" будет заменено номером хранилища игрока. +# %price - цена. +# "%number" - номер хранилища. +# %converted - число сконвертированных хранилищ (где возможно преобразовать) +# "%m" будет заменено запрещённым материалом (где возможно заменить) +# Сделано с любовью <З :з + +title-name: "&4[&fPlayerVaultsX&4]:" +open-vault: "&fОткрываю хранилище &a%v" +open-other-vault: "&fОткрываю хранилище &a%v &fигрока &a%p" +delete-vault: "&fУдалено хранилище &a%v" +delete-other-vault: "&fУдалено хранилище &a%v &fигрока &a%p" +delete-other-vault-all: "&4Удалены все хранилищи игрока &a%p" +player-only: "&cИзвините, но это может использовать только игрок!" +must-be-number: "&cВы должны указать число в промежутке 1-99" +invalid-args: "&cНеверные аргументы!" +no-permissions: "&cУ Вас нет прав для этого!" +insufficient-funds: "&cУ Вас недостаточно денег!" +refund-amount: "&fВам вернули &a%price &fза удаление хранилища." +cost-to-create: "&fУ Вас взяли &c%price &fза создание хранилища." +cost-to-open: "&fУ Вас взяли &c%price &fза открытие хранилища." +vault-title: "&4Хранилище #%number" +existing-vaults: "&aУ игрока &f%p есть хранилище &a%v" +no-owner-found: "&cУ игрока &a%p &cнет хранилищ" +plugin-not-found: "&cКонвертер для плагина на найден" +conversion-complete: "&aСконвертировано %converted игроков к PlayerVaults" +conversion-background: "&fКонвертирование просходит в фоне. Следите за консолью для получения обновлений." +vaults-locked: "&cХранилища сейчас заблокированы, пока конвертируются. Пожалуйста, попробуйте чуть позже!" +help: "/pv <номер>" +blocked-item: "&cПредмет «&6%m&c» &cзаблокирован хранилищем." +signs-disabled: "&cVault signs are currently disabled." +blocked-bad-item: "&cThis item is not allowed in a vault." +vault-does-not-exist: "&cThat vault does not exist!" +click-a-sign: "&fNow click a sign!" +not-a-sign: "&cYou must click a sign!" +set-sign-success: "&fYou have successfully set a PlayerVault access sign!" +open-with-sign: "&fOpening vault &a%v &fof &a%p" diff --git a/PlayerVaultsX/src/main/resources/lang/turkish.yml b/PlayerVaultsX/src/main/resources/lang/turkish.yml new file mode 100644 index 0000000..c888e45 --- /dev/null +++ b/PlayerVaultsX/src/main/resources/lang/turkish.yml @@ -0,0 +1,39 @@ +# Renk kodları için & kullanın. +# %p oyuncu isminin ekleneceği yerdir. +# %v kasa numarasının ekleneceği yerdir. +# %price fiyatıdır. +# %number kasa numarasıdır. +# %converted dönüştürülen depo sayısı (uygulanabilir olduğunda) +# %m kara listeye alınmış malzeme ile değiştirilecek (uygulanabilir olduğunda) +# Aşkla yapıldı :) + +title-name: "&4[&fPlayerVaultsX&4]:" +open-vault: "&a%v. &fdepo açılıyor." +open-other-vault: "&a%p &foyuncusunun &a%v. &fdeposu açılıyor." +delete-vault: "&a%v. &fdepo silindi." +delete-other-vault: "&a%p &foyuncusunun &a%v. &fdeposu silindi." +delete-other-vault-all: "&4Deleted all vaults belonging to &a%p" +player-only: "&cÜzgünüz ama bu sadece bir oyuncu tarafından çalıştırılabilir!" +must-be-number: "&c1-99 arasında bir sayı belirtmeniz gerekiyor" +invalid-args: "&cGeçersiz argüman!" +no-permissions: "&cBunun için iznin yok!" +insufficient-funds: "&cBunun için yeterli paran yok!" +refund-amount: "&fDepo kapatıldığı için &a%price &fgeri ödeme aldın." +cost-to-create: "&fBu kasayı oluşturmak için &c%price &födedin." +cost-to-open: "&fDepo açılış ücreti olarak &c%price &födedin." +vault-title: "&4Depo #%number" +existing-vaults: "&f%p oyuncusunun depoları: &a%v" +no-owner-found: "&cCannot find vault owner: &a%p" +plugin-not-found: "&cBu eklenti için dönüştürücü bulunamadı" +conversion-complete: "&a%converted depo PlayerVaults'a dönüştürüldü" +conversion-background: "&fDönüşüm, arka plana aktarıldı. Detaylar için konsola bakın." +vaults-locked: "&cDönüşüm gerçekleştiğinde kasalar kilitlenir. Lütfen biraz sonra tekrar deneyin!" +help: "/pv " +blocked-item: "&6%m &cdepoda barındırılamaz!" +signs-disabled: "&cVault signs are currently disabled." +blocked-bad-item: "&cThis item is not allowed in a vault." +vault-does-not-exist: "&cThat vault does not exist!" +click-a-sign: "&fNow click a sign!" +not-a-sign: "&cYou must click a sign!" +set-sign-success: "&fYou have successfully set a PlayerVault access sign!" +open-with-sign: "&fOpening vault &a%v &fof &a%p" diff --git a/PlayerVaultsX/src/main/resources/plugin.yml b/PlayerVaultsX/src/main/resources/plugin.yml new file mode 100644 index 0000000..c0a2ab6 --- /dev/null +++ b/PlayerVaultsX/src/main/resources/plugin.yml @@ -0,0 +1,41 @@ +name: PlayerVaults +authors: [drtshock, kashike, CmdrKittens] +website: ${project.url} + +version: ${project.version} +main: com.drtshock.playervaults.PlayerVaults +depend: [CrankedUtils, StorageUtil] +softdepend: [Vault, Multiverse-Inventories] +api-version: 1.13 + +commands: + pv: + description: Open a vault. + aliases: [vault, chest, playervaults, vc] + pvdel: + description: Delete a vault. + aliases: [vaultdel] + pvsign: + description: Manage vault signs. + aliases: [vaultsign] + pvconvert: + description: Convert other plugins to PlayerVaultsX. + aliases: [vaultconvert] + pvreload: + description: Reload the configuration and language files. + permission: playervaults.admin + pvhelpme: + description: Pastes debug info to get better assistance. + permission: playervaults.admin + pvsearch: + description: Search trough pvs +permissions: + playervaults.admin: + description: Grants access to admin commands for vaults. + default: op + playervaults.bypassblockeditems: + description: Grants access to bypass blocked vault items. + default: op + playervaults.commands.use: + description: Use the command + default: true diff --git a/PluginViewer/pom.xml b/PluginViewer/pom.xml new file mode 100644 index 0000000..bda04a2 --- /dev/null +++ b/PluginViewer/pom.xml @@ -0,0 +1,26 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + PluginViewer + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + + \ No newline at end of file diff --git a/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/PluginViewerPlugin.java b/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/PluginViewerPlugin.java new file mode 100644 index 0000000..3862f68 --- /dev/null +++ b/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/PluginViewerPlugin.java @@ -0,0 +1,19 @@ +package net.crankedpvp.pluginviewer; + +import lombok.Getter; +import net.crankedpvp.pluginviewer.inventory.PluginViewerInventory; +import net.crankedpvp.pluginviewer.listeners.PluginsCommand; +import org.bukkit.plugin.java.JavaPlugin; + +public class PluginViewerPlugin extends JavaPlugin { + + @Getter + private PluginViewerInventory pluginViewerInventory; + + @Override + public void onEnable() { + this.pluginViewerInventory = new PluginViewerInventory(this); + this.getServer().getScheduler().runTaskLater(this, () -> this.getServer().getPluginManager().registerEvents(new PluginsCommand(this), this), 5 * 20L); + } + +} diff --git a/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/inventory/PluginViewerInventory.java b/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/inventory/PluginViewerInventory.java new file mode 100644 index 0000000..142e024 --- /dev/null +++ b/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/inventory/PluginViewerInventory.java @@ -0,0 +1,52 @@ +package net.crankedpvp.pluginviewer.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.SortUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.pluginviewer.PluginViewerPlugin; +import org.bukkit.Material; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; + +import java.util.*; + +public class PluginViewerInventory { + + private final PaginatedGui pluginViewerInventory; + + public PaginatedGui getUI() { + return this.pluginViewerInventory; + } + + public PluginViewerInventory(PluginViewerPlugin mainClass) { + this.pluginViewerInventory = GuiUtil.setupGui(new PaginatedGui(6, 28, "Plugins")); + this.pluginViewerInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + List plugins = Arrays.asList(mainClass.getServer().getPluginManager().getPlugins()); + plugins.sort(Comparator.comparing(Plugin::getName)); + for(Plugin plugin : plugins) { + boolean enabled = plugin.isEnabled(); + Material material = enabled? Material.SLIME_BALL : Material.FIREBALL; + String name = enabled ? "&a&l" + plugin.getName() : "&c&l" + plugin.getName(); + ItemBuilder itemBuilder = new ItemBuilder(material, name); + PluginDescriptionFile pluginDescriptionFile = plugin.getDescription(); + if(!pluginDescriptionFile.getAuthors().isEmpty()) itemBuilder.addLoreLine(enabled ? "&aAuthor(s): &f" + getStringFromList(pluginDescriptionFile.getAuthors()) : "&cAuthor(s): &f" + getStringFromList(pluginDescriptionFile.getAuthors())); + if(pluginDescriptionFile.getVersion() != null) itemBuilder.addLoreLine(enabled ? "&aVersion: &f" + pluginDescriptionFile.getVersion() : "&cVersion: &f" + pluginDescriptionFile.getVersion()); + if(pluginDescriptionFile.getWebsite() != null) itemBuilder.addLoreLine(enabled ? "&aWebsite: &f" + pluginDescriptionFile.getWebsite() : "&cWebsite: &f" + pluginDescriptionFile.getWebsite()); + if(pluginDescriptionFile.getDescription() != null) itemBuilder.addLoreLine(enabled ? "&aDescription: &f" + pluginDescriptionFile.getDescription() : "&cDescription: &f" + pluginDescriptionFile.getDescription()); + + this.pluginViewerInventory.addItem(new GuiItem(itemBuilder.colorize().build())); + } + } + + + private String getStringFromList(List list) { + StringBuilder stringBuilder = new StringBuilder(); + for(String s : list) { + stringBuilder.append(s).append(" "); + } + return stringBuilder.toString(); + } +} diff --git a/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/listeners/PluginsCommand.java b/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/listeners/PluginsCommand.java new file mode 100644 index 0000000..5989b3f --- /dev/null +++ b/PluginViewer/src/main/java/net/crankedpvp/pluginviewer/listeners/PluginsCommand.java @@ -0,0 +1,24 @@ +package net.crankedpvp.pluginviewer.listeners; + +import net.crankedpvp.pluginviewer.PluginViewerPlugin; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +public class PluginsCommand implements Listener { + + private final PluginViewerPlugin plugin; + + public PluginsCommand(PluginViewerPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void cmdPreProcessEvent(PlayerCommandPreprocessEvent event) { + if(event.getMessage().equals("/plugins")) { + event.setCancelled(true); + if(!event.getPlayer().hasPermission("*")) return; + if(event.getPlayer().isOp()) this.plugin.getPluginViewerInventory().getUI().open(event.getPlayer()); + } + } +} diff --git a/PluginViewer/src/main/resources/plugin.yml b/PluginViewer/src/main/resources/plugin.yml new file mode 100644 index 0000000..4bc164b --- /dev/null +++ b/PluginViewer/src/main/resources/plugin.yml @@ -0,0 +1,10 @@ +name: CrankedPluginViewer +main: net.crankedpvp.pluginviewer.PluginViewerPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - CrankedCore +softdepend: + - zzzzzz \ No newline at end of file diff --git a/PvPTop/pom.xml b/PvPTop/pom.xml new file mode 100644 index 0000000..ee5e1e6 --- /dev/null +++ b/PvPTop/pom.xml @@ -0,0 +1,56 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + PvPTop + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + com.massivecraft + Factions + + + net.crankedpvp + Spawners + + + net.crankedpvp + Enchants + + + net.crankedpvp + Armor + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + net.crankedpvp + FactionsKore + 0.1 + system + ${project.basedir}/../.lib/FactionsKore-1.3.431.jar + + + + \ No newline at end of file diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/PvPTopAPI.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/PvPTopAPI.java new file mode 100644 index 0000000..81bd452 --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/PvPTopAPI.java @@ -0,0 +1,27 @@ +package net.crankedpvp.pvptop; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +public class PvPTopAPI { + + public static final String PREFIX = "&b&lPoints &8" + Arrow.arrow() + " &7"; + + public static FactionData getFactionData(Faction faction) { + return PvPTopPlugin.getInstance().getPvpTopManager().getOrCreate(faction); + } + + public static FactionData getFactionData(String factionId) { + return PvPTopPlugin.getInstance().getPvpTopManager().getOrCreate(Factions.getInstance().getFactionById(factionId)); + } + + public static FactionData getFactionData(Player player) { + return PvPTopPlugin.getInstance().getPvpTopManager().getOrCreate(FactionUtils.getFaction(player)); + } +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/PvPTopPlugin.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/PvPTopPlugin.java new file mode 100644 index 0000000..7322c7f --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/PvPTopPlugin.java @@ -0,0 +1,92 @@ +package net.crankedpvp.pvptop; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedenchants.struct.enchantstruct.Enchantment; +import net.crankedpvp.crankedenchants.struct.enums.EnchantTier; +import net.crankedpvp.pvptop.commands.PvPTopCommand; +import net.crankedpvp.pvptop.data.FactionData; +import net.crankedpvp.pvptop.data.PvPTopManager; +import net.crankedpvp.pvptop.inventory.ObtainPointsMethodsInventory; +import net.crankedpvp.pvptop.inventory.PvPTopInventory; +import net.crankedpvp.pvptop.listeners.FactionDisbandCheck; +import net.crankedpvp.pvptop.listeners.KothCaptureListener; +import net.crankedpvp.pvptop.listeners.PlayerDeathListener; +import net.crankedpvp.pvptop.tasks.UpdateLeaderboardTask; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Locale; +import java.util.stream.Collectors; + +public class PvPTopPlugin extends JavaPlugin { + + @Getter + private static PvPTopPlugin instance; + + @Getter + private PvPTopManager pvpTopManager; + + @Getter + private UpdateLeaderboardTask updateLeaderboardTask; + + @Getter + private CommandManager commandManager; + + @Getter + private PvPTopInventory pvPTopInventory; + @Getter + private ObtainPointsMethodsInventory obtainPointsMethodsInventory; + + @Override + public void onEnable() { + instance = this; + + this.pvpTopManager = new PvPTopManager(this); + this.pvpTopManager.loadAll(); + + this.commandManager = new CommandManager(this); + this.registerCommandParameters(); + this.registerCommandCompletion(); + this.commandManager.register(new PvPTopCommand(this)); + + this.pvPTopInventory = new PvPTopInventory(this, true); + this.obtainPointsMethodsInventory = new ObtainPointsMethodsInventory(); + + this.registerListeners(); + + this.updateLeaderboardTask = new UpdateLeaderboardTask(this); + this.updateLeaderboardTask.runTaskTimer(this, 10 * 20L, 30 * 20L); + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(FactionData.Points.class, argument -> { + FactionData.Points points = FactionData.Points.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(points, argument); + }); + } + + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#factions", input -> Factions.getInstance().getAllFactions().stream().map(Faction::getTag).collect(Collectors.toList())); + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new PlayerDeathListener(this), this); + pluginManager.registerEvents(new FactionDisbandCheck(), this); + pluginManager.registerEvents(new KothCaptureListener(this), this); + } + + @Override + public void onDisable() { + this.pvpTopManager.saveAll(); + } + + public void updateInventory() { + this.pvPTopInventory = new PvPTopInventory(this, false); + } +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/commands/PvPTopCommand.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/commands/PvPTopCommand.java new file mode 100644 index 0000000..702a986 --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/commands/PvPTopCommand.java @@ -0,0 +1,58 @@ +package net.crankedpvp.pvptop.commands; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.pvptop.PvPTopPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("pvptop") +public class PvPTopCommand extends CommandBase { + + private final PvPTopPlugin plugin; + public PvPTopCommand(PvPTopPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getPvPTopInventory().getUI().open(player); + player.updateInventory(); + } + + @SubCommand("force") + @Alias("update") + @Permission("pvptop.admin") + public void forceUpdateCommand(final CommandSender commandSender) { + this.plugin.getUpdateLeaderboardTask().update(); + } + + @SubCommand("add") + @Permission("pvptop.admin") + public void addPointsCommand(final CommandSender commandSender, @Completion("#factions") String factionTag, @Completion("#enum") final FactionData.Points points) { + Faction faction = Factions.getInstance().getByTag(factionTag); + if(faction == null) { + commandSender.sendMessage(CC.translate("&cThat is not a faction g")); + return; + } + this.plugin.getPvpTopManager().getOrCreate(faction).addPoint(points); + commandSender.sendMessage(CC.translate("&aSuccessfully added " + points.getPoints() + " points to " + factionTag)); + } + + @SubCommand("remove") + @Permission("pvptop.admin") + public void removePointsCommand(final CommandSender commandSender, @Completion("#factions") String factionTag, @Completion("#enum") final FactionData.Points points) { + Faction faction = Factions.getInstance().getByTag(factionTag); + if(faction == null) { + commandSender.sendMessage(CC.translate("&cThat is not a faction g")); + return; + } + this.plugin.getPvpTopManager().getOrCreate(faction).removePoint(points); + commandSender.sendMessage(CC.translate("&aSuccessfully removed " + points.getPoints() + " points from " + factionTag)); + } +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/data/FactionData.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/data/FactionData.java new file mode 100644 index 0000000..c30175e --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/data/FactionData.java @@ -0,0 +1,242 @@ +package net.crankedpvp.pvptop.data; + +import com.massivecraft.factions.Faction; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.pvptop.PvPTopAPI; +import net.crankedpvp.pvptop.PvPTopPlugin; +import net.crankedpvp.storageutils.struct.NewKeyToSave; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +@Getter @Setter +public class FactionData implements NewKeyToSave { + + private String factionId; + private Map points; + + public void addPoint(Points points) { + if(this.points.containsKey(points)) { + int amount = this.points.get(points); + amount += 1; + this.points.put(points, amount); + return; + } + this.points.put(points, 1); + } + + public void removePoint(Points points) { + if(this.points.containsKey(points)) { + int amount = this.points.get(points); + amount -= 1; + this.points.put(points, amount); + return; + } + this.points.put(points, 0); + } + + public int calculateAllPoints() { + int amount = 0; + for(Points points : this.points.keySet()) { + if(points == Points.DEATH) { + amount -= this.points.get(points); + continue; + } + amount += this.points.get(points) * points.getPoints(); + } + return amount; + } + + public FactionData(String factionId) { + this.factionId = factionId; + this.points = new HashMap<>(); + } + + public int getPointsFor(Points points) { + return this.points.getOrDefault(points, 0); + } + + public int getKills() { + return this.points.getOrDefault(Points.KILL, 0); + } + + public int getDeaths() { + return this.points.getOrDefault(Points.DEATH, 0); + } + + public int getStrongholdControlled() { + return this.points.getOrDefault(Points.STRONHOLD_CONTROL, 0); + } + + public int getCitadelCaptured() { + return this.points.getOrDefault(Points.CITADEL_CAPTURE, 0); + } + + public int getDeadmansChestCaptures() { + return this.points.getOrDefault(Points.DEADMANS_CHEST, 0); + } + + public int getWarpKothCaptured() { + return this.points.getOrDefault(Points.WARP_KOTH_CAPTURE, 0); + } + + public int getKothCaptured() { + return this.points.getOrDefault(Points.KOTH_CAPTURE, 0); + } + + public int getCerberusKills() { + return this.points.getOrDefault(Points.CERBERUS_KILLED, 0); + } + + @Override + public String getKey() { + return this.factionId; + } + + @Override + public void setKey(String string) { + this.factionId = string; + } + + public enum Points { + KOTH_CAPTURE(50, "&d&lKoth Capture"), + WARP_KOTH_CAPTURE(75, "&5&lWarp Koth Capture"), + KILL(1, "&a&lPlayer Kill"), + DEATH(1, "&c&lMember Death"), + STRONHOLD_CONTROL(15, "&4&lStronghold Control"), + DEADMANS_CHEST(100, "&d&lDead Mans Chest Capture"), + CERBERUS_KILLED(150, "&6&lCerberus Slain"), + CITADEL_CAPTURE(1000, "&e&lCitadel Capture"), + ; + + @Getter + private final int points; + @Getter + private final String due; + Points(int points, String due) { + this.points = points; + this.due = due; + } + + public void add(Faction faction) { + FactionData factionData = PvPTopPlugin.getInstance().getPvpTopManager().getOrCreate(faction); + String plural = this.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has gained &a" + this.getPoints() + " &7faction " + plural + " due to " + this.getDue())); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + factionData.addPoint(this); + } + + public void remove(Faction faction) { + FactionData factionData = PvPTopPlugin.getInstance().getPvpTopManager().getOrCreate(faction); + String plural = this.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has lost &c" + this.getPoints() + " &7faction " + plural + " due to " + this.getDue())); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + factionData.removePoint(this); + } + } + + + /* + public final static transient int KOTH_CAPTURE_POINTS = 50; + public final static transient int WARP_KOTH_CAPTURE_POINTS = 75; + public final static transient int KILL_POINTS = 1; + public final static transient int DEATH_POINTS = 1; + public final static transient int STRONGHOLD_HOLD_POINTS = 15; + public final static transient int DEADMANS_CHEST_POINTS = 100; + public final static transient int CITADEL_CAPTURE_POINTS = 1000; + public final static transient int CERBERUS_KILLED = 150; + + + */ + + /* + public void addCerberusKilled() { + Faction faction = Factions.getInstance().getFactionById(this.factionId); + String plural = Points.CERBERUS_KILLED.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has gained &a" + Points.CERBERUS_KILLED.getPoints() + " &7faction " + plural + " due to " + "&9&lCerberus Killed")); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + this.cerberusKilled += 1; + } + + public void addKothCapture() { + Faction faction = Factions.getInstance().getFactionById(this.factionId); + String plural = Points.KOTH_CAPTURE.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has gained &a" + Points.KOTH_CAPTURE.getPoints() + " &7faction " + plural + " due to " + "&d&lKoth Capture")); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + this.kothsCaptured += 1; + } + + public void addWarpKothCapture() { + Faction faction = Factions.getInstance().getFactionById(this.factionId); + String plural = Points.WARP_KOTH_CAPTURE.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has gained &a" + Points.WARP_KOTH_CAPTURE.getPoints() + " &7faction " + plural + " due to " + "&6&lWarp Koth Capture")); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + this.warpKothsCaptured += 1; + } + + public void addCitadelCapture() { + Faction faction = Factions.getInstance().getFactionById(this.factionId); + String plural = Points.CITADEL_CAPTURE.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has gained &a" + Points.CITADEL_CAPTURE.getPoints() + " &7faction " + plural + " due to " + "&e&lCitadel Capture")); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + this.citadelsCaptured += 1; + } + + public void addStrongholdHold() { + Faction faction = Factions.getInstance().getFactionById(this.factionId); + String plural = Points.STRONHOLD_CONTROL.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has gained &a" + Points.STRONHOLD_CONTROL.getPoints() + " &7faction " + plural + " due to " + "&4&lStronghold Hold")); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + this.strongholdHeld += 1; + } + + public void addPlayerKill() { + Faction faction = Factions.getInstance().getFactionById(this.factionId); + String plural = Points.KILL.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has gained &a" + Points.KILL.getPoints() + " &7faction " + plural + " due to " + "&a&lEnemy Kill")); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + this.kills += 1; + } + + public void addPlayerDeath() { + Faction faction = Factions.getInstance().getFactionById(this.factionId); + String plural = Points.DEATH.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has lost &c" + Points.DEATH.getPoints() + " &7faction " + plural + " due to " + "&c&lMember Death")); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LAVA_POP, 1.0f, 1.0f); + } + this.deaths += 1; + } + + public void addDeadMansChestCapture() { + Faction faction = Factions.getInstance().getFactionById(this.factionId); + String plural = Points.DEADMANS_CHEST.getPoints() > 1 ? "points" : "point"; + for(Player onlinePlayer : faction.getOnlinePlayers()) { + onlinePlayer.sendMessage(CC.translate(PvPTopAPI.PREFIX + "Your faction has gained &a" + Points.DEADMANS_CHEST.getPoints() + " &7faction " + plural + " due to " + "&d&lDead Mans Chest Capture")); + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f); + } + this.deadmansChestCaptured += 1; + } + + */ +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/data/PvPTopManager.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/data/PvPTopManager.java new file mode 100644 index 0000000..b96fd42 --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/data/PvPTopManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.pvptop.data; + +import com.massivecraft.factions.Faction; +import net.crankedpvp.pvptop.PvPTopPlugin; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.struct.NewSaveLoadManager; + +public class PvPTopManager extends NewSaveLoadManager { + + public PvPTopManager(PvPTopPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "data", FactionData.class); + } + + @Override + public String serialize(String string) { + return string; + } + + @Override + public String deserialize(String string) { + return string; + } + + public FactionData getOrCreate(Faction faction) { + + if(!faction.isNormal()) return null; + + if(super.containsKey(faction.getId())) { + return super.getFromCache(faction.getId()); + } + + FactionData factionData = new FactionData(faction.getId()); + super.addToCache(factionData); + return factionData; + } + + +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/events/UpdateFactionPointsEvent.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/events/UpdateFactionPointsEvent.java new file mode 100644 index 0000000..6aecc5a --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/events/UpdateFactionPointsEvent.java @@ -0,0 +1,49 @@ +package net.crankedpvp.pvptop.events; + +import com.massivecraft.factions.Faction; +import lombok.Getter; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@Getter +public class UpdateFactionPointsEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean canceled = false; + + @Getter + private final Faction faction; + + @Getter + private final long oldPoints; + + @Getter + private final long newPoints; + + public UpdateFactionPointsEvent(Faction faction, long oldPoints, long newPoints) { + this.oldPoints = oldPoints; + this.newPoints = newPoints; + this.faction = faction; + } + + @Override + public boolean isCancelled() { + return this.canceled; + } + + @Override + public void setCancelled(boolean b) { + this.canceled = b; + } + + @Override + public HandlerList getHandlers() { + return UpdateFactionPointsEvent.handlers; + } + + public static HandlerList getHandlerList() { + return UpdateFactionPointsEvent.handlers; + } + +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/FactionPointsBreakdownInventory.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/FactionPointsBreakdownInventory.java new file mode 100644 index 0000000..ff8af34 --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/FactionPointsBreakdownInventory.java @@ -0,0 +1,133 @@ +package net.crankedpvp.pvptop.inventory; + +import com.massivecraft.factions.Faction; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.pvptop.PvPTopPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; + +public class FactionPointsBreakdownInventory { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final Faction faction; + private final FactionData factionData; + + + private final Gui pointsBreakdownInventory; + + public Gui getUI() { + return this.pointsBreakdownInventory; + } + + public FactionPointsBreakdownInventory(Faction faction) { + this.faction = faction; + this.factionData = PvPTopPlugin.getInstance().getPvpTopManager().getOrCreate(faction); + this.pointsBreakdownInventory = new Gui(4, faction.getTag() + " Points Breakdown"); + this.pointsBreakdownInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.pointsBreakdownInventory.getFiller().fillBorder(GuiUtil.createFillerGuiItem()); + + ItemStack info = new ItemBuilder(Material.BOOK, "&f" + faction.getTag()) + .setLore( + "", + "&b&lInformation", + " &f• Leader: &3" + faction.getLeader().getName(), + "", + "&b&lStatistics", + " &f• Faction Points: &3" + moneyFormat.format(factionData.calculateAllPoints()) + ) + .colorize().build(); + + this.pointsBreakdownInventory.setItem(1, 5, new GuiItem(info)); + + this.pointsBreakdownInventory.addItem(new GuiItem(this.buildKillsItemStack())); + this.pointsBreakdownInventory.addItem(new GuiItem(this.buildDeathsItemStack())); + this.pointsBreakdownInventory.addItem(new GuiItem(this.buildDeadmansChestCapturedItemStack())); + this.pointsBreakdownInventory.addItem(new GuiItem(this.buildKothsCapturedItemStack())); + this.pointsBreakdownInventory.addItem(new GuiItem(this.buildWarpKothsCapturedItemStack())); + this.pointsBreakdownInventory.addItem(new GuiItem(this.buildCitadelsCapturedItemStack())); + this.pointsBreakdownInventory.addItem(new GuiItem(this.buildCerberusKillItemStack())); + this.pointsBreakdownInventory.addItem(new GuiItem(this.buildStrongholdControlledItemStack())); + } + + + private ItemStack buildKillsItemStack() { + return new ItemBuilder(Material.GOLD_SWORD, "&aPlayer Kills", + "&f+" + FactionData.Points.KILL.getPoints() + " &bFaction Point", + "", + " &f• Total: &e" + this.factionData.getKills(), + " &f• Points Gained: &8(&a+" + (this.factionData.getKills() * FactionData.Points.KILL.getPoints()) + "&8)" + ).colorize().build(); + } + + private ItemStack buildKothsCapturedItemStack() { + return new ItemBuilder(Material.WOOL, 1, DyeColor.RED.getWoolData(), "&aKOTH Capture", + "&f+" + FactionData.Points.KOTH_CAPTURE.getPoints() + " &bFaction Points", + "", + " &f• Total: &e" + this.factionData.getKothCaptured(), + " &f• Points Gained: &8(&a+" + (this.factionData.getKothCaptured() * FactionData.Points.KOTH_CAPTURE.getPoints()) + "&8)" + ).colorize().build(); + } + + private ItemStack buildWarpKothsCapturedItemStack() { + return new ItemBuilder(Material.ENDER_PORTAL_FRAME, "&aWarp KOTH Capture", + "&f+" + FactionData.Points.WARP_KOTH_CAPTURE.getPoints() + " &bFaction Points", + "", + " &f• Total: &e" + this.factionData.getWarpKothCaptured(), + " &f• Points Gained: &8(&a+" + (this.factionData.getWarpKothCaptured() * FactionData.Points.WARP_KOTH_CAPTURE.getPoints()) + "&8)" + ).colorize().build(); + } + + private ItemStack buildCitadelsCapturedItemStack() { + return new ItemBuilder(Material.BEACON, "&aCitadel Capture", + "&f+" + FactionData.Points.CITADEL_CAPTURE.getPoints() + " &bFaction Points", + "", + " &f• Total: &e" + this.factionData.getCitadelCaptured(), + " &f• Points Gained: &8(&a+" + (this.factionData.getCitadelCaptured() * FactionData.Points.CITADEL_CAPTURE.getPoints()) + "&8)" + ).colorize().build(); + } + + private ItemStack buildDeadmansChestCapturedItemStack() { + return new ItemBuilder(Material.ENDER_CHEST, "&aDead Mans Chest Capture", + "&f+" + FactionData.Points.DEADMANS_CHEST.getPoints() + " &bFaction Points", + "", + " &f• Total: &e" + this.factionData.getDeadmansChestCaptures(), + " &f• Points Gained: &8(&a+" + (this.factionData.getDeadmansChestCaptures() * FactionData.Points.DEADMANS_CHEST.getPoints()) + "&8)" + ).colorize().build(); + } + + private ItemStack buildDeathsItemStack() { + return new ItemBuilder(Material.INK_SACK, 1, DyeColor.RED.getDyeData(), "&cPlayer Deaths", + "&f-" + FactionData.Points.DEATH.getPoints() + " &bFaction Point", + "", + " &f• Total: &e" + this.factionData.getDeaths(), + " &f• Points Gained: &8(&c-" + (this.factionData.getDeaths() * FactionData.Points.DEATH.getPoints()) + "&8)" + ).colorize().build(); + } + + private ItemStack buildStrongholdControlledItemStack() { + return new ItemBuilder(Material.BLAZE_POWDER, "&aStronghold Controlled &7(30 Minutes)", + "&f+" + FactionData.Points.STRONHOLD_CONTROL.getPoints() + " &bFaction Points", + "", + " &f• Total: &e" + this.factionData.getStrongholdControlled(), + " &f• Points Gained: &8(&a+" + (this.factionData.getStrongholdControlled() * FactionData.Points.STRONHOLD_CONTROL.getPoints()) + "&8)" + ).colorize().build(); + } + + private ItemStack buildCerberusKillItemStack() { + return new ItemBuilder(Material.MONSTER_EGG, "&aCerberus Kills", + "&f+" + FactionData.Points.CERBERUS_KILLED.getPoints() + " &bFaction Points", + "", + " &f• Total: &e" + this.factionData.getCerberusKills(), + " &f• Points Gained: &8(&a+" + (this.factionData.getCerberusKills() * FactionData.Points.CERBERUS_KILLED.getPoints()) + "&8)" + ).colorize().build(); + } +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/ObtainPointsMethodsInventory.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/ObtainPointsMethodsInventory.java new file mode 100644 index 0000000..c87d96e --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/ObtainPointsMethodsInventory.java @@ -0,0 +1,87 @@ +package net.crankedpvp.pvptop.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; + +public class ObtainPointsMethodsInventory { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final Gui obtainPointsMethodInventory; + + public Gui getUI() { + return this.obtainPointsMethodInventory; + } + + public ObtainPointsMethodsInventory() { + this.obtainPointsMethodInventory = new Gui(4, "Obtain Points Methods"); + this.obtainPointsMethodInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.obtainPointsMethodInventory.getFiller().fillBorder(GuiUtil.createFillerGuiItem()); + + this.obtainPointsMethodInventory.addItem(new GuiItem(this.buildKillsItemStack())); + this.obtainPointsMethodInventory.addItem(new GuiItem(this.buildDeathsItemStack())); + this.obtainPointsMethodInventory.addItem(new GuiItem(this.buildDeadmansChestCapturedItemStack())); + this.obtainPointsMethodInventory.addItem(new GuiItem(this.buildKothsCapturedItemStack())); + this.obtainPointsMethodInventory.addItem(new GuiItem(this.buildWarpKothsCapturedItemStack())); + this.obtainPointsMethodInventory.addItem(new GuiItem(this.buildCitadelsCapturedItemStack())); + this.obtainPointsMethodInventory.addItem(new GuiItem(this.buildCerberusKillItemStack())); + this.obtainPointsMethodInventory.addItem(new GuiItem(this.buildStrongholdControlledItemStack())); + } + + + private ItemStack buildKillsItemStack() { + return new ItemBuilder(Material.GOLD_SWORD, "&aPlayer Kills", + "&f+" + FactionData.Points.KILL.getPoints() + " &bFaction Point" + ).colorize().build(); + } + + private ItemStack buildKothsCapturedItemStack() { + return new ItemBuilder(Material.WOOL, 1, DyeColor.RED.getWoolData(), "&aKOTH Capture", + "&f+" + FactionData.Points.KOTH_CAPTURE.getPoints() + " &bFaction Points" + ).colorize().build(); + } + + private ItemStack buildDeadmansChestCapturedItemStack() { + return new ItemBuilder(Material.ENDER_CHEST, "&aDead Mans Chest Capture", + "&f+" + FactionData.Points.DEADMANS_CHEST.getPoints() + " &bFaction Points").colorize().build(); + } + + private ItemStack buildDeathsItemStack() { + return new ItemBuilder(Material.INK_SACK, 1, DyeColor.RED.getDyeData(), "&cPlayer Deaths", + "&f-" + FactionData.Points.DEATH.getPoints() + " &bFaction Point" + ).colorize().build(); + } + + private ItemStack buildWarpKothsCapturedItemStack() { + return new ItemBuilder(Material.ENDER_PORTAL_FRAME, "&aWarp KOTH Capture", + "&f+" + FactionData.Points.WARP_KOTH_CAPTURE.getPoints() + " &bFaction Points" + ).colorize().build(); + } + + private ItemStack buildCitadelsCapturedItemStack() { + return new ItemBuilder(Material.BEACON, "&aCitadel Capture", + "&f+" + FactionData.Points.CITADEL_CAPTURE.getPoints() + " &bFaction Points" + ).colorize().build(); + } + + private ItemStack buildStrongholdControlledItemStack() { + return new ItemBuilder(Material.BLAZE_POWDER, "&aStronghold Controlled &7(30 Minutes)", + "&f+" + FactionData.Points.STRONHOLD_CONTROL.getPoints() + " &bFaction Points" + ).colorize().build(); + } + + private ItemStack buildCerberusKillItemStack() { + return new ItemBuilder(Material.MONSTER_EGG, "&aCerberus Kills", + "&f+" + FactionData.Points.CERBERUS_KILLED.getPoints() + " &bFaction Points" + ).colorize().build(); + } +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/PvPTopInventory.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/PvPTopInventory.java new file mode 100644 index 0000000..4a286c9 --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/inventory/PvPTopInventory.java @@ -0,0 +1,128 @@ +package net.crankedpvp.pvptop.inventory; + +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import de.tr7zw.nbtapi.NBTItem; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.GuiUtil; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.pvptop.PvPTopPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import net.crankedpvp.spawners.SpawnerPlugin; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.text.DecimalFormat; + +public class PvPTopInventory { + + private static final DecimalFormat moneyFormat = new DecimalFormat("#,###"); + + private final Gui pvpTopInventory; + + public Gui getUI() { + return this.pvpTopInventory; + } + + public PvPTopInventory(PvPTopPlugin plugin, boolean firstLoad) { + this.pvpTopInventory = new Gui(6, "PvP Top"); + this.pvpTopInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + this.pvpTopInventory.getFiller().fillBorder(GuiUtil.createFillerGuiItem()); + this.pvpTopInventory.getFiller().fillBetweenPoints(2, 2, 2, 8, GuiUtil.createFillerGuiItem()); + this.pvpTopInventory.getFiller().fillBetweenPoints(5, 2, 5, 8, GuiUtil.createFillerGuiItem()); + + + ItemStack info = new ItemBuilder(Material.BOOK, "&b&lTop Point Factions", + "&fThe top factions amongst Cranked are", + "&flisted below, sorted by &bFaction Points" + ).colorize().build(); + + ItemStack facPoints = new ItemBuilder(Material.SIGN, "&3&lObtaining Points", + "&fThere are numerous ways to obtain", + "&ffaction points, and you need these", + "&fpoints to show up on the leaderboard", + "&fand to compete for the /pvptop payouts.", + "", + "&3Obtaining Point Methods:", + " &f• Player Kills", + " &f• Capturing KOTHs", + " &f• Holding control of /stronghold", + " &f• Capturing Dead Mans Chests", + " &f• Capturing Citadel", + "", + "&7&oClick to view all methods of obtaining points" + ).colorize().build(); + + ItemStack questionMark = new ItemBuilder(Material.SKULL_ITEM, "&f&l???", "&7Click me to make player skulls visible" + ).colorize().build(); + + this.pvpTopInventory.setItem(1, 5, new GuiItem(info)); + this.pvpTopInventory.setItem(6, 4, new GuiItem(facPoints, event -> { + event.getWhoClicked().closeInventory(); + PvPTopPlugin.getInstance().getObtainPointsMethodsInventory().getUI().open(event.getWhoClicked()); + })); + this.pvpTopInventory.setItem(6, 6, new GuiItem(questionMark)); + + if(firstLoad) return; + int count = 1; + for(FactionData value : plugin.getUpdateLeaderboardTask().getSortedFactionData()) { + ItemStack itemToAddToInventory = this.buildItemOfFactionData(value, count); + if(itemToAddToInventory == null) continue; + this.pvpTopInventory.addItem(new GuiItem(itemToAddToInventory, event -> { + event.getWhoClicked().closeInventory(); + FactionPointsBreakdownInventory factionPointsBreakdownInventory = new FactionPointsBreakdownInventory(Factions.getInstance().getFactionById(value.getFactionId())); + factionPointsBreakdownInventory.getUI().open(event.getWhoClicked()); + })); + count++; + if(count == 15) return; + } + } + + private ItemStack buildItemOfFactionData(FactionData value, int count) { + Faction faction = Factions.getInstance().getFactionById(value.getKey()); + if(faction == null) { + PvPTopPlugin.getInstance().getPvpTopManager().removeFromCache(value); + PvPTopPlugin.getInstance().getUpdateLeaderboardTask().update(); + return null; + } + net.crankedpvp.spawners.data.ftop.FactionData factionData = SpawnerPlugin.getInstance().getFactionsTopManager().getFactionData(faction); + if(factionData == null) { + ItemBuilder itemBuilder = new ItemBuilder(getSkull(faction.getLeader().getName())) + .setName("&3" + faction.getTag() + " &7(Points #" + count + ")") + .setLore( + "", + "&b&lInformation", + " &f• Leader: &3" + faction.getLeader().getName(), + "", + "&b&lStatistics", + " &f• Faction Points: &3" + moneyFormat.format(value.calculateAllPoints()) + ); + return itemBuilder.colorize().build(); + } + ItemBuilder itemBuilder = new ItemBuilder(getSkull(faction.getLeader().getName())) + .setName("&3" + faction.getTag() + " &7(Points #" + count + ")") + .setLore( + "", + "&b&lInformation", + " &f• Leader: &3" + faction.getLeader().getName(), + " &f• Richest Member: &3" + factionData.getRichestPlayer(), + "", + "&b&lStatistics", + " &f• Faction Points: &3" + moneyFormat.format(value.calculateAllPoints()), + " &f• Spawner Value: &3$" + moneyFormat.format(factionData.getSpawnerValue()), + " &f• Spawner Count: &3" + moneyFormat.format(factionData.getSpawnerCount()) + ); + + return itemBuilder.colorize().build(); + } + + private ItemStack getSkull(String playerName) { + ItemStack playerSkull = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); + NBTItem nbtItem = new NBTItem(playerSkull); + nbtItem.setString("SkullOwner", playerName); + return nbtItem.getItem(); + } + +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/FactionDisbandCheck.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/FactionDisbandCheck.java new file mode 100644 index 0000000..9781fdb --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/FactionDisbandCheck.java @@ -0,0 +1,15 @@ +package net.crankedpvp.pvptop.listeners; + +import com.massivecraft.factions.event.FactionDisbandEvent; +import net.crankedpvp.pvptop.PvPTopPlugin; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class FactionDisbandCheck implements Listener { + + @EventHandler + public void facDisband(FactionDisbandEvent event) { + PvPTopPlugin.getInstance().getPvpTopManager().removeFromCache(event.getFaction().getId()); + } + +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/KothCaptureListener.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/KothCaptureListener.java new file mode 100644 index 0000000..1814f4b --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/KothCaptureListener.java @@ -0,0 +1,35 @@ +package net.crankedpvp.pvptop.listeners; + +import com.golfing8.kore.event.KothCaptureEvent; +import com.massivecraft.factions.Faction; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.pvptop.PvPTopPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class KothCaptureListener implements Listener { + + private final PvPTopPlugin plugin; + public KothCaptureListener(PvPTopPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onKothCapture(KothCaptureEvent event) { + if(event.getPlayerCapper() == null) return; + + Faction faction = FactionUtils.getFaction(event.getPlayerCapper()); + FactionData factionData = this.plugin.getPvpTopManager().getOrCreate(faction); + if(factionData == null) return; + if(event.getKoth().getName().equalsIgnoreCase("Citadel")) { + factionData.addPoint(FactionData.Points.CITADEL_CAPTURE); + return; + } + if(event.getKoth().getName().equalsIgnoreCase("End")) { + factionData.addPoint(FactionData.Points.WARP_KOTH_CAPTURE); + return; + } + factionData.addPoint(FactionData.Points.KOTH_CAPTURE); + } +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/PlayerDeathListener.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/PlayerDeathListener.java new file mode 100644 index 0000000..3d03937 --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/listeners/PlayerDeathListener.java @@ -0,0 +1,39 @@ +package net.crankedpvp.pvptop.listeners; + +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Factions; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedutils.struct.factions.CrankedFactionHandler; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.pvptop.PvPTopAPI; +import net.crankedpvp.pvptop.PvPTopPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; + +public class PlayerDeathListener implements Listener { + + private final PvPTopPlugin plugin; + public PlayerDeathListener(PvPTopPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void handlePlayerDeath(PlayerDeathEvent event) { + if(event.getEntity() == null) return; + if(event.getEntity().getKiller() == null) return; + + Player attacker = event.getEntity().getKiller(); + Player victim = event.getEntity(); + + if(FPlayers.getInstance().getByPlayer(victim).hasFaction()) PvPTopAPI.getFactionData(victim).addPoint(FactionData.Points.DEATH); + if(FPlayers.getInstance().getByPlayer(attacker).hasFaction()) { + if (CrankedArmorAPI.getCurrentArmorSet(victim) == null) return; + if (CrankedEnchantsAPI.getEnchantments(victim).size() < 16) return; + PvPTopAPI.getFactionData(attacker).addPoint(FactionData.Points.KILL); + } + } +} diff --git a/PvPTop/src/main/java/net/crankedpvp/pvptop/tasks/UpdateLeaderboardTask.java b/PvPTop/src/main/java/net/crankedpvp/pvptop/tasks/UpdateLeaderboardTask.java new file mode 100644 index 0000000..cbd98da --- /dev/null +++ b/PvPTop/src/main/java/net/crankedpvp/pvptop/tasks/UpdateLeaderboardTask.java @@ -0,0 +1,35 @@ +package net.crankedpvp.pvptop.tasks; + +import lombok.Getter; +import net.crankedpvp.pvptop.PvPTopPlugin; +import net.crankedpvp.pvptop.data.FactionData; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class UpdateLeaderboardTask extends BukkitRunnable { + + @Getter + private List sortedFactionData; + + private final PvPTopPlugin plugin; + public UpdateLeaderboardTask(PvPTopPlugin plugin) { + this.plugin = plugin; + this.sortedFactionData = new ArrayList<>(); + } + + @Override + public void run() { + this.update(); + } + + public void update() { + this.sortedFactionData = new ArrayList<>(this.plugin.getPvpTopManager().getCacheValues()); + this.sortedFactionData.sort(Comparator.comparingInt(FactionData::calculateAllPoints)); + Collections.reverse(this.sortedFactionData); + PvPTopPlugin.getInstance().updateInventory(); + } +} diff --git a/PvPTop/src/main/resources/plugin.yml b/PvPTop/src/main/resources/plugin.yml new file mode 100644 index 0000000..3d79888 --- /dev/null +++ b/PvPTop/src/main/resources/plugin.yml @@ -0,0 +1,10 @@ +name: CrankedPvPTop +main: net.crankedpvp.pvptop.PvPTopPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - Factions + - StorageUtil + - CrankedSpawners \ No newline at end of file diff --git a/RPS/pom.xml b/RPS/pom.xml new file mode 100644 index 0000000..88c8f7e --- /dev/null +++ b/RPS/pom.xml @@ -0,0 +1,30 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + RPS + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + com.massivecraft + Factions + + + + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/RPSPlugin.java b/RPS/src/main/java/net/crankedpvp/rps/RPSPlugin.java new file mode 100644 index 0000000..784b019 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/RPSPlugin.java @@ -0,0 +1,134 @@ +// =============================================== // +// Recompile disabled. Please run Recaf with a JDK // +// =============================================== // + +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.crankedpvp.rps; + +import net.crankedpvp.rps.commands.RPSCommand; +import net.crankedpvp.rps.listeners.ChooseEvents; +import net.crankedpvp.rps.listeners.InventoryCloseListener; +import net.crankedpvp.rps.listeners.RPSEvents; +import net.crankedpvp.rps.listeners.TopGuiListener; +import net.crankedpvp.rps.players.PlayerData; +import net.crankedpvp.rps.players.PlayerDataManager; +import net.crankedpvp.rps.players.wages.InventoryEnum; +import net.crankedpvp.rps.players.wages.RPS; +import net.crankedpvp.rps.players.wages.WageManager; +import net.crankedpvp.rps.rpsutilities.RpsUtilities; +import net.crankedpvp.rps.utilities.CFG; +import net.crankedpvp.rps.utilities.MessagesX; +import net.crankedpvp.rps.utilities.VaultAPI; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class RPSPlugin extends JavaPlugin { + private final WageManager wageManager = new WageManager(this); + private final PlayerDataManager playerDataManager = new PlayerDataManager(this); + private final RpsUtilities rpsUtilities = new RpsUtilities(this); + private final CFG options = new CFG(this, "options", true); + private final CFG rps = new CFG(this, "rps", true); + private final CFG playerBase = new CFG(this, "playerbase", true); + private final CFG messages = new CFG(this, "messages", false); + private final VaultAPI vault = new VaultAPI(this); + + public void onEnable() { + if (!this.vault.setupEconomy()) { + Bukkit.getPluginManager().disablePlugin(this); + return; + } + this.getCommand("rps").setExecutor(new RPSCommand(this)); + MessagesX.repairPaths(this.messages); + this.playerDataManager.loadFrom(); + this.rps.getFile().getConfigurationSection("Bets").getKeys(false).forEach(name -> { + if (!this.rps.getFile().isSet("Bets." + name + ".rps")) { + this.rps.getFile().set("Bets." + name, null); + this.rps.saveFile(); + return; + } + RPS rps = RPS.valueOf(this.rps.getFile().getString("Bets." + name + ".rps")); + int money = this.rps.getFile().getInt("Bets." + name + ".money"); + PlayerData data = this.playerDataManager.getData(name); + data.setMoney(money); + data.setWageRps(rps); + }); + PluginManager pm = Bukkit.getPluginManager(); + pm.registerEvents(this.playerDataManager, this); + pm.registerEvents(new RPSEvents(this), this); + pm.registerEvents(new TopGuiListener(this), this); + pm.registerEvents(new InventoryCloseListener(this), this); + pm.registerEvents(new ChooseEvents(this), this); + Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> { + FileConfiguration playerBase = this.playerBase.getFile(); + this.playerDataManager.getPlayerData().forEach((key, data) -> { + playerBase.set("Players." + key + ".wins", data.getWins()); + playerBase.set("Players." + key + ".losses", data.getLosses()); + playerBase.set("Players." + key + ".uuid", data.getPlayer().getUniqueId().toString()); + }); + this.playerBase.saveFile(); + this.playerDataManager.getPlayerData().values().forEach(value -> { + this.rps.getFile().set("Bets", null); + this.rps.getFile().createSection("Bets"); + if (value.getMoney() != -1L) { + this.rps.getFile().set("Bets." + value.getName() + ".money", value.getMoney()); + this.rps.getFile().set("Bets." + value.getName() + ".rps", value.getWageRps().toString()); + } else { + this.rps.getFile().set("Bets." + value.getName(), null); + } + }); + this.rps.saveFile(); + }, 100L, 20L); + } + + public void onDisable() { + this.playerDataManager.loadTo(); + this.playerDataManager.getPlayerData().values().forEach(value -> { + if (value.getInventoryEnum() != InventoryEnum.NONE) { + Bukkit.getPlayer(value.getName()).closeInventory(); + } + if (value.getMoney() != -1L) { + this.rps.getFile().set("Bets." + value.getName() + ".money", value.getMoney()); + this.rps.getFile().set("Bets." + value.getName() + ".rps", value.getWageRps().toString()); + } else { + this.rps.getFile().set("Bets." + value.getName(), null); + } + }); + this.rps.saveFile(); + } + + public CFG getOptions() { + return this.options; + } + + public CFG getRps() { + return this.rps; + } + + public CFG getMessages() { + return this.messages; + } + + public WageManager getWageManager() { + return this.wageManager; + } + + public PlayerDataManager getPlayerDataManager() { + return this.playerDataManager; + } + + public CFG getPlayerBase() { + return this.playerBase; + } + + public VaultAPI getVault() { + return this.vault; + } + + public RpsUtilities getRpsUtilities() { + return this.rpsUtilities; + } +} + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/commands/RPSCommand.java b/RPS/src/main/java/net/crankedpvp/rps/commands/RPSCommand.java new file mode 100644 index 0000000..a1f8af3 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/commands/RPSCommand.java @@ -0,0 +1,47 @@ +package net.crankedpvp.rps.commands; +import net.crankedpvp.rps.RPSPlugin; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +public class RPSCommand implements CommandExecutor { + private final RPSPlugin core; + + public RPSCommand(RPSPlugin core) { + this.core = core; + } + + public boolean onCommand(CommandSender cs, Command cmd, String lb, String[] args) { + if (args.length == 0) { + this.core.getRpsUtilities().openRps(cs); + return true; + } + if (args.length == 1) { + if (args[0].equalsIgnoreCase("reload")) { + this.core.getRpsUtilities().reloadFiles(cs); + } else if (args[0].equalsIgnoreCase("cancel")) { + this.core.getRpsUtilities().cancel(cs); + } else if (args[0].equalsIgnoreCase("stats")) { + this.core.getRpsUtilities().sendStats(cs, null); + } else if (args[0].equalsIgnoreCase("toggle")) { + this.core.getRpsUtilities().toggleNot(cs); + } else { + this.core.getRpsUtilities().sendHelp(cs); + } + return true; + } + if (args.length == 2) { + if (args[0].equalsIgnoreCase("stats")) { + this.core.getRpsUtilities().sendStats(cs, args[1]); + } else if (args[0].equalsIgnoreCase("rig")) { + this.core.getRpsUtilities().rig(cs, args[1]); + } else if (args[0].equalsIgnoreCase("top")) { + this.core.getRpsUtilities().topStats(cs, args[1]); + } else { + this.core.getRpsUtilities().createRps(cs, args[0], args[1]); + } + return true; + } + return true; + } +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/listeners/ChooseEvents.java b/RPS/src/main/java/net/crankedpvp/rps/listeners/ChooseEvents.java new file mode 100644 index 0000000..8a64bd2 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/listeners/ChooseEvents.java @@ -0,0 +1,133 @@ +// =============================================== // +// Recompile disabled. Please run Recaf with a JDK // +// =============================================== // + +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.crankedpvp.rps.listeners; + +import com.google.common.collect.Maps; +import net.crankedpvp.rps.RPSPlugin; +import net.crankedpvp.rps.players.PlayerData; +import net.crankedpvp.rps.players.wages.InventoryEnum; +import net.crankedpvp.rps.players.wages.RPS; +import net.crankedpvp.rps.utilities.MessagesX; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.text.NumberFormat; +import java.util.HashMap; +import java.util.Locale; +import java.util.Set; +import java.util.stream.Collectors; + +public class ChooseEvents + implements Listener { + private final RPSPlugin core; + public static HashMap writers = new HashMap(); + + public ChooseEvents(RPSPlugin core) { + this.core = core; + } + + public BufferedWriter getBufferedWriter(File f) { + try { + if (writers.containsKey(f)) { + return writers.get(f); + } + BufferedWriter returns = new BufferedWriter(new FileWriter(f, true)); + writers.put(f, returns); + return returns; + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public void logToFile(File f, String message) { + try { + if (!f.exists()) { + f.getParentFile().mkdirs(); + f.createNewFile(); + } + BufferedWriter br = this.getBufferedWriter(f); + br.write(message); + br.flush(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + @EventHandler + private void onClick(InventoryClickEvent e) { + if (!(e.getWhoClicked() instanceof Player)) { + return; + } + Player player = (Player) e.getWhoClicked(); + PlayerData data = this.core.getPlayerDataManager().getData(player); + Inventory inv = e.getInventory(); + if (data.getInventoryEnum() != InventoryEnum.RPS_CHOOSE_GUI || !inv.equals(data.getInventory())) { + return; + } + e.setCancelled(true); + switch (e.getRawSlot()) { + case 2: { + data.setChooseRps(RPS.ROCK); + break; + } + case 4: { + data.setChooseRps(RPS.PAPER); + break; + } + case 6: { + data.setChooseRps(RPS.SCISSORS); + } + } + if (data.getChooseRps() == null) { + return; + } + PlayerData other = data.getChoosePlayer(); + PlayerData winner = this.core.getWageManager().getWinner(other, data); + HashMap map = Maps.newHashMap(); + other.setWageRps(null); + data.setChooseRps(null); + double worth = other.getMoney(); + map.put("%money%", NumberFormat.getNumberInstance(Locale.US).format(worth * 2.0)); + other.setMoney(-1L); + data.setChoosePlayer(null); + player.closeInventory(); + this.core.getPlayerDataManager().update(); + Set stream = this.core.getPlayerDataManager().getPlayerData().values().stream().filter(streamData -> streamData.isSendMessage() && streamData.getPlayer().isOnline()).map(streamData -> streamData.getPlayer().getPlayer()).collect(Collectors.toSet()); + if (winner == null) { + this.core.getVault().getEconomy().depositPlayer(other.getPlayer(), worth); + map.put("%player_one%", player.getName()); + map.put("%player_two%", other.getName()); + stream.forEach(streamPlayer -> MessagesX.NO_WINNER.msg(streamPlayer, map, false)); + return; + } + if (winner == other) { + other.addWin(); + data.addLose(); + this.core.getVault().getEconomy().depositPlayer(other.getPlayer(), worth * 2.0); + this.core.getVault().getEconomy().withdrawPlayer(data.getPlayer(), worth); + map.put("%winner%", winner.getName()); + map.put("%loser%", data.getName()); + } else { + data.addWin(); + other.addLose(); + this.core.getVault().getEconomy().depositPlayer(data.getPlayer(), worth); + map.put("%winner%", data.getName()); + map.put("%loser%", other.getName()); + } + stream.forEach(streamPlayer -> MessagesX.WINNER.msg(streamPlayer, map, false)); + } +} + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/listeners/InventoryCloseListener.java b/RPS/src/main/java/net/crankedpvp/rps/listeners/InventoryCloseListener.java new file mode 100644 index 0000000..cc332ed --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/listeners/InventoryCloseListener.java @@ -0,0 +1,30 @@ +package net.crankedpvp.rps.listeners; + +import net.crankedpvp.rps.RPSPlugin; +import net.crankedpvp.rps.players.PlayerData; +import net.crankedpvp.rps.players.wages.InventoryEnum; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryCloseEvent; + +public class InventoryCloseListener implements Listener { + private final RPSPlugin core; + + public InventoryCloseListener(RPSPlugin core) { + this.core = core; + } + + @EventHandler + private void onClose(InventoryCloseEvent e) { + if (!(e.getPlayer() instanceof Player)) + return; + Player player = (Player)e.getPlayer(); + PlayerData data = this.core.getPlayerDataManager().getData(player); + if (data.getInventory() != null) { + data.setInventoryEnum(InventoryEnum.NONE); + data.setInventory(null); + data.setChoosePlayer(null); + } + } +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/listeners/RPSEvents.java b/RPS/src/main/java/net/crankedpvp/rps/listeners/RPSEvents.java new file mode 100644 index 0000000..fcd317d --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/listeners/RPSEvents.java @@ -0,0 +1,69 @@ +package net.crankedpvp.rps.listeners; + +import net.crankedpvp.rps.RPSPlugin; +import net.crankedpvp.rps.players.PlayerData; +import net.crankedpvp.rps.players.wages.InventoryEnum; +import net.crankedpvp.rps.utilities.ItemBuilder; +import net.crankedpvp.rps.utilities.NBTEditor; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public class RPSEvents implements Listener { + private final RPSPlugin core; + + private final Inventory inv; + + public RPSEvents(RPSPlugin core) { + this.core = core; + this.inv = Bukkit.createInventory(null, 9, "Rock, Paper or Scissors..."); + this.inv.setItem(2, (new ItemBuilder(Material.COBBLESTONE)).setName("&a&lRock") + .addLoreLine("&7Click to choose this type.").toItemStack()); + this.inv.setItem(4, (new ItemBuilder(Material.PAPER)).setName("&c&lPaper").addLoreLine("&7Click to choose this type.") + .toItemStack()); + this.inv.setItem(6, (new ItemBuilder(Material.SHEARS)).setName("&6&lScissors") + .addLoreLine("&7Click to choose this type.").toItemStack()); + } + + @EventHandler + private void onClick(InventoryClickEvent e) { + if (!(e.getWhoClicked() instanceof Player)) + return; + Player viewer = (Player)e.getWhoClicked(); + PlayerData viewerData = this.core.getPlayerDataManager().getData(viewer); + Inventory inv = e.getInventory(); + if (viewerData.getInventoryEnum() != InventoryEnum.RPS_GUI || !inv.equals(viewerData.getInventory())) + return; + e.setCancelled(true); + ItemStack item = e.getCurrentItem(); + if (item == null || item.getType() == Material.AIR) + return; + Object obj = NBTEditor.getItemTag(item, "wager"); + if (!(obj instanceof String)) + return; + String wagerName = obj.toString(); + PlayerData wagerData = this.core.getPlayerDataManager().getData(wagerName); + if (wagerName.equalsIgnoreCase(viewer.getName())) + return; + if (wagerData.getMoney() == -1L) { + this.core.getRpsUtilities().openRps(viewer); + return; + } + if (this.core.getPlayerDataManager().getBalance(viewer) < wagerData.getMoney()) + return; + openChoose(viewer, wagerData); + } + + private void openChoose(Player player, PlayerData wagerData) { + player.openInventory(this.inv); + PlayerData data = this.core.getPlayerDataManager().getData(player); + data.setInventory(this.inv); + data.setChoosePlayer(wagerData); + data.setInventoryEnum(InventoryEnum.RPS_CHOOSE_GUI); + } +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/listeners/TopGuiListener.java b/RPS/src/main/java/net/crankedpvp/rps/listeners/TopGuiListener.java new file mode 100644 index 0000000..1a13431 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/listeners/TopGuiListener.java @@ -0,0 +1,30 @@ +package net.crankedpvp.rps.listeners; + +import net.crankedpvp.rps.RPSPlugin; +import net.crankedpvp.rps.players.PlayerData; +import net.crankedpvp.rps.players.wages.InventoryEnum; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; + +public class TopGuiListener implements Listener { + private final RPSPlugin core; + + public TopGuiListener(RPSPlugin core) { + this.core = core; + } + + @EventHandler + private void onClick(InventoryClickEvent e) { + if (!(e.getWhoClicked() instanceof Player)) + return; + Player player = (Player)e.getWhoClicked(); + PlayerData data = this.core.getPlayerDataManager().getData(player); + Inventory inv = e.getInventory(); + if (data.getInventoryEnum() != InventoryEnum.TOP_STATS_GUI || !inv.equals(data.getInventory())) + return; + e.setCancelled(true); + } +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/players/PlayerData.java b/RPS/src/main/java/net/crankedpvp/rps/players/PlayerData.java new file mode 100644 index 0000000..e3381e4 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/players/PlayerData.java @@ -0,0 +1,164 @@ +// =============================================== // +// Recompile disabled. Please run Recaf with a JDK // +// =============================================== // + +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.crankedpvp.rps.players; + +import net.crankedpvp.rps.RPSPlugin; +import net.crankedpvp.rps.players.wages.InventoryEnum; +import net.crankedpvp.rps.players.wages.RPS; +import net.crankedpvp.rps.utilities.Utils; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.inventory.Inventory; + +import java.util.UUID; + +public class PlayerData { + private int wins; + private int losses; + private final String name; + private Inventory inventory; + private RPS wageRps = null; + private RPS chooseRps = null; + private long money = -1L; + private PlayerData choosePlayer = null; + private InventoryEnum inventoryEnum = InventoryEnum.NONE; + private boolean sendMessage = true; + private final UUID uuid; + private boolean rig = false; + private OfflinePlayer offPlayer; + + public PlayerData(RPSPlugin core, String name, UUID uuid) { + this.name = name; + this.uuid = uuid; + FileConfiguration file = core.getPlayerBase().getFile(); + boolean change = false; + if (!file.isSet("Players." + name + ".wins")) { + file.set("Players." + name + ".wins", 0); + change = true; + } + if (!file.isSet("Players." + name + ".losses")) { + file.set("Players." + name + ".losses", 0); + change = true; + } + if (change) { + core.getPlayerBase().saveFile(); + } + this.setWins(file.getInt("Players." + name + ".wins")); + this.setLosses(file.getInt("Players." + name + ".losses")); + } + + public int getLosses() { + return this.losses; + } + + public int getWins() { + return this.wins; + } + + public double getRatio() { + if (this.wins > this.losses) { + return this.losses == 0 ? (double)this.wins : Utils.round((double)this.wins / (double)this.losses, 2); + } + if (this.wins < this.losses) { + return -(this.wins == 0 ? (double)this.losses : Utils.round((double)this.losses / (double)this.wins, 2)); + } + return 0.0; + } + + public void setWins(int wins) { + this.wins = wins; + } + + public void setLosses(int losses) { + this.losses = losses; + } + + public void addWin() { + this.setWins(this.wins + 1); + } + + public void addLose() { + this.setLosses(this.losses + 1); + } + + public String getName() { + return this.name; + } + + public Inventory getInventory() { + return this.inventory; + } + + public void setInventory(Inventory inventory) { + this.inventory = inventory; + } + + public OfflinePlayer getPlayer() { + return this.offPlayer == null ? (this.offPlayer = Bukkit.getOfflinePlayer(this.uuid)) : this.offPlayer; + } + + public long getMoney() { + return this.money; + } + + public void setMoney(long money) { + this.money = money; + } + + public boolean isRig() { + return this.rig; + } + + public void setRig(boolean rig) { + this.rig = rig; + } + + public RPS getChooseRps() { + return this.chooseRps; + } + + public void setChooseRps(RPS chooseRps) { + this.chooseRps = chooseRps; + } + + public RPS getWageRps() { + return this.wageRps; + } + + public void setWageRps(RPS wageRps) { + this.wageRps = wageRps; + } + + public PlayerData getChoosePlayer() { + return this.choosePlayer; + } + + public void setChoosePlayer(PlayerData choosePlayer) { + if (choosePlayer == this) { + throw new UnsupportedOperationException(); + } + this.choosePlayer = choosePlayer; + } + + public boolean isSendMessage() { + return this.sendMessage; + } + + public void setSendMessage(boolean sendMessage) { + this.sendMessage = sendMessage; + } + + public InventoryEnum getInventoryEnum() { + return this.inventoryEnum; + } + + public void setInventoryEnum(InventoryEnum inventoryEnum) { + this.inventoryEnum = inventoryEnum; + } +} + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/players/PlayerDataManager.java b/RPS/src/main/java/net/crankedpvp/rps/players/PlayerDataManager.java new file mode 100644 index 0000000..a48616c --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/players/PlayerDataManager.java @@ -0,0 +1,129 @@ +// =============================================== // +// Recompile disabled. Please run Recaf with a JDK // +// =============================================== // + +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.crankedpvp.rps.players; + +import com.google.common.collect.Maps; +import net.crankedpvp.rps.RPSPlugin; +import net.crankedpvp.rps.players.wages.InventoryEnum; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.logging.Level; + +public class PlayerDataManager implements Listener { + private final Map map = Maps.newHashMap(); + private final RPSPlugin core; + + public Map getPlayerData() { + return this.map; + } + + public PlayerDataManager(RPSPlugin core) { + this.core = core; + } + + public PlayerData getData(Player target) { + return this.getData(target.getName()); + } + + public PlayerData getData(String name) { + if (!this.map.containsKey(name)) { + try { + return this.loadPlayer(name, Bukkit.getOfflinePlayer(name).getUniqueId()); + } catch (NullPointerException ignored) { + this.core.getLogger().log(Level.WARNING, "Player: " + name + " was unable to be loaded into memory"); + } + throw new RuntimeException("The player: " + name + " is not registered in memory."); + } + return this.map.get(name); + } + + public PlayerData loadPlayer(String name, UUID uuid) { + if (this.isRegistered(name)) { + return this.map.get(name); + } + PlayerData data = new PlayerData(this.core, name, uuid); + this.map.put(name, data); + return data; + } + + public void purge(String name) { + this.map.remove(name); + } + + public Optional getDataIgnoreCase(String key) { + return this.map.entrySet().stream().filter(entry -> entry.getKey().equalsIgnoreCase(key)).findAny().map(Map.Entry::getValue); + } + + public boolean isRegistered(String name) { + return name != null && this.map.containsKey(name); + } + + public double getBalance(OfflinePlayer player) { + return this.core.getVault().getEconomy().getBalance(player); + } + + public void update() { + Bukkit.getOnlinePlayers().forEach(this::update); + } + + public void update(Player target) { + PlayerData data = this.getData(target); + InventoryEnum invEnum = data.getInventoryEnum(); + if (invEnum == InventoryEnum.NONE || invEnum == InventoryEnum.TOP_STATS_GUI) { + return; + } + if (invEnum == InventoryEnum.RPS_GUI) { + this.core.getRpsUtilities().openRps(target); + return; + } + if (data.getChoosePlayer() == null || data.getChoosePlayer().getMoney() == -1L) { + this.core.getRpsUtilities().openRps(target); + } + } + + public void loadTo() { + FileConfiguration playerBase = this.core.getPlayerBase().getFile(); + this.map.forEach((key, data) -> { + playerBase.set("Players." + key + ".wins", data.getWins()); + playerBase.set("Players." + key + ".losses", data.getLosses()); + playerBase.set("Players." + key + ".uuid", data.getPlayer().getUniqueId().toString()); + }); + this.core.getPlayerBase().saveFile(); + } + + public void loadFrom() { + FileConfiguration playerBase = this.core.getPlayerBase().getFile(); + this.core.getPlayerBase().getFile().getConfigurationSection("Players").getKeys(false).forEach(name -> { + if (!playerBase.isSet("Players." + name + ".uuid")) { + playerBase.set("Players." + name, null); + this.core.getPlayerBase().saveFile(); + return; + } + UUID uuid = UUID.fromString(playerBase.getString("Players." + name + ".uuid")); + PlayerData data = this.loadPlayer(name, uuid); + int wins = playerBase.getInt("Players." + name + ".wins"); + int losses = playerBase.getInt("Players." + name + ".losses"); + data.setWins(wins); + data.setLosses(losses); + }); + } + + @EventHandler + private void onJoin(PlayerJoinEvent e) { + this.loadPlayer(e.getPlayer().getName(), e.getPlayer().getUniqueId()); + } +} + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/players/wages/InventoryEnum.java b/RPS/src/main/java/net/crankedpvp/rps/players/wages/InventoryEnum.java new file mode 100644 index 0000000..7d390b1 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/players/wages/InventoryEnum.java @@ -0,0 +1,5 @@ +package net.crankedpvp.rps.players.wages; + +public enum InventoryEnum { + RPS_GUI, RPS_CHOOSE_GUI, TOP_STATS_GUI, NONE; +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/players/wages/RPS.java b/RPS/src/main/java/net/crankedpvp/rps/players/wages/RPS.java new file mode 100644 index 0000000..ad79910 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/players/wages/RPS.java @@ -0,0 +1,5 @@ +package net.crankedpvp.rps.players.wages; + +public enum RPS { + ROCK, PAPER, SCISSORS; +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/players/wages/WageManager.java b/RPS/src/main/java/net/crankedpvp/rps/players/wages/WageManager.java new file mode 100644 index 0000000..3f6bc90 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/players/wages/WageManager.java @@ -0,0 +1,177 @@ +// =============================================== // +// Recompile disabled. Please run Recaf with a JDK // +// =============================================== // + +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.crankedpvp.rps.players.wages; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.mojang.authlib.GameProfile; +import net.crankedpvp.rps.RPSPlugin; +import net.crankedpvp.rps.players.PlayerData; +import net.crankedpvp.rps.utilities.MessagesX; +import net.crankedpvp.rps.utilities.NBTEditor; +import net.crankedpvp.rps.utilities.Utils; +import net.minecraft.server.v1_8_R3.*; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftInventory; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import java.text.NumberFormat; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class WageManager { + private final RPSPlugin core; + + public WageManager(RPSPlugin core) { + this.core = core; + } + + public PlayerData getWinner(PlayerData data, PlayerData accept) { + RPS wager = data.getWageRps(); + RPS accepter = accept.getChooseRps(); + if (data.isRig() && accept.isRig()) { + return null; + } + if (data.isRig()) { + return data; + } + if (accept.isRig()) { + return accept; + } + if (wager == null || accepter == null) { + return null; + } + if (accepter == wager) { + return null; + } + switch (wager) { + case PAPER: { + return accepter == RPS.ROCK ? data : accept; + } + case ROCK: { + return accepter == RPS.PAPER ? accept : data; + } + case SCISSORS: { + return accepter == RPS.ROCK ? accept : data; + } + } + return null; + } + + public List getTopWagers(boolean wins) { + Map playerDataMap = this.core.getPlayerDataManager().getPlayerData(); + Map sorted = wins ? this.sortByWins(playerDataMap) : this.sortByLosses(playerDataMap); + return sorted.entrySet().stream().limit(9L).map(Map.Entry::getValue).collect(Collectors.toCollection(LinkedList::new)); + } + + public static void ensureSkullTextures(Inventory inv, int slot) { + IInventory iinv = ((CraftInventory) inv).getInventory(); + net.minecraft.server.v1_8_R3.ItemStack item = iinv.getItem(slot); + NBTTagCompound tag = item.getTag(); + NBTTagCompound skullOwner = (NBTTagCompound)tag.get("SkullOwner"); + if (skullOwner == null) { + throw new IllegalArgumentException("No SkullOwner NBT tag"); + } + GameProfile profile = GameProfileSerializer.deserialize(skullOwner); + if (!profile.getProperties().containsKey("textures")) { + TileEntitySkull.b(profile, input -> { + NBTTagCompound owner = new NBTTagCompound(); + GameProfileSerializer.serialize(owner, input); + tag.set("SkullOwner", owner); + WageManager.updateSlot(inv, slot, item); + return false; + }); + } + } + + private static void updateSlot(Inventory inventory, int slot, net.minecraft.server.v1_8_R3.ItemStack item) { + for (HumanEntity viewer : inventory.getViewers()) { + Player player = (Player) viewer; + EntityPlayer ep = ((CraftPlayer) player).getHandle(); + ep.a(ep.activeContainer, slot, item); + } + } + + public Set getWagers(boolean operator, Player viewer) { + LinkedHashSet skulls = Sets.newLinkedHashSet(); + FileConfiguration options = this.core.getOptions().getFile(); + FPlayer fviewer = FPlayers.getInstance().getByPlayer(viewer); + + Stream> playerDataStream = this.core.getPlayerDataManager().getPlayerData().entrySet().stream() + .filter(data -> (data.getValue().getMoney() != -1L)); + this.sortByLongValue(playerDataStream.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))).limit(26L).forEachOrdered(wager -> { + ItemStack item = NBTEditor.setItemTag(new ItemStack(Material.SKULL_ITEM, 1, (short) 3), wager.getKey(), "wager"); + SkullMeta meta = (SkullMeta)item.getItemMeta(); + HashMap map = Maps.newHashMap(); + if (operator || viewer.getName().equals(wager.getKey())) { + map.put("%rps%", StringUtils.capitalize(wager.getValue().getWageRps().name())); + } + FPlayer fwager = FPlayers.getInstance().getByOfflinePlayer(wager.getValue().getPlayer()); + double balance = this.core.getVault().getEconomy().getBalance(viewer); + map.put("%enterable%", Utils.colorize(wager.getKey().equals(viewer.getName()) ? MessagesX.SELF_WAGER.getMessages()[0] : (balance >= (double) wager.getValue().getMoney() ? MessagesX.AFFORDABLE.getMessages()[0] : MessagesX.UNAFFORDABLE.getMessages()[0]))); + map.put("%name%", wager.getKey()); + map.put("%faction%", fwager.getFaction().getTag()); + map.put("%relation_color%", fviewer.getRelationTo(fwager).getColor().toString()); + map.put("%money%", NumberFormat.getNumberInstance(Locale.US).format(wager.getValue().getMoney())); + map.put("%ratio%", String.valueOf(wager.getValue().getWins() == 0 && wager.getValue().getLosses() == 0 ? 0.0 : wager.getValue().getRatio())); + map.put("%wins%", String.valueOf(wager.getValue().getWins())); + map.put("%losses%", String.valueOf(wager.getValue().getLosses())); + meta.setOwner(wager.getKey()); + meta.setDisplayName(Utils.placeHolder(Utils.colorize(options.getString(operator || viewer.getName().equals(wager.getKey()) ? "Heads.operator.name" : "Heads.normal.name")), map, false)); + meta.setLore(Utils.placeHolder(Utils.colorize(options.getStringList(operator || viewer.getName().equals(wager.getKey()) ? "Heads.operator.lore" : "Heads.normal.lore")), map, false)); + meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + item.setItemMeta(meta); + skulls.add(item); + }); + return skulls; + } + + public Stream> sortByLongValue(Map input) { + return input.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue(Comparator.comparingLong(this::getLongValue).reversed())); + } + + public Map sortByWins(Map input) { + return input.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue(Comparator.comparingLong(this::getWinsValue).reversed())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); + } + + private long getWinsValue(PlayerData playerData) { + return playerData.getWins(); + } + + private long getLossesValue(PlayerData playerData) { + return playerData.getLosses(); + } + + public Map sortByLosses(Map input) { + return input.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue(Comparator.comparingLong(this::getLossesValue).reversed())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); + } + + private long getLongValue(PlayerData playerData) { + String name = playerData.getName(); + return this.core.getRps().getFile().getLong("Bets." + name + ".time"); + } +} + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/rpsutilities/RpsUtilities.java b/RPS/src/main/java/net/crankedpvp/rps/rpsutilities/RpsUtilities.java new file mode 100644 index 0000000..1eeb8a7 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/rpsutilities/RpsUtilities.java @@ -0,0 +1,296 @@ +// =============================================== // +// Recompile disabled. Please run Recaf with a JDK // +// =============================================== // + +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.crankedpvp.rps.rpsutilities; + +import com.google.common.collect.Maps; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import net.crankedpvp.rps.RPSPlugin; +import net.crankedpvp.rps.players.PlayerData; +import net.crankedpvp.rps.players.wages.InventoryEnum; +import net.crankedpvp.rps.players.wages.RPS; +import net.crankedpvp.rps.players.wages.WageManager; +import net.crankedpvp.rps.utilities.ItemBuilder; +import net.crankedpvp.rps.utilities.MessagesX; +import net.crankedpvp.rps.utilities.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.text.NumberFormat; +import java.util.*; + +public class RpsUtilities { + private final RPSPlugin core; + + public RpsUtilities(RPSPlugin core) { + this.core = core; + } + + public void openRps(CommandSender cs) { + if (!(cs instanceof Player)) { + return; + } + Player player = (Player)cs; + Set heads = this.core.getWageManager().getWagers(player.isOp(), player); + Inventory inv = Bukkit.createInventory(null, 27, Utils.colorize(this.core.getOptions().getFile().getString("Inventory.name").replace("%amount%", String.valueOf(heads.size())))); + ItemStack[] stacks = heads.toArray(new ItemStack[0]); + int i = 0; + while (i < stacks.length) { + inv.setItem(i, stacks[i]); + WageManager.ensureSkullTextures(inv, i); + ++i; + } + FileConfiguration file = this.core.getOptions().getFile(); + ItemStack book = new ItemBuilder(Material.BOOK).setName(file.getString("Inventory.items.book.name")).setLore(file.getStringList("Inventory.items.book.lore")).toItemStack(); + inv.setItem(26, book); + player.openInventory(inv); + PlayerData data = this.core.getPlayerDataManager().getData(player); + data.setInventory(inv); + data.setInventoryEnum(InventoryEnum.RPS_GUI); + player.updateInventory(); + } + + public void topStats(CommandSender cs, String input) { + boolean wins; + if (!(cs instanceof Player)) { + return; + } + Player player = (Player)cs; + if (input.equalsIgnoreCase("wins")) { + wins = true; + } else if (input.equalsIgnoreCase("losses")) { + wins = false; + } else { + this.sendHelp(cs); + return; + } + List datas = this.core.getWageManager().getTopWagers(wins); + FPlayer fviewer = FPlayers.getInstance().getByPlayer(player); + FileConfiguration options = this.core.getOptions().getFile(); + Inventory inv = Bukkit.createInventory(null, 27, Utils.colorize(options.getString(wins ? "Top-Players.Wins.name" : "Top-Players.Losses.name"))); + int i = 0; + while (i < datas.size()) { + PlayerData data = datas.get(i); + ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); + SkullMeta meta = (SkullMeta)item.getItemMeta(); + HashMap map = Maps.newHashMap(); + FPlayer fwager = FPlayers.getInstance().getByOfflinePlayer(data.getPlayer()); + map.put("%rank%", String.valueOf(i + 1)); + map.put("%name%", data.getName()); + map.put("%faction%", fwager.getFaction().getTag()); + map.put("%relation_color%", fviewer.getRelationTo(fwager).getColor().toString()); + map.put("%ratio%", String.valueOf(data.getWins() == 0 && data.getLosses() == 0 ? 0.0 : data.getRatio())); + map.put("%wins%", String.valueOf(data.getWins())); + map.put("%losses%", String.valueOf(data.getLosses())); + meta.setOwner(data.getName()); + meta.setDisplayName(Utils.placeHolder(Utils.colorize(options.getString("Top-Players.Wins.items.name")), map, false)); + meta.setLore(Utils.placeHolder(Utils.colorize(options.getStringList(wins ? "Top-Players.Wins.items.lore" : "Top-Players.Losses.items.lore")), map, false)); + meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + item.setItemMeta(meta); + inv.setItem(i + 9, item); + ++i; + } + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 15); + ItemMeta meta = item.getItemMeta(); + meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + meta.setDisplayName(Utils.colorize("&c")); + item.setItemMeta(meta); + int i2 = 0; + while (i2 < 27) { + if (inv.getItem(i2) == null) { + inv.setItem(i2, item); + } + ++i2; + } + player.openInventory(inv); + PlayerData pdata = this.core.getPlayerDataManager().getData(player); + pdata.setInventoryEnum(InventoryEnum.TOP_STATS_GUI); + pdata.setInventory(inv); + } + + public void toggleNot(CommandSender cs) { + if (!(cs instanceof Player)) { + return; + } + Player player = (Player)cs; + PlayerData data = this.core.getPlayerDataManager().getData(player); + if (data.isSendMessage()) { + data.setSendMessage(false); + MessagesX.NOT_TOGGLE_OFF.msg(player); + } else { + data.setSendMessage(true); + MessagesX.NOT_TOGGLE_ON.msg(player); + } + } + + public void sendHelp(CommandSender cs) { + MessagesX.HELP_FORMAT.msg(cs); + } + + public void rig(CommandSender cs, String string) { + if (!cs.hasPermission("rps.rig")) { + MessagesX.NO_PERMISSION.msg(cs); + return; + } + HashMap map = Maps.newHashMap(); + Optional opt = this.core.getPlayerDataManager().getDataIgnoreCase(string); + if (!opt.isPresent()) { + map.put("%name%", string); + MessagesX.USER_NOT_FOUND.msg(cs, map, false); + return; + } + PlayerData data = opt.get(); + map.put("%user%", data.getName()); + if (data.isRig()) { + data.setRig(false); + MessagesX.RIGLESS.msg(cs, map, false); + } else { + data.setRig(true); + MessagesX.RIG.msg(cs, map, false); + } + } + + public void cancel(CommandSender cs) { + if (!(cs instanceof Player)) { + return; + } + Player player = (Player)cs; + PlayerData data = this.core.getPlayerDataManager().getPlayerData().get(player.getName()); + if (data.getMoney() == -1L) { + MessagesX.CANCEL_FAIL.msg(player); + return; + } + this.core.getVault().getEconomy().depositPlayer(player, data.getMoney()); + data.setMoney(-1L); + this.core.getPlayerDataManager().update(); + MessagesX.CANCEL_SUCCESSFUL.msg(player); + } + + public void createRps(CommandSender cs, String inputMoney, String inputRps) { + if (!(cs instanceof Player)) { + return; + } + Player player = (Player)cs; + + if (!Utils.isLong(inputMoney)) { + MessagesX.HELP_FORMAT.msg(player); + return; + } + long money = Long.parseLong(inputMoney); + PlayerData data = this.core.getPlayerDataManager().loadPlayer(player.getName(), player.getUniqueId()); + if (data.getMoney() != -1L) { + MessagesX.ALREADY_WAGED.msg(player); + return; + } + if (this.core.getPlayerDataManager().getPlayerData().values().stream().filter(datax -> datax.getMoney() != -1L).count() >= 26L) { + MessagesX.WAGE_FULL.msg(player); + return; + } + long small = this.core.getOptions().getFile().getLong("Prices.minimum"); + long maximum = this.core.getOptions().getFile().getLong("Prices.maximum"); + if (money < small) { + MessagesX.AMOUNT_TOO_SMALL.msg(player); + return; + } + if (money > maximum) { + MessagesX.AMOUNT_TOO_BIG.msg(player); + return; + } + if (this.core.getPlayerDataManager().getBalance(player) < (double)money) { + MessagesX.INSUFFICIENT_FUNDS.msg(player); + return; + } + switch (inputRps.toLowerCase()) { + case "r": + case "rock": { + data.setWageRps(RPS.ROCK); + break; + } + case "p": + case "paper": { + data.setWageRps(RPS.PAPER); + break; + } + case "scissors": + case "s": { + data.setWageRps(RPS.SCISSORS); + break; + } + default: { + MessagesX.HELP_FORMAT.msg(player); + return; + } + } + data.setMoney(money); + this.core.getVault().getEconomy().withdrawPlayer(player, money); + this.core.getRps().getFile().set("Bets." + player.getName() + ".time", System.currentTimeMillis()); + this.core.getRps().saveFile(); + HashMap map = Maps.newHashMap(); + map.put("%amount%", NumberFormat.getNumberInstance(Locale.US).format(money)); + MessagesX.WAGE_CREATE.msg(player, map, false); + this.core.getPlayerDataManager().update(); + } + + public void sendStats(CommandSender cs, String input) { + PlayerData data; + HashMap map = Maps.newHashMap(); + if (input == null) { + if (!(cs instanceof Player)) { + return; + } + data = this.core.getPlayerDataManager().getPlayerData().get(cs.getName()); + } else { + Optional opt = this.core.getPlayerDataManager().getDataIgnoreCase(input); + if (!opt.isPresent()) { + map.put("%name%", input); + MessagesX.USER_NOT_FOUND.msg(cs, map, false); + return; + } + data = opt.get(); + } + String name = data.getName(); + double ratio = data.getRatio(); + int wins = data.getWins(); + int losses = data.getLosses(); + map.put("%player%", name); + map.put("%ratio%", String.valueOf(ratio)); + map.put("%wins%", String.valueOf(wins)); + map.put("%losses%", String.valueOf(losses)); + MessagesX.STATS.msg(cs, map, false); + } + + public void reloadFiles(CommandSender cs) { + if (!cs.hasPermission("rps.reload")) { + MessagesX.NO_PERMISSION.msg(cs); + return; + } + this.core.getOptions().reloadFile(); + this.core.getRps().reloadFile(); + this.core.getPlayerBase().reloadFile(); + this.core.getMessages().reloadFile(); + MessagesX.repairPaths(this.core.getMessages()); + MessagesX.RELOADED.msg(cs); + this.core.getPlayerDataManager().loadFrom(); + this.core.getRps().getFile().getConfigurationSection("Bets").getKeys(false).forEach(name -> { + RPS rps = RPS.valueOf(this.core.getRps().getFile().getString("Bets." + name + ".rps")); + int money = this.core.getRps().getFile().getInt("Bets." + name + ".money"); + PlayerData data = this.core.getPlayerDataManager().getData(name); + data.setMoney(money); + data.setWageRps(rps); + }); + this.core.getPlayerDataManager().update(); + } +} + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/utilities/CFG.java b/RPS/src/main/java/net/crankedpvp/rps/utilities/CFG.java new file mode 100644 index 0000000..aceba07 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/utilities/CFG.java @@ -0,0 +1,59 @@ +package net.crankedpvp.rps.utilities; + +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.IOException; + +public class CFG { + private final JavaPlugin p; + + private final String filename; + + private FileConfiguration file; + + private File cfile; + + private final boolean saveResource; + + public CFG(JavaPlugin p, String string, boolean saveResource) { + this.p = p; + this.filename = String.valueOf(string) + ".yml"; + this.saveResource = saveResource; + setup(); + } + + public void setup() { + if (!this.p.getDataFolder().exists()) + this.p.getDataFolder().mkdir(); + this.cfile = new File(this.p.getDataFolder(), this.filename); + if (!this.cfile.exists()) { + try { + this.cfile.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + if (this.saveResource) + this.p.saveResource(this.filename, true); + } + reloadFile(); + } + + public void saveFile() { + try { + getFile().save(this.cfile); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void reloadFile() { + this.file = (FileConfiguration)YamlConfiguration.loadConfiguration(this.cfile); + } + + public FileConfiguration getFile() { + return this.file; + } +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/utilities/ItemBuilder.java b/RPS/src/main/java/net/crankedpvp/rps/utilities/ItemBuilder.java new file mode 100644 index 0000000..3ddd709 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/utilities/ItemBuilder.java @@ -0,0 +1,108 @@ +package net.crankedpvp.rps.utilities; + +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +public class ItemBuilder { + private ItemStack is; + + public ItemBuilder(Material m) { + this(m, 1); + } + + public ItemBuilder(ItemStack is) { + this.is = is; + } + + public ItemBuilder(Material m, int amount) { + this.is = new ItemStack(m, amount); + } + + public ItemBuilder(Material m, int amount, byte durability) { + this.is = new ItemStack(m, amount, durability); + } + + public ItemBuilder clone() { + return new ItemBuilder(this.is); + } + + public ItemBuilder setDurability(short dur) { + this.is.setDurability(dur); + return this; + } + + public ItemBuilder setName(String name) { + ItemMeta im = this.is.getItemMeta(); + im.setDisplayName(Utils.colorize(name)); + this.is.setItemMeta(im); + return this; + } + + public ItemBuilder addUnsafeEnchantment(Enchantment ench, int level) { + this.is.addUnsafeEnchantment(ench, level); + return this; + } + + public ItemBuilder removeEnchantment(Enchantment ench) { + this.is.removeEnchantment(ench); + return this; + } + + public ItemBuilder setSkullOwner(String owner) { + if (!(this.is.getItemMeta() instanceof SkullMeta)) + throw new UnsupportedOperationException("Casting SkullMeta to the current ItemMeta is not possible!"); + SkullMeta im = (SkullMeta)this.is.getItemMeta(); + im.setOwner(owner); + this.is.setItemMeta((ItemMeta)im); + return this; + } + + public ItemBuilder addEnchant(Enchantment ench, int level) { + ItemMeta im = this.is.getItemMeta(); + im.addEnchant(ench, level, true); + this.is.setItemMeta(im); + return this; + } + + public ItemBuilder addEnchantments(Map enchantments) { + this.is.addEnchantments(enchantments); + return this; + } + + public ItemBuilder setLore(String... lore) { + ItemMeta im = this.is.getItemMeta(); + im.setLore(Arrays.asList(lore)); + this.is.setItemMeta(im); + return this; + } + + public ItemBuilder setLore(List lore) { + ItemMeta im = this.is.getItemMeta(); + im.setLore(Utils.colorize(lore)); + this.is.setItemMeta(im); + return this; + } + + public ItemBuilder addLoreLine(String line) { + ItemMeta im = this.is.getItemMeta(); + List lore = new ArrayList<>(); + if (im.hasLore()) + lore = new ArrayList<>(im.getLore()); + lore.add(Utils.colorize(line)); + im.setLore(lore); + this.is.setItemMeta(im); + return this; + } + + public ItemStack toItemStack() { + return this.is; + } +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/utilities/MessagesX.java b/RPS/src/main/java/net/crankedpvp/rps/utilities/MessagesX.java new file mode 100644 index 0000000..cb29b92 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/utilities/MessagesX.java @@ -0,0 +1,133 @@ +// =============================================== // +// Recompile disabled. Please run Recaf with a JDK // +// =============================================== // + +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.crankedpvp.rps.utilities; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; + +import java.util.Map; + +public enum MessagesX { + NO_PERMISSION("Messages.No-Permission", "&cYou are not allowed to use this command."), + PLAYER_OFFLINE("Messages.Player-Offline", "&c&l(!) &4%player%&c is not locally online."), + RELOADED("Messages.Reloaded", "&a&l(!) &7Plugin has been reloaded!"), + AFFORDABLE("Messages.Affordable", "&aYou can afford to enter this wager."), + UNAFFORDABLE("Messages.Unaffordable", "&cYou cannot afford to enter this wager."), + NO_WINNER("Messages.No-Win", "&6%player_one% &7went tie with &6%player_two% &7in an &e/rps &7game worth &n$%money%&7."), + WINNER("Messages.Win", "&a%winner% &7has won against &c%loser% &7in an &e/rps &7game worth &n$%money%&7."), + SELF_WAGER("Messages.Self-Wager", "&cYou cannot enter your own wager."), + ALREADY_WAGED("Messages.Already-Wager", "&cYou already have a wage set."), + WAGE_FULL("Messages.Wage-Full", "&cYou may not wage as the max capacity is reached!"), + WAGE_CREATE("Messages.Wage-Create", "&7Created a wager with an amount of &e$%amount% &7"), + AMOUNT_TOO_SMALL("Messages.Money-Too-Small", "&7The amount specified wasn't enough, the amount must be greater than 1."), + AMOUNT_TOO_BIG("Messages.Money-Too-Big", "&7The amount specified wasn't enough, the amount must be smaller than 10.000."), + USER_NOT_FOUND("MessagesX.User-Not-Found", "&cNo user found with the name: &e%name%"), + CANCEL_FAIL("Messages.Cancel-Fail", "&cYou do not have a wage to cancel!"), + RIG("Messages.Rig", "&aUser &e%user% &ais now rigged!"), + RIGLESS("Messages.Rigless", "&cUser &e%user% &cis no longer rigged!"), + INSUFFICIENT_FUNDS("Messages.Insufficient-Funds", "&cYou do not have enough money!"), + CANCEL_SUCCESSFUL("Messages.Cancel-Successful", "&aYou have removed your wage."), + NOT_TOGGLE_ON("Messages.Notification-On", "&aYou will now receive notification upon an rps match."), + NOT_TOGGLE_OFF("Messages.Notification-Off", "&cYou will no longer receive notification upon an rps match."), + STATS("MessagesX.Stats", "", "&e&l%player%'s RPS Stats", "&6- Ratio: %ratio%", "&6- Wins: %wins%", "&6- Losses: %losses%", ""), + HELP_FORMAT("Messages.Help", "", "&e&l(!) &eRPS Commands:", " &8� &f/rps", " &8� &f/rps &7reload", " &8� &f/rps &7cancel", " &8� &f/rps &7 ", " &8� &f/rps &7toggle", " &8� &f/rps &7top ", ""); + + private String[] messages; + private final String path; + + MessagesX(String path, String... messages) { + this.messages = messages; + this.path = path; + } + + private boolean isMultiLined() { + return this.messages.length > 1; + } + + public static void repairPaths(CFG cfg) { + boolean changed = false; + MessagesX[] messagesXArray = MessagesX.values(); + int n = messagesXArray.length; + int n2 = 0; + while (n2 < n) { + MessagesX enumMessage = messagesXArray[n2]; + if (cfg.getFile().contains(enumMessage.getPath())) { + MessagesX.setPathToMessage(cfg, enumMessage); + } else { + MessagesX.setMessageToPath(cfg, enumMessage); + if (!changed) { + changed = true; + } + } + ++n2; + } + if (changed) { + cfg.saveFile(); + } + } + + private static void setMessageToPath(CFG cfg, MessagesX enumMessage) { + if (enumMessage.isMultiLined()) { + cfg.getFile().set(enumMessage.getPath(), enumMessage.getMessages()); + } else { + cfg.getFile().set(enumMessage.getPath(), enumMessage.getMessages()[0]); + } + } + + private static void setPathToMessage(CFG cfg, MessagesX enumMessage) { + if (Utils.isList(cfg.getFile(), enumMessage.getPath())) { + enumMessage.setMessages(cfg.getFile().getStringList(enumMessage.getPath()).toArray(new String[0])); + } else { + enumMessage.setMessages(cfg.getFile().getString(enumMessage.getPath())); + } + } + + public String getPath() { + return this.path; + } + + public String[] getMessages() { + return this.messages; + } + + public void setMessages(String[] messages) { + this.messages = messages; + } + + public void setMessages(String messages) { + this.messages[0] = messages; + } + + public void msg(CommandSender target) { + this.msg(target, null, false); + } + + public void msg(CommandSender target, Map map, boolean ignoreCase) { + if (this.isMultiLined()) { + Utils.msg(target, this.getMessages(), map, ignoreCase); + } else { + Utils.msg(target, this.getMessages()[0], map, ignoreCase); + } + } + + public void msgAll() { + if (this.isMultiLined()) { + Bukkit.getOnlinePlayers().forEach(target -> Utils.msg(target, this.getMessages())); + } else { + Bukkit.getOnlinePlayers().forEach(target -> Utils.msg(target, this.getMessages()[0])); + } + } + + public void msgAll(Map map, boolean ignoreCase) { + if (this.isMultiLined()) { + Bukkit.getOnlinePlayers().forEach(target -> Utils.msg(target, this.getMessages(), map, ignoreCase)); + } else { + Bukkit.getOnlinePlayers().forEach(target -> Utils.msg(target, this.getMessages()[0], map, ignoreCase)); + } + } +} + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/utilities/NBTEditor.java b/RPS/src/main/java/net/crankedpvp/rps/utilities/NBTEditor.java new file mode 100644 index 0000000..1e817db --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/utilities/NBTEditor.java @@ -0,0 +1,328 @@ +package net.crankedpvp.rps.utilities; + +import com.google.common.primitives.Primitives; +import com.mojang.authlib.GameProfile; +import org.bukkit.Bukkit; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class NBTEditor { + private static final Map> classCache; + + private static final Map methodCache; + + private static final Map, Constructor> constructorCache; + + private static final Map, Class> NBTClasses; + + private static final Map, Field> NBTTagFieldCache; + + private static Field NBTListData; + + private static Field NBTCompoundMap; + + private static final String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + + static { + classCache = new HashMap<>(); + try { + classCache.put("NBTBase", Class.forName("net.minecraft.server." + version + "." + "NBTBase")); + classCache.put("NBTTagCompound", Class.forName("net.minecraft.server." + version + "." + "NBTTagCompound")); + classCache.put("NBTTagList", Class.forName("net.minecraft.server." + version + "." + "NBTTagList")); + classCache.put("NBTBase", Class.forName("net.minecraft.server." + version + "." + "NBTBase")); + classCache.put("ItemStack", Class.forName("net.minecraft.server." + version + "." + "ItemStack")); + classCache.put("CraftItemStack", + Class.forName("org.bukkit.craftbukkit." + version + ".inventory." + "CraftItemStack")); + classCache.put("Entity", Class.forName("net.minecraft.server." + version + "." + "Entity")); + classCache.put("CraftEntity", + Class.forName("org.bukkit.craftbukkit." + version + ".entity." + "CraftEntity")); + classCache.put("EntityLiving", Class.forName("net.minecraft.server." + version + "." + "EntityLiving")); + classCache.put("CraftWorld", Class.forName("org.bukkit.craftbukkit." + version + "." + "CraftWorld")); + classCache.put("CraftBlockState", + Class.forName("org.bukkit.craftbukkit." + version + ".block." + "CraftBlockState")); + classCache.put("BlockPosition", Class.forName("net.minecraft.server." + version + "." + "BlockPosition")); + classCache.put("TileEntity", Class.forName("net.minecraft.server." + version + "." + "TileEntity")); + classCache.put("World", Class.forName("net.minecraft.server." + version + "." + "World")); + classCache.put("TileEntitySkull", + Class.forName("net.minecraft.server." + version + "." + "TileEntitySkull")); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + NBTClasses = new HashMap<>(); + try { + NBTClasses.put(Byte.class, Class.forName("net.minecraft.server." + version + "." + "NBTTagByte")); + NBTClasses.put(String.class, Class.forName("net.minecraft.server." + version + "." + "NBTTagString")); + NBTClasses.put(Double.class, Class.forName("net.minecraft.server." + version + "." + "NBTTagDouble")); + NBTClasses.put(Integer.class, Class.forName("net.minecraft.server." + version + "." + "NBTTagInt")); + NBTClasses.put(Long.class, Class.forName("net.minecraft.server." + version + "." + "NBTTagLong")); + NBTClasses.put(Short.class, Class.forName("net.minecraft.server." + version + "." + "NBTTagShort")); + NBTClasses.put(Float.class, Class.forName("net.minecraft.server." + version + "." + "NBTTagFloat")); + NBTClasses.put(Class.forName("[B"), + Class.forName("net.minecraft.server." + version + "." + "NBTTagByteArray")); + NBTClasses.put(Class.forName("[I"), + Class.forName("net.minecraft.server." + version + "." + "NBTTagIntArray")); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + methodCache = new HashMap<>(); + try { + methodCache.put("get", getNMSClass("NBTTagCompound").getMethod("get", new Class[] { String.class })); + methodCache.put("set", + getNMSClass("NBTTagCompound").getMethod("set", new Class[] { String.class, getNMSClass("NBTBase") })); + methodCache.put("hasKey", getNMSClass("NBTTagCompound").getMethod("hasKey", new Class[] { String.class })); + methodCache.put("setIndex", getNMSClass("NBTTagList").getMethod("a", new Class[] { int.class, getNMSClass("NBTBase") })); + methodCache.put("add", getNMSClass("NBTTagList").getMethod("add", new Class[] { getNMSClass("NBTBase") })); + methodCache.put("hasTag", getNMSClass("ItemStack").getMethod("hasTag", new Class[0])); + methodCache.put("getTag", getNMSClass("ItemStack").getMethod("getTag", new Class[0])); + methodCache.put("setTag", getNMSClass("ItemStack").getMethod("setTag", new Class[] { getNMSClass("NBTTagCompound") })); + methodCache.put("asNMSCopy", getNMSClass("CraftItemStack").getMethod("asNMSCopy", new Class[] { ItemStack.class })); + methodCache.put("asBukkitCopy", + getNMSClass("CraftItemStack").getMethod("asBukkitCopy", new Class[] { getNMSClass("ItemStack") })); + methodCache.put("getEntityHandle", getNMSClass("CraftEntity").getMethod("getHandle", new Class[0])); + methodCache.put("getEntityTag", getNMSClass("Entity").getMethod("c", new Class[] { getNMSClass("NBTTagCompound") })); + methodCache.put("setEntityTag", getNMSClass("Entity").getMethod("f", new Class[] { getNMSClass("NBTTagCompound") })); + if (version.contains("1_12") || version.contains("1_13")) { + methodCache.put("setTileTag", + getNMSClass("TileEntity").getMethod("load", new Class[] { getNMSClass("NBTTagCompound") })); + } else { + methodCache.put("setTileTag", getNMSClass("TileEntity").getMethod("a", new Class[] { getNMSClass("NBTTagCompound") })); + } + methodCache.put("getTileEntity", + getNMSClass("World").getMethod("getTileEntity", new Class[] { getNMSClass("BlockPosition") })); + methodCache.put("getWorldHandle", getNMSClass("CraftWorld").getMethod("getHandle", new Class[0])); + methodCache.put("setGameProfile", + getNMSClass("TileEntitySkull").getMethod("setGameProfile", new Class[] { GameProfile.class })); + } catch (Exception e) { + e.printStackTrace(); + } + try { + methodCache.put("getTileTag", getNMSClass("TileEntity").getMethod("save", new Class[] { getNMSClass("NBTTagCompound") })); + } catch (NoSuchMethodException exception) { + try { + methodCache.put("getTileTag", getNMSClass("TileEntity").getMethod("b", new Class[] { getNMSClass("NBTTagCompound") })); + } catch (Exception exception2) { + exception2.printStackTrace(); + } + } catch (Exception exception) { + exception.printStackTrace(); + } + constructorCache = new HashMap<>(); + try { + constructorCache.put(getNBTTag(Byte.class), getNBTTag(Byte.class).getConstructor(new Class[] { byte.class })); + constructorCache.put(getNBTTag(String.class), getNBTTag(String.class).getConstructor(new Class[] { String.class })); + constructorCache.put(getNBTTag(Double.class), getNBTTag(Double.class).getConstructor(new Class[] { double.class })); + constructorCache.put(getNBTTag(Integer.class), getNBTTag(Integer.class).getConstructor(new Class[] { int.class })); + constructorCache.put(getNBTTag(Long.class), getNBTTag(Long.class).getConstructor(new Class[] { long.class })); + constructorCache.put(getNBTTag(Float.class), getNBTTag(Float.class).getConstructor(new Class[] { float.class })); + constructorCache.put(getNBTTag(Short.class), getNBTTag(Short.class).getConstructor(new Class[] { short.class })); + constructorCache.put(getNBTTag(Class.forName("[B")), + getNBTTag(Class.forName("[B")).getConstructor(new Class[] { Class.forName("[B") })); + constructorCache.put(getNBTTag(Class.forName("[I")), + getNBTTag(Class.forName("[I")).getConstructor(new Class[] { Class.forName("[I") })); + constructorCache.put(getNMSClass("BlockPosition"), + getNMSClass("BlockPosition").getConstructor(new Class[] { int.class, int.class, int.class })); + } catch (Exception e) { + e.printStackTrace(); + } + NBTTagFieldCache = new HashMap<>(); + try { + for (Class clazz : NBTClasses.values()) { + Field data = clazz.getDeclaredField("data"); + data.setAccessible(true); + NBTTagFieldCache.put(clazz, data); + } + } catch (Exception e) { + e.printStackTrace(); + } + try { + NBTListData = getNMSClass("NBTTagList").getDeclaredField("list"); + NBTListData.setAccessible(true); + NBTCompoundMap = getNMSClass("NBTTagCompound").getDeclaredField("map"); + NBTCompoundMap.setAccessible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Class getPrimitiveClass(Class clazz) { + return Primitives.unwrap(clazz); + } + + public static Class getNBTTag(Class primitiveType) { + if (NBTClasses.containsKey(primitiveType)) + return NBTClasses.get(primitiveType); + return primitiveType; + } + + public static Object getNBTVar(Object object) { + if (object == null) + return null; + Class clazz = object.getClass(); + try { + if (NBTTagFieldCache.containsKey(clazz)) + return ((Field)NBTTagFieldCache.get(clazz)).get(object); + } catch (Exception exception) { + exception.printStackTrace(); + } + return null; + } + + public static Method getMethod(String name) { + return methodCache.containsKey(name) ? methodCache.get(name) : null; + } + + public static Constructor getConstructor(Class clazz) { + return constructorCache.containsKey(clazz) ? constructorCache.get(clazz) : null; + } + + public static Class getNMSClass(String name) { + if (classCache.containsKey(name)) + return classCache.get(name); + try { + return Class.forName("net.minecraft.server." + version + "." + name); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + public static Object getItemTag(ItemStack item, Object... keys) { + if (item == null) + return null; + try { + Object stack = null; + stack = getMethod("asNMSCopy").invoke(null, new Object[] { item }); + Object tag = null; + if (getMethod("hasTag").invoke(stack, new Object[0]).equals(Boolean.valueOf(true))) { + tag = getMethod("getTag").invoke(stack, new Object[0]); + } else { + tag = getNMSClass("NBTTagCompound").newInstance(); + } + return getTag(tag, keys); + } catch (Exception exception) { + exception.printStackTrace(); + return null; + } + } + + public static ItemStack setItemTag(ItemStack item, Object value, Object... keys) { + if (item == null) + return null; + try { + Object stack = getMethod("asNMSCopy").invoke(null, new Object[] { item }); + Object tag = null; + if (getMethod("hasTag").invoke(stack, new Object[0]).equals(Boolean.valueOf(true))) { + tag = getMethod("getTag").invoke(stack, new Object[0]); + } else { + tag = getNMSClass("NBTTagCompound").newInstance(); + } + setTag(tag, value, keys); + getMethod("setTag").invoke(stack, new Object[] { tag }); + return (ItemStack)getMethod("asBukkitCopy").invoke(null, new Object[] { stack }); + } catch (Exception exception) { + exception.printStackTrace(); + return null; + } + } + + private static void setTag(Object tag, Object value, Object... keys) throws Exception { + Object notCompound = getConstructor(getNBTTag(value.getClass())).newInstance(new Object[] { value }); + Object compound = tag; + for (int index = 0; index < keys.length; index++) { + Object key = keys[index]; + if (index + 1 == keys.length) { + if (key == null) { + getMethod("add").invoke(compound, new Object[] { notCompound }); + break; + } + if (key instanceof Integer) { + getMethod("setIndex").invoke(compound, new Object[] { Integer.valueOf(((Integer)key).intValue()), notCompound }); + break; + } + getMethod("set").invoke(compound, new Object[] { key, notCompound }); + break; + } + Object oldCompound = compound; + if (key instanceof Integer) { + compound = ((List)NBTListData.get(compound)).get(((Integer)key).intValue()); + } else if (key != null) { + compound = getMethod("get").invoke(compound, new Object[] { key }); + } + if (compound == null || key == null) { + if (keys[index + 1] == null || keys[index + 1] instanceof Integer) { + compound = getNMSClass("NBTTagList").newInstance(); + } else { + compound = getNMSClass("NBTTagCompound").newInstance(); + } + if (oldCompound.getClass().getSimpleName().equals("NBTTagList")) { + getMethod("add").invoke(oldCompound, new Object[] { compound }); + } else { + getMethod("set").invoke(oldCompound, new Object[] { key, compound }); + } + } + } + } + + private static Object getTag(Object tag, Object... keys) throws Exception { + if (keys.length == 0) + return getTags(tag); + Object notCompound = tag; + byte b; + int i; + Object[] arrayOfObject; + for (i = (arrayOfObject = keys).length, b = 0; b < i; ) { + Object key = arrayOfObject[b]; + if (notCompound == null) + return null; + if (getNMSClass("NBTTagCompound").isInstance(notCompound)) { + notCompound = getMethod("get").invoke(notCompound, new Object[] { key }); + } else if (getNMSClass("NBTTagList").isInstance(notCompound)) { + notCompound = ((List)NBTListData.get(notCompound)).get(((Integer)key).intValue()); + } else { + return getNBTVar(notCompound); + } + b++; + } + if (notCompound == null) + return null; + if (getNMSClass("NBTTagList").isInstance(notCompound)) + return getTags(notCompound); + if (getNMSClass("NBTTagCompound").isInstance(notCompound)) + return getTags(notCompound); + return getNBTVar(notCompound); + } + + private static Object getTags(Object tag) { + Map tags = new HashMap<>(); + try { + if (getNMSClass("NBTTagCompound").isInstance(tag)) { + Map tagCompound = (Map)NBTCompoundMap.get(tag); + for (String key : tagCompound.keySet()) { + Object value = tagCompound.get(key); + if (getNMSClass("NBTTagEnd").isInstance(value)) + continue; + tags.put(key, getTag(value, new Object[0])); + } + } else if (getNMSClass("NBTTagList").isInstance(tag)) { + List tagList = (List)NBTListData.get(tag); + for (int index = 0; index < tagList.size(); index++) { + Object value = tagList.get(index); + if (!getNMSClass("NBTTagEnd").isInstance(value)) + tags.put(Integer.valueOf(index), getTag(value, new Object[0])); + } + } else { + return getNBTVar(tag); + } + return tags; + } catch (Exception e) { + e.printStackTrace(); + return tags; + } + } +} diff --git a/RPS/src/main/java/net/crankedpvp/rps/utilities/Utils.java b/RPS/src/main/java/net/crankedpvp/rps/utilities/Utils.java new file mode 100644 index 0000000..2385f24 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/utilities/Utils.java @@ -0,0 +1,346 @@ +// =============================================== // +// Recompile disabled. Please run Recaf with a JDK // +// =============================================== // + +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.crankedpvp.rps.utilities; + +import com.google.common.primitives.Doubles; +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; +import org.apache.commons.lang.Validate; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.URL; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public final class Utils { + private Utils() { + throw new UnsupportedOperationException(); + } + + public static String convertSeconds(int input) { + Validate.isTrue(input > 0, "Why are you even trying to convert: " + input + "?"); + int days = (int)TimeUnit.SECONDS.toDays(input); + StringBuilder builder = new StringBuilder(days > 0 ? Utils.pluralize("^# day^s", days) : ""); + int hours = (int)(TimeUnit.SECONDS.toHours(input) - TimeUnit.DAYS.toHours(days)); + builder.append(hours > 0 ? (builder.toString().equals("") ? "" : ", ") + Utils.pluralize("^# hour^s", hours) : ""); + int minutes = (int)(TimeUnit.SECONDS.toMinutes(input) - TimeUnit.HOURS.toMinutes(hours) - TimeUnit.DAYS.toMinutes(days)); + builder.append(minutes > 0 ? (builder.toString().equals("") ? "" : ", ") + Utils.pluralize("^# minute^s", minutes) : ""); + int seconds = (int)(TimeUnit.SECONDS.toSeconds(input) - TimeUnit.MINUTES.toSeconds(minutes) - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.DAYS.toSeconds(days)); + builder.append(seconds > 0 ? (builder.toString().equals("") ? "" : ", ") + Utils.pluralize("^# second^s", seconds) : ""); + return builder.toString(); + } + + private static String pluralize(String text, int value) { + return text.replace("^s", value > 1 ? "s" : "").replace("^#", String.valueOf(value)); + } + + public static String getMachineIP() { + try { + return new BufferedReader(new InputStreamReader(new URL("http://checkip.amazonaws.com").openStream())).readLine(); + } + catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static boolean isDouble(String input) { + return Doubles.tryParse(StringUtils.deleteWhitespace(input)) != null; + } + + public static boolean isInt(String input) { + return Ints.tryParse(StringUtils.deleteWhitespace(input)) != null; + } + + public static boolean isLong(String input) { + return Longs.tryParse(StringUtils.deleteWhitespace(input)) != null; + } + + public static boolean isList(FileConfiguration file, String path) { + return Utils.isList(file.get(path)); + } + + public static boolean isList(Object obj) { + return obj instanceof ArrayList; + } + + public static void bcMsg(String input) { + Bukkit.broadcastMessage(Utils.colorize(input)); + } + + public static void bcMsg(List input) { + input.forEach(Utils::bcMsg); + } + + @Deprecated + public static void bcMsg(Object input) { + Utils.bcMsg(String.valueOf(input)); + } + + public static void msgConsole(String message) { + Bukkit.getConsoleSender().sendMessage(Utils.colorize(message)); + } + + public static void msgConsole(List message) { + message.forEach(Utils::msgConsole); + } + + public static void msg(CommandSender target, String message) { + Validate.notNull(target, "The commandsender can't be null"); + target.sendMessage(Utils.colorize(message)); + } + + public static void msg(CommandSender target, List message) { + Validate.notNull(target, "The commandsender can't be null"); + Utils.colorize(message).forEach(target::sendMessage); + } + + public static void msg(CommandSender target, String[] message) { + Validate.notNull(target, "The commandsender can't be null"); + target.sendMessage(Utils.colorize(message)); + } + + public static void msg(CommandSender target, String message, Map map, boolean ignoreCase) { + Utils.msg(target, Utils.placeHolder(message, map, ignoreCase)); + } + + public static void msg(CommandSender target, List message, Map map, boolean ignoreCase) { + Utils.msg(target, Utils.placeHolder(message, map, ignoreCase)); + } + + public static void msg(CommandSender target, String[] message, Map map, boolean ignoreCase) { + Utils.msg(target, Utils.placeHolder(message, map, ignoreCase)); + } + + public static void msg(CommandSender target, FileConfiguration file, String path) { + Utils.msg(target, null, false, file, path); + } + + public static void msg(CommandSender target, Map map, boolean replace, FileConfiguration file, String path) { + Validate.notNull(file, "The file can't be null"); + Validate.notNull(file, "The path can't be null"); + if (Utils.isList(file, path)) { + Utils.msg(target, file.getStringList(path), map, replace); + } else { + Utils.msg(target, file.getString(path), map, replace); + } + } + + public static String placeHolder(String str, Map map, boolean ignoreCase) { + Validate.notNull(str, "The string can't be null!"); + if (map == null) { + return str; + } + for (Map.Entry entr : map.entrySet()) { + String string = str = ignoreCase ? Utils.replaceIgnoreCase(str, entr.getKey(), entr.getValue()) : str.replace(entr.getKey(), entr.getValue()); + } + return str; + } + + public static String[] placeHolder(String[] array, Map map, boolean ignoreCase) { + Validate.notNull(array, "The string array can't be null!"); + Validate.noNullElements(array, "The string array can't have null elements!"); + String[] newarr = Arrays.copyOf(array, array.length); + if (map == null) { + return newarr; + } + int i = 0; + while (i < newarr.length) { + newarr[i] = Utils.placeHolder(newarr[i], map, ignoreCase); + ++i; + } + return newarr; + } + + public static List placeHolder(List coll, Map map, boolean ignoreCase) { + Validate.notNull(coll, "The string collection can't be null!"); + Validate.noNullElements(coll, "The string collection can't have null elements!"); + if (map == null) { + return coll; + } + return coll.stream().map(str -> Utils.placeHolder(str, map, ignoreCase)).collect(Collectors.toList()); + } + + public static boolean isStringAllowed(String message, boolean ignoreSpace) { + return ignoreSpace ? StringUtils.isAlphanumericSpace(message) : StringUtils.isAlphanumeric(message); + } + + public static String capitalize(String string, boolean reset) { + Validate.notNull(string, "Null string object can't be capitalized!"); + return StringUtils.capitalize(reset ? string.toLowerCase() : string); + } + + public static int getRandomInt(int lowerBound, int upperBound) { + Validate.isTrue(upperBound > lowerBound, "uppderBound should be > lowerBound, min: " + lowerBound + ", max: " + upperBound); + return ThreadLocalRandom.current().nextInt(lowerBound, upperBound + 1); + } + + public static String colorize(String msg) { + Validate.notNull(msg, "The string can't be null!"); + return ChatColor.translateAlternateColorCodes('&', msg); + } + + public static String[] colorize(String[] array) { + Validate.notNull(array, "The string array can't be null!"); + Validate.noNullElements(array, "The string array can't have null elements!"); + String[] newarr = Arrays.copyOf(array, array.length); + int i = 0; + while (i < newarr.length) { + newarr[i] = Utils.colorize(newarr[i]); + ++i; + } + return newarr; + } + + public static List colorize(List coll) { + Validate.notNull(coll, "The string collection can't be null!"); + Validate.noNullElements(coll, "The string collection can't have null elements!"); + coll.replaceAll(Utils::colorize); + return coll; + } + + public static String filterSpecialChars(String str) { + return Objects.isNull(str) || StringUtils.deleteWhitespace(str).equals("") ? str : str.replaceAll("[^a-zA-Z0-9 ]", ""); + } + + public static int getPlayerPing(CommandSender player) { + if (!(player instanceof Player)) { + return 0; + } + try { + Class craftPlayer = Class.forName("org.bukkit.craftbukkit." + Utils.getServerVersion() + ".entity.CraftPlayer"); + Object converted = craftPlayer.cast(player); + Method handle = converted.getClass().getMethod("getHandle"); + Object entityPlayer = handle.invoke(converted); + Field pingField = entityPlayer.getClass().getField("ping"); + return pingField.getInt(entityPlayer); + } + catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + private static String getServerVersion() { + String pkg; + String version; + Pattern brand = Pattern.compile("(v|)[0-9][_.][0-9][_.][R0-9]*"); + return brand.matcher(version = (pkg = Bukkit.getServer().getClass().getPackage().getName()).substring(pkg.lastIndexOf(46) + 1)).matches() ? version : null; + } + + public static Map addItems(Inventory inv, ItemStack ... items) { + ItemStack[] filteredItems = Stream.of(items).filter(Objects::nonNull).toArray(ItemStack[]::new); + return inv.addItem(filteredItems); + } + + public static String replaceIgnoreCase(String text, String searchString, String replacement) { + int start; + if (StringUtils.isEmpty(text) || StringUtils.isEmpty(searchString) || replacement == null) { + return text; + } + int max = -1; + String searchText = text.toLowerCase(); + int end = searchText.indexOf(searchString = searchString.toLowerCase(), start = 0); + if (end == -1) { + return text; + } + int replLength = searchString.length(); + int increase = replacement.length() - replLength; + increase = increase < 0 ? 0 : increase; + StringBuilder buf = new StringBuilder(text.length() + (increase *= 16)); + while (end != -1) { + buf.append(text, start, end).append(replacement); + start = end + replLength; + if (--max == 0) break; + end = searchText.indexOf(searchString, start); + } + return buf.append(text, start, text.length()).toString(); + } + + public static boolean isServerOld() { + String version = Bukkit.getVersion(); + return version.contains("1.8"); + } + + public static ItemStack getMainItem(Player player) { + ItemStack item = player.getItemInHand(); + return item == null || item.getType() == Material.AIR ? null : item; + } + + public static boolean isSimilar(ItemStack stack, ItemStack stack2, boolean durability) { + boolean a; + boolean bl = a = stack2.getType() == stack.getType() && stack2.hasItemMeta() == stack.hasItemMeta() && (!stack2.hasItemMeta() || Bukkit.getItemFactory().equals(stack2.getItemMeta(), stack.getItemMeta())); + return durability ? a : a && stack2.getDurability() == stack.getDurability(); + } + + public static String arrayToUpperCase(String name, String splitter) { + String[] split = StringUtils.splitByWholeSeparator(name, splitter); + StringBuilder buff = new StringBuilder(); + String[] stringArray = split; + int n = split.length; + int n2 = 0; + while (n2 < n) { + String str = stringArray[n2]; + buff.append(StringUtils.capitalize(str.toLowerCase()) + " "); + ++n2; + } + return buff.substring(0, buff.toString().length() - 1); + } + + public static void debug(JavaPlugin plugin, Map map, String ... messages) { + System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); + System.out.println(); + String name = plugin.getDescription().getName() + " "; + String desc = plugin.getDescription().getVersion(); + System.out.println(" " + name + desc); + System.out.println(); + String[] stringArray = messages; + int n = messages.length; + int n2 = 0; + while (n2 < n) { + String msg = stringArray[n2]; + System.err.println(Utils.placeHolder(msg, map, false)); + ++n2; + } + System.out.println(); + System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); + } + + public static void debug(JavaPlugin plugin, String ... messages) { + Utils.debug(plugin, null, messages); + } + + public static double round(double value, int places) { + if (places < 0) { + throw new IllegalArgumentException(); + } + BigDecimal bd = new BigDecimal(String.valueOf(value)); + bd = bd.setScale(places, RoundingMode.HALF_UP); + return bd.doubleValue(); + } +} + \ No newline at end of file diff --git a/RPS/src/main/java/net/crankedpvp/rps/utilities/VaultAPI.java b/RPS/src/main/java/net/crankedpvp/rps/utilities/VaultAPI.java new file mode 100644 index 0000000..e427909 --- /dev/null +++ b/RPS/src/main/java/net/crankedpvp/rps/utilities/VaultAPI.java @@ -0,0 +1,27 @@ +package net.crankedpvp.rps.utilities; + +import net.crankedpvp.rps.RPSPlugin; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.plugin.RegisteredServiceProvider; + +public class VaultAPI { + private final RPSPlugin core; + + private Economy economy; + + public VaultAPI(RPSPlugin core) { + this.core = core; + } + + public Economy getEconomy() { + return this.economy; + } + + public boolean setupEconomy() { + RegisteredServiceProvider economyProvider = this.core.getServer().getServicesManager() + .getRegistration(Economy.class); + if (economyProvider != null) + this.economy = (Economy)economyProvider.getProvider(); + return (this.economy != null); + } +} diff --git a/RPS/src/main/resources/options.yml b/RPS/src/main/resources/options.yml new file mode 100644 index 0000000..5eea8ba --- /dev/null +++ b/RPS/src/main/resources/options.yml @@ -0,0 +1,78 @@ +Inventory: + name: 'Viewing %amount% Wages' + items: + book: + name: '&a&lRPS Help' + lore: + - '' + - '&e/rps' + - '&7View all active RPS wagers.' + - '' + - '&e/rps ' + - '&7Start a RPS match with the set wager.' + - '' + - '&e/rps cancel' + - '&7Remove all your existing RPS matches.' + - '' + - '&e/rps stats ' + - '&7View your own or a player''s RPS stats.' + - '' + - '&e/rps top ' + - '&7View top users.' + - '' + - '&e/rps toggle' + - '&7Toggle incoming win/lose messages.' + - '' + +Top-Players: + Wins: + name: 'Top 9 Winners' + items: + name: '&7(#%rank%) %relation_color%%name% &l%faction%' + lore: + - '&7Stats' + - ' &7&l* &7Wins: &a%wins%' + - ' &7&l* &7Losses: &c%losses%' + - ' &7&l* &7Ratio: &6%ratio%' + Losses: + name: 'Top 9 Losses' + items: + name: '&7(#%rank%) %relation_color%%name% &l%faction%' + lore: + - '&7Stats' + - ' &7&l* &7Wins: &a%wins%' + - ' &7&l* &7Losses: &c%losses%' + - ' &7&l* &7Ratio: &6%ratio%' + +Prices: + minimum: 1 + maximum: 100000000000 + +Heads: + operator: + name: '&r%relation_color%%name% &l%faction%' + lore: + - '' + - '&e&lWager' + - ' &7$%money%' + - '' + - '&e&lChosen' + - ' &6%rps%' + - '' + - '&e&lStats' + - '&7 Wins &a%wins%' + - '&7 Losses &c%losses%' + - '' + - '&r%enterable%' + normal: + name: '&r%relation_color%%name% &l%faction%' + lore: + - '' + - '&e&lWager' + - ' &7$%money%' + - '' + - '&e&lStats' + - '&7 Wins &a%wins%' + - '&7 Losses &c%losses%' + - '' + - '&r%enterable%' \ No newline at end of file diff --git a/RPS/src/main/resources/playerbase.yml b/RPS/src/main/resources/playerbase.yml new file mode 100644 index 0000000..ace0e4a --- /dev/null +++ b/RPS/src/main/resources/playerbase.yml @@ -0,0 +1 @@ +Players: {} \ No newline at end of file diff --git a/RPS/src/main/resources/plugin.yml b/RPS/src/main/resources/plugin.yml new file mode 100644 index 0000000..5a74517 --- /dev/null +++ b/RPS/src/main/resources/plugin.yml @@ -0,0 +1,9 @@ +main: net.crankedpvp.rps.RPSPlugin +name: CrankedRockPaperScissors +version: ${git.total.commit.count}.0 +depend: [Factions, Vault] +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +commands: + rps: + diff --git a/RPS/src/main/resources/rps.yml b/RPS/src/main/resources/rps.yml new file mode 100644 index 0000000..e978f66 --- /dev/null +++ b/RPS/src/main/resources/rps.yml @@ -0,0 +1 @@ +Bets: {} \ No newline at end of file diff --git a/Revive/pom.xml b/Revive/pom.xml new file mode 100644 index 0000000..83bb2e0 --- /dev/null +++ b/Revive/pom.xml @@ -0,0 +1,52 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Revive + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + Collect + net.crankedpvp + + + net.crankedpvp + Enchants + + + net.crankedpvp + Masks + + + net.crankedpvp + StarItems + + + net.crankedpvp + Armor + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + \ No newline at end of file diff --git a/Revive/src/main/java/net/crankedpvp/revive/CrankedRevivePlugin.java b/Revive/src/main/java/net/crankedpvp/revive/CrankedRevivePlugin.java new file mode 100644 index 0000000..20fbfc4 --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/CrankedRevivePlugin.java @@ -0,0 +1,51 @@ +package net.crankedpvp.revive; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import net.crankedpvp.revive.commands.ReviveCommand; +import net.crankedpvp.revive.listeners.PlayerDeathListener; +import net.crankedpvp.revive.managers.AdminLogManager; +import net.crankedpvp.revive.managers.ReviveManager; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.plugin.java.JavaPlugin; + +@Getter +public class CrankedRevivePlugin extends JavaPlugin { + @Getter + public static CrankedRevivePlugin instance; + @Getter + private ReviveManager reviveManager; + private AdminLogManager adminLogManager; + private CommandManager commandManager; + + public void onEnable() { + instance = this; + this.reviveManager = new ReviveManager(); + this.adminLogManager = new AdminLogManager(this); + this.adminLogManager.load(); + //this.reviveManager.loadAll(); + this.commandManager = new CommandManager(this, true); + registerCommandParameters(); + commandManager.register(new ReviveCommand(this)); + PluginUtils.registerListeners(this, new PlayerDeathListener(this)); + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, () -> { + this.reviveManager.saveAll(); + }, 60L, 10 * 20 * 60); + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(OfflinePlayer.class, argument -> { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer((String) argument); + return new TypeResult(offlinePlayer, argument); + }); + } + + public void onDisable() { + this.adminLogManager.save(); + this.reviveManager.saveAll(); + instance = null; + } +} diff --git a/Revive/src/main/java/net/crankedpvp/revive/commands/ReviveCommand.java b/Revive/src/main/java/net/crankedpvp/revive/commands/ReviveCommand.java new file mode 100644 index 0000000..dd800f5 --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/commands/ReviveCommand.java @@ -0,0 +1,51 @@ +package net.crankedpvp.revive.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.revive.CrankedRevivePlugin; +import net.crankedpvp.revive.data.ReviveUser; +import net.crankedpvp.revive.inventories.ReviveGUI; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("revive") +@Alias({"rev", "revives"}) +public class ReviveCommand extends CommandBase { + + private CrankedRevivePlugin plugin; + public ReviveCommand(CrankedRevivePlugin plugin) { + this.plugin = plugin; + } + + @Default + @WrongUsage("/revive ") + @Permission({"revive.command", "cranked.admin"}) + public void onReviveCommand(CommandSender sender, @Completion("#players") OfflinePlayer player) { + Player pSender = (Player)sender; + pSender.sendMessage(CC.translate("&d&lRevive &8" + Arrow.arrow() + " &7Revive data for &d" + player.getName() + " &7is being loaded...")); + ReviveUser reviveUser = this.plugin.getReviveManager().getReviveUser(player.getUniqueId()); + long started = System.currentTimeMillis(); + pSender.sendMessage(CC.translate("&d&lRevive &8" + Arrow.arrow() + " &7Revive data for &d" + player.getName() + " &7was loaded in &d" + (System.currentTimeMillis() - started) + "ms")); + ReviveGUI reviveGUI = new ReviveGUI(reviveUser); + reviveGUI.getReviveGUI().open(pSender); + } + + @SubCommand("logs") + @Permission("cranked.admin") + public void viewReviveLogsCommand(final CommandSender commandSender) { + commandSender.sendMessage(CC.translate("&6Cranked &eRevive Logs")); + for(String log : this.plugin.getAdminLogManager().getLogs()) { + commandSender.sendMessage(CC.translate(" &f&l* " + log)); + } + } + + @SubCommand("clearlogs") + @Permission("cranked.admin") + public void clearReviveLogsCommand(final CommandSender commandSender) { + commandSender.sendMessage(CC.translate("&aCLEARED LOGS.")); + this.plugin.getAdminLogManager().clear(); + } +} diff --git a/Revive/src/main/java/net/crankedpvp/revive/data/ReviveLog.java b/Revive/src/main/java/net/crankedpvp/revive/data/ReviveLog.java new file mode 100644 index 0000000..9ee8496 --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/data/ReviveLog.java @@ -0,0 +1,61 @@ +package net.crankedpvp.revive.data; + +import lombok.Getter; +import net.crankedpvp.collect.CollectPlugin; +import net.crankedpvp.collect.struct.CollectCategory; +import net.crankedpvp.collect.struct.CollectType; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.revive.CrankedRevivePlugin; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.UUID; + +@Getter +public class ReviveLog implements Serializable { + private final UUID uuid; + private final long time; + private final List items; + private String killerName; + private final double lastDamage; + private final Location location; + + private final SetData setData; + + public ReviveLog(UUID uuid, long time, List items, double lastDamage, Location location, SetData setData) { + this.uuid = uuid; + this.time = time; + this.items = items; + this.lastDamage = lastDamage; + this.location = location; + this.setData = setData; + } + + public void setKiller(String killerName) { + this.killerName = killerName; + } + + public void revivePlayer(Player whoRevived) { + DateTimeFormatter formattedDate = DateTimeFormatter.ofPattern("EEE, MMM dd | HH:mm"); + LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("America/New_York")); + String date = localDateTime.format(formattedDate); + if(CrankedRevivePlugin.getInstance().getReviveManager().getReviveUser(uuid).getPlayer() != null) { + CrankedRevivePlugin.getInstance().getReviveManager().getReviveUser(uuid).getPlayer().sendMessage(CC.translate("&a&l(!)&a A revive inventory has been added to your /collect")); + whoRevived.sendMessage(CC.translate("&a&l(!)&a Successfully revived " + CrankedRevivePlugin.getInstance().getReviveManager().getReviveUser(uuid).getPlayer().getName())); + } else { + whoRevived.sendMessage(CC.translate("&a&l(!)&a Successfully revived " + CrankedRevivePlugin.getInstance().getReviveManager().getReviveUser(uuid).getUuid())); + } + CrankedRevivePlugin.getInstance().getReviveManager().getReviveUser(uuid).getReviveLogs().remove(this); + CollectPlugin.getInstance().getCollectManager().getOrCreate(uuid.toString()).add(new CollectCategory(CollectType.REVIVE, items.toArray(new ItemStack[items.size() - 1]), "&c&lRevive Inventory &c&l(&7" + date + " EST&c&l)", System.currentTimeMillis())); + CrankedRevivePlugin.getInstance().getAdminLogManager().addLog("&fRevived: &c" + Bukkit.getOfflinePlayer(this.uuid).getName() + "&7, " + "&fBy: &a" + whoRevived.getName() + "&7, " + "&fAt: &7" + localDateTime.format(formattedDate)); + } + + +} diff --git a/Revive/src/main/java/net/crankedpvp/revive/data/ReviveUser.java b/Revive/src/main/java/net/crankedpvp/revive/data/ReviveUser.java new file mode 100644 index 0000000..cd9b39e --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/data/ReviveUser.java @@ -0,0 +1,39 @@ +package net.crankedpvp.revive.data; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.storageutils.utils.KeyToSave; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Getter +public class ReviveUser implements KeyToSave { + private UUID uuid; + private final List reviveLogs; + + public ReviveUser(UUID uuid) { + this.uuid = uuid; + reviveLogs = new ArrayList<>(); + } + + public Player getPlayer() { + return Bukkit.getPlayer(uuid); + } + + @Override + public String getKey() { + return uuid.toString(); + } + + @Override + public void setKey(String key) { + this.uuid = UUID.fromString(key); + } +} diff --git a/Revive/src/main/java/net/crankedpvp/revive/data/SetData.java b/Revive/src/main/java/net/crankedpvp/revive/data/SetData.java new file mode 100644 index 0000000..749a042 --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/data/SetData.java @@ -0,0 +1,40 @@ +package net.crankedpvp.revive.data; + +import lombok.Getter; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedenchants.CrankedEnchantsAPI; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedmasks.struct.Mask; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.entity.Player; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +@Getter +public class SetData implements Serializable { + + private List masks; + private List starItems; + private String armorSet; + private int armorEnchantments; + + public SetData() {} + + public void buildSetDataFromPlayer(Player player) { + + this.armorEnchantments = (CrankedEnchantsAPI.getEnchantments(player) == null || CrankedEnchantsAPI.getEnchantments(player).isEmpty()) ? 0 : CrankedEnchantsAPI.getEnchantments(player).size(); + if(ItemUtils.isHelmet(player.getInventory().getHelmet())) { + List masks = CrankedMasksAPI.getMasksOnItem(player.getInventory().getHelmet()); + this.masks = (masks == null || masks.isEmpty()) ? new ArrayList<>() : Objects.requireNonNull(CrankedMasksAPI.getMasksOnItem(player.getInventory().getHelmet())).stream().map(Mask::getName).collect(Collectors.toList()); + } + this.armorSet = (CrankedArmorAPI.getCurrentArmorSet(player) == null) ? "none" : Objects.requireNonNull(CrankedArmorAPI.getCurrentArmorSet(player)).getName(); + this.starItems = (StarItemsAPI.getStarItemFromCache(player) == null || StarItemsAPI.getStarItemFromCache(player).isEmpty()) ? new ArrayList<>() : StarItemsAPI.getStarItemFromCache(player).stream().map(StarItem::getName).collect(Collectors.toList()); + } + +} diff --git a/Revive/src/main/java/net/crankedpvp/revive/inventories/ReviveGUI.java b/Revive/src/main/java/net/crankedpvp/revive/inventories/ReviveGUI.java new file mode 100644 index 0000000..2d0457d --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/inventories/ReviveGUI.java @@ -0,0 +1,109 @@ +package net.crankedpvp.revive.inventories; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.revive.CrankedRevivePlugin; +import net.crankedpvp.revive.data.ReviveLog; +import net.crankedpvp.revive.data.ReviveUser; +import net.crankedpvp.revive.data.SetData; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +@Getter +public class ReviveGUI { + private final PaginatedGui reviveGUI; + private final DateTimeFormatter DATE_FORMATED = DateTimeFormatter.ofPattern("EEE, MMM dd | HH:mm"); + + public ReviveGUI(ReviveUser reviveUser) { + + if (reviveUser.getPlayer() != null) { + this.reviveGUI = new PaginatedGui(6, 45, Bukkit.getPlayer(reviveUser.getUuid()).getName() + "'s Revive Menu"); + } else { + this.reviveGUI = new PaginatedGui(6, 45, reviveUser.getUuid().toString() + " Revive Menu"); + } + this.reviveGUI.setDefaultClickAction(event -> event.setCancelled(true)); + + for (ReviveLog reviveLog : reviveUser.getReviveLogs()) { + + Instant instant = Instant.ofEpochMilli(reviveLog.getTime()); + ZonedDateTime currentDateTime = instant.atZone(ZoneId.of("America/New_York")); + String reviveLogDate = currentDateTime.format(DATE_FORMATED); + + + SetData setData = reviveLog.getSetData(); + if (setData == null) continue; + Location loc = reviveLog.getLocation(); + ItemStack reviveLogItem = new ItemBuilder(Material.ENDER_CHEST, "&c&lRevive Inventory &c&l(&7" + reviveLogDate + " EST&c&l)") + .addLoreLine("") + .addLoreLine("&c&lDeath Information") + .addLoreLine(" &c&l• &7Killer: &f" + reviveLog.getKillerName()) + .addLoreLine(" &c&l• &7World: &f" + loc.getWorld().getName()) + .addLoreLine(" &c&l• &7Location: &fx: " + Math.round(loc.getX()) + ", y: " + Math.round(loc.getY()) + ", z: " + Math.round(loc.getZ())) + .addLoreLine(" &c&l• &7Last Damage: &f" + reviveLog.getLastDamage()) + .addLoreLine(" &c&l• &7Items: &f" + reviveLog.getItems().size()) + .addLoreLine(" &c&l• &7Died: &f" + getHowLongAgoTheDeathWas(reviveLog) + " Ago") + .addLoreLine("") + .addLoreLine("&c&lCache Information") + .addLoreLine(" &c&l• &7Armor Set: &f" + setData.getArmorSet()) + .addLoreLine(" &c&l• &7Star Items: &f" + String.join(", ", setData.getStarItems())) + .addLoreLine(" &c&l• &7Masks: &f" + ((setData.getMasks() == null || setData.getMasks().isEmpty()) ? "None" : String.join(", ", setData.getMasks()))) + .addLoreLine(" &c&l• &7Enchants: &f" + setData.getArmorEnchantments()) + .addLoreLine("") + .addLoreLine("&7&nRight-Click&7 to view revive items.") + .addLoreLine("&7&nSHIFT&7 + &7&nLeft-Click&7 to revive this player.") + .colorize() + .build(); + this.reviveGUI.addItem(new GuiItem(reviveLogItem, event -> { + if (event.isShiftClick() && event.isLeftClick()) { + reviveLog.revivePlayer((Player) event.getWhoClicked()); + ReviveGUI reviveGUI = new ReviveGUI(CrankedRevivePlugin.getInstance().getReviveManager().getReviveUser(reviveLog.getUuid())); + reviveGUI.getReviveGUI().open(event.getWhoClicked()); + } else { + RevivePreviewGUI revivePreviewGUI = new RevivePreviewGUI(reviveLog); + revivePreviewGUI.getRevivePreviewGUI().open(event.getWhoClicked()); + } + })); + } + this.reviveGUI.getFiller().fillBottom(new GuiItem(createFillerItem())); + + reviveGUI.setItem(6, 1, new GuiItem(createPreviousItem(), event -> { + reviveGUI.previous(); + event.setCancelled(true); + })); + + reviveGUI.setItem(6, 9, new GuiItem(createNextItem(), event -> { + reviveGUI.next(); + event.setCancelled(true); + })); + + } + + private String getHowLongAgoTheDeathWas(ReviveLog reviveLog) { + long longAgo = System.currentTimeMillis() - reviveLog.getTime(); + return TimeUtils.formatMilliseconds(longAgo); + } + + public ItemStack createPreviousItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&c<- Previous Page"), "&7Right-Click&7 to go to the previous page.").colorize().build(); + } + public ItemStack createNextItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&aNext Page ->"), "&7Right-Click&7 to go to the next page.").colorize().build(); + + } + public ItemStack createFillerItem() { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData())).setName("&7").colorize().build(); + } +} diff --git a/Revive/src/main/java/net/crankedpvp/revive/inventories/RevivePreviewGUI.java b/Revive/src/main/java/net/crankedpvp/revive/inventories/RevivePreviewGUI.java new file mode 100644 index 0000000..5580e38 --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/inventories/RevivePreviewGUI.java @@ -0,0 +1,44 @@ +package net.crankedpvp.revive.inventories; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.revive.CrankedRevivePlugin; +import net.crankedpvp.revive.data.ReviveLog; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +@Getter +public class RevivePreviewGUI { + private PaginatedGui revivePreviewGUI; + + public RevivePreviewGUI(ReviveLog reviveLog) { + this.revivePreviewGUI = new PaginatedGui(6, 54, "Revive Items Preview"); + this.revivePreviewGUI.setDefaultClickAction(event -> event.setCancelled(true)); + + for (ItemStack item : reviveLog.getItems()) { + this.revivePreviewGUI.addItem(new GuiItem(item)); + } + + this.revivePreviewGUI.getFiller().fillBottom(new GuiItem(createFillerItem())); + + revivePreviewGUI.setItem(6, 1, new GuiItem(createPreviousItem(), event -> { + ReviveGUI reviveGUI = new ReviveGUI(CrankedRevivePlugin.getInstance().getReviveManager().getReviveUser(reviveLog.getUuid())); + reviveGUI.getReviveGUI().open(event.getWhoClicked()); + event.setCancelled(true); + })); + + + } + + public ItemStack createPreviousItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&c<- Go Back"), "&7Right-Click&7 to go back.").colorize().build(); + } + + public ItemStack createFillerItem() { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData())).setName("&7").colorize().build(); + } +} \ No newline at end of file diff --git a/Revive/src/main/java/net/crankedpvp/revive/listeners/PlayerDeathListener.java b/Revive/src/main/java/net/crankedpvp/revive/listeners/PlayerDeathListener.java new file mode 100644 index 0000000..be36173 --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/listeners/PlayerDeathListener.java @@ -0,0 +1,42 @@ +package net.crankedpvp.revive.listeners; + +import net.crankedpvp.revive.CrankedRevivePlugin; +import net.crankedpvp.revive.data.ReviveLog; +import net.crankedpvp.revive.data.SetData; +import net.crankedpvp.revive.managers.AdminLogManager; +import net.crankedpvp.revive.managers.ReviveManager; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class PlayerDeathListener implements Listener { + private final List blockedWorlds = Arrays.asList("tournament_world", "event_world"); + private final ReviveManager reviveManager; + private final AdminLogManager adminLogManager; + + public PlayerDeathListener(CrankedRevivePlugin plugin) { + this.reviveManager = plugin.getReviveManager(); + this.adminLogManager = plugin.getAdminLogManager(); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerDeath(PlayerDeathEvent event) { + if (event.getDrops().isEmpty()) return; + final List items = new ArrayList<>(event.getDrops()); + items.removeIf(itemStack -> itemStack.getType() == Material.POTION); + SetData setData = new SetData(); + setData.buildSetDataFromPlayer(event.getEntity()); + if (blockedWorlds.contains(event.getEntity().getLocation().getWorld().getName())) return; + ReviveLog reviveLog = new ReviveLog(event.getEntity().getUniqueId(), System.currentTimeMillis(), items, event.getEntity().getLastDamage(), event.getEntity().getLocation(), setData); + reviveLog.setKiller(event.getEntity().getKiller() == null ? "Unknown" : event.getEntity().getKiller().getName()); + reviveManager.addReviveLog(event.getEntity().getUniqueId(), reviveLog); + } + +} diff --git a/Revive/src/main/java/net/crankedpvp/revive/managers/AdminLogManager.java b/Revive/src/main/java/net/crankedpvp/revive/managers/AdminLogManager.java new file mode 100644 index 0000000..5a6fce3 --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/managers/AdminLogManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.revive.managers; + +import lombok.Getter; +import net.crankedpvp.revive.CrankedRevivePlugin; + +import java.util.ArrayList; +import java.util.List; + +public class AdminLogManager { + + @Getter + private final List logs; + private final CrankedRevivePlugin plugin; + + public AdminLogManager(CrankedRevivePlugin plugin) { + this.plugin = plugin; + this.logs = new ArrayList<>(); + } + + public void addLog(String string) { + this.logs.add(string); + } + + public void save() { + this.plugin.getConfig().set("logs", this.logs); + this.plugin.saveConfig(); + } + + public void load() { + if(!this.plugin.getConfig().contains("logs")) return; + this.plugin.getConfig().getStringList("logs").forEach(this::addLog); + } + + public void clear() { + this.logs.clear(); + this.plugin.getConfig().set("logs", null); + } +} diff --git a/Revive/src/main/java/net/crankedpvp/revive/managers/ReviveManager.java b/Revive/src/main/java/net/crankedpvp/revive/managers/ReviveManager.java new file mode 100644 index 0000000..a7d5f96 --- /dev/null +++ b/Revive/src/main/java/net/crankedpvp/revive/managers/ReviveManager.java @@ -0,0 +1,44 @@ +package net.crankedpvp.revive.managers; + +import lombok.Getter; +import net.crankedpvp.revive.CrankedRevivePlugin; +import net.crankedpvp.revive.data.ReviveLog; +import net.crankedpvp.revive.data.ReviveUser; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; + +import java.io.File; +import java.util.UUID; + +@Getter +public class ReviveManager extends SaveLoadManager { + + private final static String dataFolder = "/data"; + + public ReviveManager() { + super(CrankedRevivePlugin.getInstance(), StorageUtils.getInstance().getGson(), dataFolder, ReviveUser.class); + } + + public void addReviveLog(UUID uuid, ReviveLog reviveLog) { + getReviveUser(uuid).getReviveLogs().add(reviveLog); + } + + + public ReviveUser getReviveUser(UUID key) { + if (!containsKey(key.toString())) { + + File file = new File(CrankedRevivePlugin.getInstance().getDataFolder() + dataFolder, key + ".json"); + if(file.exists()) { + super.load(file); + } else { + if (!containsKey(key.toString())) { + addToCache(new ReviveUser(key)); + } + } + + } + + return getFromCache(key.toString()); + } + +} diff --git a/Revive/src/main/resources/adminlogs.yml b/Revive/src/main/resources/adminlogs.yml new file mode 100644 index 0000000..e69de29 diff --git a/Revive/src/main/resources/plugin.yml b/Revive/src/main/resources/plugin.yml new file mode 100644 index 0000000..4c279f3 --- /dev/null +++ b/Revive/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedRevive +main: net.crankedpvp.revive.CrankedRevivePlugin +version: 1.0 +depend: + - StorageUtil + - CrankedUtils + - CrankedCollect diff --git a/Scoreboard/pom.xml b/Scoreboard/pom.xml new file mode 100644 index 0000000..e96d32e --- /dev/null +++ b/Scoreboard/pom.xml @@ -0,0 +1,57 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Scoreboard + + + 8 + 8 + + + + + net.crankedpvp + tab-api + 0.1 + system + ${project.basedir}/../.lib/TAB.v3.1.2.jar + + + com.massivecraft + Factions + + + Shards + net.crankedpvp + + + Underworld + net.crankedpvp + + + Utils + net.crankedpvp + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + Spawners + net.crankedpvp + 1.0 + + + + \ No newline at end of file diff --git a/Scoreboard/src/main/java/net/crankedpvp/scoreboard/CrankedScoreboardPlugin.java b/Scoreboard/src/main/java/net/crankedpvp/scoreboard/CrankedScoreboardPlugin.java new file mode 100644 index 0000000..793f889 --- /dev/null +++ b/Scoreboard/src/main/java/net/crankedpvp/scoreboard/CrankedScoreboardPlugin.java @@ -0,0 +1,98 @@ +package net.crankedpvp.scoreboard; + +import com.massivecraft.factions.FPlayers; +import lombok.Getter; +import me.neznamy.tab.api.TabAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.underworld.UnderworldPlugin; +import net.crankedpvp.underworld.utils.WaveSpawnerUtils; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +@Getter +public class CrankedScoreboardPlugin extends JavaPlugin { + + @Getter + private static CrankedScoreboardPlugin instance; + private final DateFormat format = new SimpleDateFormat("MM/dd"); + + + public void onEnable() { + instance = this; + registerFactionScoreboard(); + } + + public void onDisable() { + instance = null; + } + + public void registerFactionScoreboard() { + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%underworld-essence%", getMS(5), player -> NumberUtils.formatNum(UnderworldPlugin.getInstance().getUnderworldPlayerManager().getOrCreate(player.getUniqueId()).getEssence())); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%underworld-level%", getMS(5), player -> UnderworldPlugin.getInstance().getUnderworldPlayerManager().getOrCreate(player.getUniqueId()).getLevel()); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%underworld-tier%", getMS(5), player -> WaveSpawnerUtils.getTierFromLevel(UnderworldPlugin.getInstance().getUnderworldPlayerManager().getOrCreate(player.getUniqueId()).getLevel()).getRomanNumber()); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%underworld-tier-color%", getMS(5), player -> WaveSpawnerUtils.getTierFromLevel(UnderworldPlugin.getInstance().getUnderworldPlayerManager().getOrCreate(player.getUniqueId()).getLevel()).getColor()); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%underworld-exp%", getMS(5), player -> NumberUtils.formatNum(UnderworldPlugin.getInstance().getUnderworldPlayerManager().getOrCreate(player.getUniqueId()).getExp())); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%underworld-required-exp%", getMS(5), player -> NumberUtils.formatNum(UnderworldPlugin.getInstance().getUnderworldLevelManager().getFromCache(UnderworldPlugin.getInstance().getUnderworldPlayerManager().getOrCreate(player.getUniqueId()).getLevel() + 1).getRequiredExp())); + + + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%has-faction%", getMS(1), player -> !FPlayers.getInstance().getByPlayer((Player) player.getPlayer()).getFaction().isWilderness()); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%kills%", getMS(5), player -> FPlayers.getInstance().getByPlayer((Player) player.getPlayer()).getKills()); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%deaths%", getMS(5), player -> FPlayers.getInstance().getByPlayer((Player) player.getPlayer()).getDeaths()); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%kdr%", getMS(5), player -> getPlayerKDR((Player) player.getPlayer())); + TabAPI.getInstance().getPlaceholderManager().registerServerPlaceholder("%date%", getMS(1), this::getDateSuffix); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%shards%", getMS(1), player -> NumberUtils.formatMoney(ShardsPlugin.getInstance().getShardsManager().getShardsUser(player.getUniqueId()).getBalance())); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%ftop%", getMS(30), player -> SpawnerPlugin.getInstance().getFactionsTopManager().getFactionTop(FPlayers.getInstance().getByPlayer((Player) player.getPlayer()).getFaction())); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%ping%", getMS(1), player -> PlayerUtils.getSpoofedPing((Player) player.getPlayer())); + TabAPI.getInstance().getPlaceholderManager().registerPlayerPlaceholder("%health-with-absorption%", 50, player -> { + Player actualPlayer = (Player) player.getPlayer(); + return actualPlayer.getHealth() + ((CraftPlayer)actualPlayer).getHandle().getAbsorptionHearts(); + }); + + } + + public int getMS(int seconds) { + return seconds * 1000; + } + + public String getDateSuffix() { + return format.format(new Date()); + } + + public String getPlayerKDR(Player player) { + double kdr; + double kills = FPlayers.getInstance().getByPlayer(player.getPlayer()).getKills(); + double deaths = FPlayers.getInstance().getByPlayer(player.getPlayer()).getDeaths(); + + if (deaths == 0) { + kdr = kills; + } else { + kdr = kills / deaths; + } + + if (kdr < 1) { + return CC.translate("&c" + round(kdr, 2)); + + } + return CC.translate("&a" + round(kdr, 2)); + + } + + public static double round(double value, int places) { + if (places < 0) throw new IllegalArgumentException(); + + long factor = (long) Math.pow(10, places); + value = value * factor; + long tmp = Math.round(value); + return (double) tmp / factor; + } + +} diff --git a/Scoreboard/src/main/resources/plugin.yml b/Scoreboard/src/main/resources/plugin.yml new file mode 100644 index 0000000..20cd203 --- /dev/null +++ b/Scoreboard/src/main/resources/plugin.yml @@ -0,0 +1,5 @@ +main: net.crankedpvp.scoreboard.CrankedScoreboardPlugin +name: CrankedScoreboard +depend: + - TAB +version: 1.0 \ No newline at end of file diff --git a/Shards/pom.xml b/Shards/pom.xml new file mode 100644 index 0000000..c2718a7 --- /dev/null +++ b/Shards/pom.xml @@ -0,0 +1,41 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Shards + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + EssentialsX + net.ess3 + + + net.crankedpvp + Leaderboards + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/Shards/src/main/java/net/crankedpvp/shards/ShardsAPI.java b/Shards/src/main/java/net/crankedpvp/shards/ShardsAPI.java new file mode 100644 index 0000000..fcfd1f2 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/ShardsAPI.java @@ -0,0 +1,30 @@ +package net.crankedpvp.shards; + +import net.crankedpvp.shards.data.ShardsUser; +import net.crankedpvp.shards.managers.ShardsManager; +import org.bukkit.entity.Player; + +public class ShardsAPI { + private static final ShardsPlugin plugin = ShardsPlugin.getInstance(); + private static final ShardsManager shardsManager = plugin.getShardsManager(); + + public static void addShards(Player player, double amount) { + shardsManager.getShardsUser(player.getUniqueId()).addShards((long) amount); + } + + public static void removeShards(Player player, double amount) { + shardsManager.getShardsUser(player.getUniqueId()).removeShards((long) amount); + } + + public static void resetShards(Player player) { + shardsManager.getShardsUser(player.getUniqueId()).resetShards(); + } + + public static double getBalance(Player player) { + return shardsManager.getShardsUser(player.getUniqueId()).getBalance(); + } + + public static ShardsUser getShardsUser(Player player) { + return shardsManager.getShardsUser(player.getUniqueId()); + } +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/ShardsPlugin.java b/Shards/src/main/java/net/crankedpvp/shards/ShardsPlugin.java new file mode 100644 index 0000000..884cad5 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/ShardsPlugin.java @@ -0,0 +1,58 @@ +package net.crankedpvp.shards; + +import lombok.Getter; +import lombok.Setter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.shards.commands.ShardsAdminCommand; +import net.crankedpvp.shards.commands.ShardsCommand; +import net.crankedpvp.shards.managers.ShardsManager; +import net.crankedpvp.shards.language.LanguageHandler; +import net.crankedpvp.shards.managers.ShardsShopManager; +import net.crankedpvp.shards.utils.ConfigManager; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +@Getter +@Setter +public class ShardsPlugin extends JavaPlugin { + @Getter + private static ShardsPlugin instance; + private ShardsManager shardsManager; + private LanguageHandler languageHandler; + private CommandManager commandManager; + private ShardsShopManager shardsShopManager; + private ConfigManager configManager; + private ShardsAPI shardsAPI; + + + @Override + public void onEnable() { + instance = this; + + + this.languageHandler = new LanguageHandler(this); + languageHandler.load(); + + this.configManager = new ConfigManager(this); + configManager.setupFiles(); + + this.shardsManager = new ShardsManager(this); + shardsManager.onEnable(); + + this.shardsShopManager = new ShardsShopManager(this); + + this.commandManager = new CommandManager(this); + this.commandManager.register(new ShardsCommand(this), new ShardsAdminCommand()); + + Bukkit.getScheduler().runTaskTimer(this, ()-> { + shardsManager.saveAll(); + }, 60L, 15*20*60); + } + + @Override + public void onDisable() { + shardsManager.saveAll(); + shardsShopManager.save(this); + instance = null; + } +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/commands/ShardsAdminCommand.java b/Shards/src/main/java/net/crankedpvp/shards/commands/ShardsAdminCommand.java new file mode 100644 index 0000000..48a5dbb --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/commands/ShardsAdminCommand.java @@ -0,0 +1,108 @@ +package net.crankedpvp.shards.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.shards.language.Language; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Command("ashards") +@Alias("ashard") +public class ShardsAdminCommand extends CommandBase { + + @SubCommand("reload") + @Permission("cranked.admin") + public void onReload(CommandSender sender) { + Language.ADMIN_RELOADING.send(sender); + long then = System.currentTimeMillis(); + + ShardsPlugin.getInstance().getLanguageHandler().load(); + ShardsPlugin.getInstance().getShardsShopManager().reload(ShardsPlugin.getInstance()); + ShardsPlugin.getInstance().getConfigManager().reloadFiles(); + + long diff = System.currentTimeMillis() - then; + Language.ADMIN_RELOADED.send(sender, str -> str.replace("%took%", String.valueOf(diff))); + } + + @SubCommand("additem") + @Permission("cranked.admin") + public void onAddItem(CommandSender sender, Double price) { + Player player = ((Player)sender); + ItemStack item = player.getItemInHand().clone(); + if (item == null || player.getItemInHand().getType() == Material.AIR) { + Language.EMPTY_HAND.send(player); + return; + } + ShardsPlugin.getInstance().getShardsShopManager().getShopItems().put(item, price); + ShardsPlugin.getInstance().getShardsShopManager().addItemStack(item, price); + + Language.ADDED_ITEM_SHOP.send(player); + + } + + @SubCommand("give") + @Permission("cranked.admin") + @WrongUsage("&c/ashards give ") + public void onGiveShards(CommandSender sender, Player toPlayer, Long amount) { + ShardsPlugin.getInstance().getShardsManager().getShardsUser(toPlayer.getUniqueId()).addShards(amount); + toPlayer.sendMessage(CC.translate(Language.SHARDS_ADDED.getMessage().replace("%amount%", NumberUtils.formatMoney(amount)))); + sender.sendMessage(Language.SHARDS_GIVING.getMessage().replace("%amount%", NumberUtils.formatMoney(amount)).replace("%player%", toPlayer.getName())); + } + + @SubCommand("set") + @Permission("cranked.admin") + @WrongUsage("&c/ashards set ") + public void onSetShards(CommandSender sender, Player toPlayer, Long amount) { + ShardsPlugin.getInstance().getShardsManager().getShardsUser(toPlayer.getUniqueId()).setBalance(amount); + toPlayer.sendMessage(CC.translate(Language.SHARDS_SET.getMessage().replace("%amount%", NumberUtils.formatMoney(amount)))); + sender.sendMessage(Language.SHARDS_SETTING.getMessage().replace("%amount%", NumberUtils.formatMoney(amount)).replace("%player%", toPlayer.getName())); + } + + @SubCommand("remove") + @Permission("cranked.admin") + @WrongUsage("&c/ashards remove ") + public void onRemoveShards(CommandSender sender, Player toPlayer, Long amount) { + ShardsPlugin.getInstance().getShardsManager().getShardsUser(toPlayer.getUniqueId()).removeShards(amount); + toPlayer.sendMessage(CC.translate(Language.SHARDS_REMOVED.getMessage().replace("%amount%", NumberUtils.formatMoney(amount)))); + sender.sendMessage(Language.SHARDS_REMOVING.getMessage().replace("%amount%", NumberUtils.formatMoney(amount)).replace("%player%", toPlayer.getName())); + } + + + @SubCommand("reset") + @Permission("cranked.admin") + @WrongUsage("&c/ashards reset ") + public void onResetShards(CommandSender sender, Player toPlayer) { + ShardsPlugin.getInstance().getShardsManager().getShardsUser(toPlayer.getUniqueId()).resetShards(); + toPlayer.sendMessage(CC.translate(Language.SHARDS_RESET.getMessage())); + sender.sendMessage(Language.SHARDS_RESETTING.getMessage().replace("%player%", toPlayer.getName())); + } + + + + + @SubCommand("removeitem") + @Permission("cranked.admin") + public void onRemoveItem(CommandSender sender) { + Player player = ((Player)sender); + ItemStack item = player.getItemInHand().clone(); + if (item == null || item.getType() == Material.AIR) { + Language.EMPTY_HAND.send(player); + return; + } + if (!ShardsPlugin.getInstance().getShardsShopManager().getShopItems().containsKey(item)) { + Language.NOT_IN_SHOP.send(player); + return; + } + ShardsPlugin.getInstance().getShardsShopManager().getShopItems().remove(item); + ShardsPlugin.getInstance().getShardsShopManager().deleteItemStack(item); + + Language.REMOVED_ITEM_SHOP.send(player); + + } + +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/commands/ShardsCommand.java b/Shards/src/main/java/net/crankedpvp/shards/commands/ShardsCommand.java new file mode 100644 index 0000000..60b3e6f --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/commands/ShardsCommand.java @@ -0,0 +1,53 @@ +package net.crankedpvp.shards.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.SubCommand; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.shards.managers.ShardsManager; +import net.crankedpvp.shards.data.ShardsUser; +import net.crankedpvp.shards.guis.MainShardsGUI; +import net.crankedpvp.shards.language.Language; +import net.crankedpvp.crankedutils.utils.CC; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("shards") +@Alias("shard") +public class ShardsCommand extends CommandBase { + private ShardsManager shardsManager; + + public ShardsCommand(ShardsPlugin plugin) { + this.shardsManager = ShardsPlugin.getInstance().getShardsManager(); + } + + @Default + public void onDefault(CommandSender sender) { + MainShardsGUI mainShardsGUI = new MainShardsGUI((Player) sender); + mainShardsGUI.getShardsGUI().open((Player)sender); + } + + @SubCommand("balance") + @Alias("bal") + public void onBalance(CommandSender sender) { + ShardsUser shardsUser = shardsManager.getShardsUser(((Player) sender).getUniqueId()); + sender.sendMessage(Language.BALANCE.getMessage().replace("%balance%", String.valueOf(shardsUser.getBalance()))); + } + + @SubCommand("shop") + @Alias("itemshop") + public void onShop(CommandSender sender) { + MainShardsGUI mainShardsGUI = new MainShardsGUI((Player) sender); + mainShardsGUI.getShardsGUI().open((Player)sender); + } + + @SubCommand("help") + @Alias("info") + public void onHelp(CommandSender sender) { + for (String s : Language.HELP.getValuesAsList()) { + sender.sendMessage(CC.translate(s)); + } + } +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/data/ShardsUser.java b/Shards/src/main/java/net/crankedpvp/shards/data/ShardsUser.java new file mode 100644 index 0000000..67d333b --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/data/ShardsUser.java @@ -0,0 +1,78 @@ +package net.crankedpvp.shards.data; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.shards.struct.ShardTransaction; +import net.crankedpvp.storageutils.utils.KeyToSave; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Getter +@Setter +public class ShardsUser implements KeyToSave { + private UUID uuid; + private long balance; + private long spent; + private List transactions; + private long lastDailyRewardClaimed; + + public ShardsUser(UUID uuid) { + this.uuid = uuid; + this.balance = 0L; + this.spent = 0L; + this.transactions = new ArrayList<>(); + this.lastDailyRewardClaimed = 0L; + } + + @Override + public String getKey() { + return uuid.toString(); + } + + @Override + public void setKey(String s) { + this.uuid = UUID.fromString(s); + } + + public boolean canAfford(double price) { + return balance >= price; + } + + public boolean canRedeemDailyreward() { + return System.currentTimeMillis() >= this.lastDailyRewardClaimed + 86400000; + } + + public void addShards(double amount) { + ShardsPlugin.getInstance().getShardsManager().setTotalShards((long) (ShardsPlugin.getInstance().getShardsManager().getTotalShards()+amount)); + balance+=amount; + } + + public void removeShards(double amount) { + ShardsPlugin.getInstance().getShardsManager().setTotalShards((long) (ShardsPlugin.getInstance().getShardsManager().getTotalShards() -amount)); + spent+=amount; + balance-=amount; + } + + public void resetShards() { + balance = 0L; + } + + public void addTransation(ShardTransaction shardTransaction) { + boolean canOffer = ShardsPlugin.getInstance().getShardsManager().getRecentTransactions().offer(shardTransaction); + if (!canOffer) { + ShardsPlugin.getInstance().getShardsManager().getRecentTransactions().poll(); + ShardsPlugin.getInstance().getShardsManager().getRecentTransactions().offer(shardTransaction); + } + transactions.add(shardTransaction); + } + + public OfflinePlayer getOfflinePlayer() { + return Bukkit.getOfflinePlayer(uuid); + } +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/events/PlayerShardBalanceUpdateEvent.java b/Shards/src/main/java/net/crankedpvp/shards/events/PlayerShardBalanceUpdateEvent.java new file mode 100644 index 0000000..c86b4ea --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/events/PlayerShardBalanceUpdateEvent.java @@ -0,0 +1,45 @@ +package net.crankedpvp.shards.events; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.crankedpvp.shards.struct.ShardBalanceUpdateType; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@RequiredArgsConstructor +@Getter +public class PlayerShardBalanceUpdateEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean canceled = false; + + @Getter + private final long oldBalance; + + @Getter + private final long newBalance; + + @Getter + private final ShardBalanceUpdateType shardBalanceUpdateType; + + @Override + public boolean isCancelled() { + return this.canceled; + } + + @Override + public void setCancelled(boolean b) { + this.canceled = b; + } + + @Override + public HandlerList getHandlers() { + return PlayerShardBalanceUpdateEvent.handlers; + } + + public static HandlerList getHandlerList() { + return PlayerShardBalanceUpdateEvent.handlers; + } + +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/guis/MainShardsGUI.java b/Shards/src/main/java/net/crankedpvp/shards/guis/MainShardsGUI.java new file mode 100644 index 0000000..f1f1fe5 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/guis/MainShardsGUI.java @@ -0,0 +1,128 @@ +package net.crankedpvp.shards.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.crankedutils.utils.TimeUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.shards.data.ShardsUser; +import net.crankedpvp.shards.language.Language; +import net.crankedpvp.shards.managers.ShardsManager; +import net.crankedpvp.shards.struct.ShardTransaction; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +@Getter +public class MainShardsGUI { + + private final PaginatedGui shardsGUI; + private final ShardsManager shardsManager = ShardsPlugin.getInstance().getShardsManager(); + + public MainShardsGUI(Player player) { + ShardsUser shardsUser = shardsManager.getShardsUser(player.getUniqueId()); + this.shardsGUI = new PaginatedGui(6, 54, "Shards Menu"); + this.shardsGUI.setDefaultClickAction(event -> event.setCancelled(true)); + this.shardsGUI.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.shardsGUI.setItem(6, 5, new GuiItem(createUserInfoItem(shardsUser))); + this.shardsGUI.setItem(3, 3, new GuiItem(createShopItem(player.getUniqueId()), event -> { + ShardsShopGUI shardsShopGUI = new ShardsShopGUI(player); + shardsShopGUI.getShardsGUI().open(player); + })); + this.shardsGUI.setItem(4, 5, new GuiItem(createDailyRewardItem(shardsUser), event -> { + if (shardsUser.canRedeemDailyreward()) { + shardsUser.addShards(Integer.parseInt(Language.DAILY_SHARDS.getValue())); + shardsUser.setLastDailyRewardClaimed(System.currentTimeMillis()); + player.sendMessage(CC.translate(Language.SHARDS_ADDED.getMessage().replace("%amount%", Language.DAILY_SHARDS.getValue()))); + } else { + player.sendMessage(CC.translate(Language.REWARD_ON_COOLDOWN.getMessage().replace("%time%", TimeUtils.formatSeconds(getSecondsTillRewardAvailable(shardsUser))))); + } + this.shardsGUI.updateItem(4, 5, new GuiItem(createDailyRewardItem(shardsUser), e -> { + if (shardsUser.canRedeemDailyreward()) { + shardsUser.addShards(Integer.parseInt(Language.DAILY_SHARDS.getValue())); + shardsUser.setLastDailyRewardClaimed(System.currentTimeMillis()); + player.sendMessage(CC.translate(Language.SHARDS_ADDED.getMessage().replace("%amount%", Language.DAILY_SHARDS.getValue()))); + } else { + player.sendMessage(CC.translate(Language.REWARD_ON_COOLDOWN.getMessage().replace("%time%", TimeUtils.formatSeconds(getSecondsTillRewardAvailable(shardsUser))))); + } + + })); + })); + this.shardsGUI.setItem(3, 7, new GuiItem(createRecentTransactions())); + } + + public ItemStack createUserInfoItem(ShardsUser shardsUser) { + return new ItemBuilder(SkullUtils.getSkullFromPlayer(Bukkit.getPlayer(shardsUser.getOfflinePlayer().getUniqueId()))) + .setName("&b&l" + shardsUser.getOfflinePlayer().getName() + "'s Shards Info") + .addLore("") + .addLore("&3&lPlayer Info") + .addLore("&b&l * &fBalance&7: &3♦&b" + NumberUtils.formatMoney(shardsUser.getBalance())) + .addLore("&b&l * &fSpent&7: &3♦&b" + NumberUtils.formatMoney(shardsUser.getSpent())) + .addLore("&b&l * &fTransactions&7: &b" + NumberUtils.formatNum(shardsUser.getTransactions().size())) + .addLore("") + .addLore("&3&lServer Info") + .addLore("&b&l * &fTotal Shards&7: &3♦&b" + NumberUtils.formatMoney(shardsManager.getTotalShards())) + .addLore("&b&l * &fRichest Online Player&7: &d" + shardsManager.getRichestPlayer().getOfflinePlayer().getName() + " &8➥ &3♦&b" + shardsManager.getRichestPlayer().getBalance()) + .colorize() + .build(); + } + + public ItemStack createRecentTransactions() { + ItemBuilder builder = new ItemBuilder(Material.PAPER, "&b&lRecent Transactions").addLore("&7This will show the 10 most recent transactions.").addLore("").colorize(); + for (ShardTransaction transaction : shardsManager.getRecentTransactionsList()) { + builder.addLore("&b&l * &f" + Bukkit.getOfflinePlayer(transaction.getBuyer()).getName() + "&7 purchased " + (transaction.getItemName() + "&7 for &3♦&b" + NumberUtils.formatMoney(transaction.getPrice()) + "&7. &8(&f" + TimeUtils.formatSeconds(((System.currentTimeMillis() - transaction.getTime()) / 1000)) + " ago&8)")); + } + + return builder.colorize().build(); + } + + + public ItemStack createPreviousItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&c<- Previous Page"), "&7Right-Click&7 to go to the previous page.").colorize().build(); + } + + public ItemStack createNextItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&aNext Page ->"), "&7Right-Click&7 to go to the next page.").colorize().build(); + + } + + public ItemStack createFillerItem() { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData())).setName("&7").colorize().build(); + } + + public ItemStack createDailyRewardItem(ShardsUser shardsUser) { + return new ItemBuilder(Material.NETHER_STAR, "&b&lDaily Reward") + .addLore("&7Click here to redeem your daily shards.") + .addLore("") + .addLore("&b&l * &fAvailable: &7" + TimeUtils.formatSeconds(getSecondsTillRewardAvailable(shardsUser))) + .addLore("&b&l * &fReward: &3♦&b" + Language.DAILY_SHARDS.getValue()) + .colorize() + .build(); + } + + public long getSecondsTillRewardAvailable(ShardsUser shardsUser) { + long claimedTimeStamp = shardsUser.getLastDailyRewardClaimed(); + long currentTimeStamp = System.currentTimeMillis(); + long difference = currentTimeStamp - claimedTimeStamp; + long cooldown = 86400000; + return TimeUnit.MILLISECONDS.toSeconds(cooldown-difference); + } + + public ItemStack createShopItem(UUID uuid) { + ShardsManager shardsManager = ShardsPlugin.getInstance().getShardsManager(); + ShardsUser shardsUser = shardsManager.getShardsUser(uuid); + return new ItemBuilder(Material.CHEST, "&b&lShards ItemShop", Arrays.asList("&7Click here to open the shards", "&7itemshop and purchase goodies", "&7using the shards you earned.", "", "&bPurchaseable Items: &f" + ShardsPlugin.getInstance().getShardsShopManager().getPurchaseAbleItemsAmount(shardsUser.getBalance())) + ).colorize().build(); + } +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/guis/ShardsShopGUI.java b/Shards/src/main/java/net/crankedpvp/shards/guis/ShardsShopGUI.java new file mode 100644 index 0000000..025b2d3 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/guis/ShardsShopGUI.java @@ -0,0 +1,110 @@ +package net.crankedpvp.shards.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.shards.data.ShardsUser; +import net.crankedpvp.shards.language.Language; +import net.crankedpvp.shards.managers.ShardsManager; +import net.crankedpvp.shards.utils.ConfigManager; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +@Getter +public class ShardsShopGUI { + private final PaginatedGui shardsGUI; + + private final ShardsManager shardsManager = ShardsPlugin.getInstance().getShardsManager(); + private final Player player; + private final ConfigManager configManager; + + + public ShardsShopGUI(Player player) { + this.player = player; + this.configManager = ShardsPlugin.getInstance().getConfigManager(); + ShardsUser shardsUser = shardsManager.getShardsUser(player.getUniqueId()); + this.shardsGUI = new PaginatedGui(6, 54, "Shards Shop Menu"); + this.shardsGUI.setDefaultClickAction(event -> event.setCancelled(true)); + this.shardsGUI.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.shardsGUI.setItem(6, 5, new GuiItem(createUserInfoItem(shardsUser))); + this.shardsGUI.setItem(6, 1, new GuiItem(createPreviousItem(), event -> { + MainShardsGUI mainShardsGUI = new MainShardsGUI(player); + mainShardsGUI.getShardsGUI().open(player); + })); + this.shardsGUI.updateItem(6, 5, new GuiItem(createUserInfoItem(shardsUser))); + + List> entries = new ArrayList<>(ShardsPlugin.getInstance().getShardsShopManager().getShopItems().entrySet()); + entries.sort(Comparator.comparing((itemStackIntegerEntry -> itemStackIntegerEntry.getKey().getType().name()))); + for (Map.Entry entry : entries) { + double price = entry.getValue(); + ItemStack item = entry.getKey(); + this.shardsGUI.addItem(new GuiItem(createXpShopItem(item.clone(), price), event -> { + ShardsPlugin.getInstance().getShardsManager().purchaseItem(player, item, price); + this.shardsGUI.updateItem(6, 5, new GuiItem(createUserInfoItem(shardsUser))); + + })); + } + + } + + public ItemStack createXpShopItem(ItemStack itemStack, double price) { + double discountedPrice; + + if (player.hasPermission("satan.discount")) { + int discountPercent = this.configManager.getAbstractConfig(ConfigManager.ConfigFile.SETTINGS).getConfig().getInt("satan-discount"); + discountedPrice = price - (price * discountPercent / 100); + } else { + discountedPrice = 0; + } + + String loreLine = discountedPrice == 0 ? Language.PRICE_LINE.getMessage(str -> str.replace("{price}", NumberUtils.formatMoney(price))) : Language.DISCOUNTED_PRICE_LINE.getMessage(str -> str.replace("{price}", NumberUtils.formatMoney(price)).replace("{discounted-price}", NumberUtils.formatMoney(discountedPrice))); + + return new ItemBuilder(itemStack.clone()) + .addLore("") + .addLore(loreLine) + .colorize() + .build(); + } + + public ItemStack createUserInfoItem(ShardsUser shardsUser) { + return new ItemBuilder(SkullUtils.getSkullFromPlayer(Bukkit.getPlayer(shardsUser.getOfflinePlayer().getUniqueId()))) + .setName("&b&l"+shardsUser.getOfflinePlayer().getName() + "'s Shards Info") + .addLore("") + .addLore("&3&lPlayer Info") + .addLore("&b&l * &fBalance&7: &3♦&b" + NumberUtils.formatMoney(shardsUser.getBalance())) + .addLore("&b&l * &fSpent&7: &3♦&b" + NumberUtils.formatMoney(shardsUser.getSpent())) + .addLore("&b&l * &fTransactions&7: &e" + NumberUtils.formatNum(shardsUser.getTransactions().size())) + .addLore("") + .addLore("&3&lServer Info") + .addLore("&b&l * &fTotal Shards&7: &3♦&b" + NumberUtils.formatMoney(shardsManager.getTotalShards())) + .addLore("&b&l * &fRichest Player&7: &d" + shardsManager.getRichestPlayer().getOfflinePlayer().getName() + " &8➥ &3♦&b" + shardsManager.getRichestPlayer().getBalance()) + .colorize() + .build(); + } + + public ItemStack createPreviousItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&c<- Go Back"), "&7Right-Click&7 to go to the previous page.").colorize().build(); + } + + public ItemStack createNextItem() { + return new ItemBuilder(Material.ARROW, CC.translate("&aNext Page ->"), "&7Right-Click&7 to go to the next page.").colorize().build(); + + } + + public ItemStack createFillerItem() { + return new ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData())).setName("&7").colorize().build(); + } +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/language/Language.java b/Shards/src/main/java/net/crankedpvp/shards/language/Language.java new file mode 100644 index 0000000..af0a54d --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/language/Language.java @@ -0,0 +1,118 @@ +package net.crankedpvp.shards.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + BALANCE, + HELP, + NO_PERMISSION, + ADMIN_RELOADING, + ADMIN_RELOADED, + NOT_ENOUGH_SHARDS, + SUCCESSFUL_ITEM_PURCHASE, + EMPTY_HAND, + NOT_IN_SHOP, + REMOVED_ITEM_SHOP, + ADDED_ITEM_SHOP, + SHARDS_ADDED, + SHARDS_REMOVED, + SHARDS_SET, + SHARDS_RESET, + REWARD_ON_COOLDOWN, + DAILY_SHARDS, + SHARDS_GIVING, + SHARDS_REMOVING, + SHARDS_RESETTING, + SHARDS_SETTING, + PRICE_LINE, + DISCOUNTED_PRICE_LINE, + + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/language/LanguageHandler.java b/Shards/src/main/java/net/crankedpvp/shards/language/LanguageHandler.java new file mode 100644 index 0000000..79fb253 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.shards.language; + +import net.crankedpvp.shards.ShardsPlugin; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final ShardsPlugin plugin; + + public LanguageHandler(ShardsPlugin plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Shards/src/main/java/net/crankedpvp/shards/managers/ShardsManager.java b/Shards/src/main/java/net/crankedpvp/shards/managers/ShardsManager.java new file mode 100644 index 0000000..3fbf63e --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/managers/ShardsManager.java @@ -0,0 +1,139 @@ +package net.crankedpvp.shards.managers; + +import com.google.common.collect.ImmutableList; +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.StringUtils; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.shards.data.ShardsUser; +import net.crankedpvp.shards.events.PlayerShardBalanceUpdateEvent; +import net.crankedpvp.shards.language.Language; +import net.crankedpvp.shards.struct.ShardBalanceUpdateType; +import net.crankedpvp.shards.struct.ShardTransaction; +import net.crankedpvp.shards.utils.ConfigManager; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.File; +import java.util.List; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.LinkedBlockingQueue; + +@Getter +@Setter +public class ShardsManager extends SaveLoadManager { + + private long totalShards; + public Queue recentTransactions; + private long value; + private ShardsShopManager shardsShopManager; + private final ConfigManager configManager; + + public ShardsManager(ShardsPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "data/", ShardsUser.class); + this.configManager = plugin.getConfigManager(); + this.totalShards = 0; + this.recentTransactions = new LinkedBlockingQueue<>(10); + this.shardsShopManager = ShardsPlugin.getInstance().getShardsShopManager(); + } + + public ShardsUser getShardsUser(UUID key) { + if (!containsKey(key.toString())) { + + File file = new File(ShardsPlugin.getInstance().getDataFolder(), "data/" + key + ".json"); + if(file.exists()) { + Bukkit.getScheduler().runTaskAsynchronously(ShardsPlugin.getInstance(), () -> super.load(file)); + } else { + + if (!containsKey(key.toString())) { + addToCache(new ShardsUser(key)); + } + } + } + + return getFromCache(key.toString()); + } + + /* + public ShardsUser getShardsUser(UUID uuid) { + if (!containsKey(uuid.toString())) { + ShardsUser shardsUser = new ShardsUser(uuid); + addToCache(shardsUser); + } + return getFromCache(uuid.toString()); + } + + */ + + public void onEnable() { + /* + loadAll(); + for (ShardsUser shardsUser : this.getCacheValues()) { + totalShards += shardsUser.getBalance(); + } + */ + this.totalShards = 0; + } + + public void purchaseItem(UUID uuid, ItemStack item, double price) { + this.purchaseItem(Bukkit.getPlayer(uuid), item, price); + } + + public void purchaseItem(Player player, ItemStack item, double price) { + final UUID uuid = player.getUniqueId(); + ShardsUser shardsUser = getShardsUser(uuid); + + if (player.hasPermission("satan.discount")) { + int discountPercent = this.configManager.getAbstractConfig(ConfigManager.ConfigFile.SETTINGS).getConfig().getInt("satan-discount"); + price = price - (price * discountPercent / 100); + } + + if (shardsUser.canAfford(price)) { + ShardTransaction shardTransaction = new ShardTransaction(shardsUser.getUuid(),price, System.currentTimeMillis(), item.getItemMeta().getDisplayName() == null ? item.getType().name() : item.getItemMeta().getDisplayName()); + shardsUser.addTransation(shardTransaction); + shardsUser.removeShards(price); + LeaderboardsAPI.getPlayerStats(uuid).addShardsSpent(price); + PlayerShardBalanceUpdateEvent event = new PlayerShardBalanceUpdateEvent(shardsUser.getBalance(), (long) (shardsUser.getBalance() - price), ShardBalanceUpdateType.DECREASE); + Bukkit.getServer().getPluginManager().callEvent(event); + String message = Language.SUCCESSFUL_ITEM_PURCHASE.getMessage().replace("%price%", NumberUtils.formatMoney(price)); + message = message.replace("%itemName%", item.getItemMeta().getDisplayName() == null ? StringUtils.getProperCase(item.getType().name()) : item.getItemMeta().getDisplayName()); + Bukkit.getPlayer(uuid).sendMessage(message); + PlayerUtils.giveOrDropProtectedItem(Bukkit.getPlayer(uuid), item, 60); + } else { + double missing = price - shardsUser.getBalance(); + String message = Language.NOT_ENOUGH_SHARDS.getMessage().replace("%missing%", NumberUtils.formatMoney(missing)); + message = message.replace("%itemName%", item.getItemMeta().getDisplayName() == null ? StringUtils.getProperCase(item.getType().name()) : item.getItemMeta().getDisplayName()); + Bukkit.getPlayer(uuid).sendMessage(message); + } + } + + + public List getRecentTransactionsList() { + return ImmutableList.copyOf(recentTransactions).reverse(); + } + + public ShardsUser getRichestPlayer() { + ShardsUser richest = getShardsUser(UUID.fromString("a86208fa-ecb2-4a3c-bed0-5136645e7d80")); + long cash = 0; + + for (ShardsUser shardsUser : getCacheValues()) { + + long balance = shardsUser.getBalance(); + if (balance > cash) { + cash = balance; + richest = shardsUser; + } + } + + return richest; + } + + +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/managers/ShardsShopManager.java b/Shards/src/main/java/net/crankedpvp/shards/managers/ShardsShopManager.java new file mode 100644 index 0000000..b719273 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/managers/ShardsShopManager.java @@ -0,0 +1,80 @@ +package net.crankedpvp.shards.managers; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.crankedutils.utils.serializer.item.ItemStackSerializer; +import net.crankedpvp.shards.ShardsPlugin; +import net.crankedpvp.shards.utils.ConfigManager; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +@Getter +@Setter +public class ShardsShopManager { + private Map shopItems; + public ShardsShopManager(ShardsPlugin plugin) { + this.shopItems = new HashMap<>(); + load(plugin); + + } + public int getPurchaseAbleItemsAmount(long balance) { + int amount = 0; + for (Double price : shopItems.values()) { + if (balance >= price) { + amount++; + } + } + return amount; + } + + public void reload(ShardsPlugin plugin) { + this.shopItems.clear(); + ShardsPlugin.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.SHOP).reloadConfig(); + load(plugin); + } + + public void load(ShardsPlugin plugin) { + ConfigManager configmanager = plugin.getConfigManager(); + FileConfiguration config = configmanager.getConfig(ConfigManager.ConfigFile.SHOP); + ConfigurationSection configurationSection = config.getConfigurationSection("shop.items"); + for (String key : configurationSection.getKeys(false)) { + double price = configurationSection.getDouble(key); + ItemStack item = ItemStackSerializer.deserialize(key); + this.shopItems.put(item, price); + } + } + + public void save(ShardsPlugin plugin) { + ConfigManager configmanager = plugin.getConfigManager(); + FileConfiguration config = configmanager.getConfig(ConfigManager.ConfigFile.SHOP); + ConfigurationSection configurationSection = config.getConfigurationSection("shop.items"); + for (Map.Entry entry : this.shopItems.entrySet()) { + double price = entry.getValue(); + ItemStack item = entry.getKey(); + configurationSection.set(ItemStackSerializer.serialize(item), price); + } + + ShardsPlugin.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.SHOP).saveConfig(); + } + + public void deleteItemStack(ItemStack item) { + ConfigManager configmanager = ShardsPlugin.getInstance().getConfigManager(); + FileConfiguration config = configmanager.getConfig(ConfigManager.ConfigFile.SHOP); + ConfigurationSection configurationSection = config.getConfigurationSection("shop.items"); + configurationSection.set(ItemStackSerializer.serialize(item), null); + ShardsPlugin.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.SHOP).saveConfig(); + } + + public void addItemStack(ItemStack item, double price) { + ConfigManager configmanager = ShardsPlugin.getInstance().getConfigManager(); + FileConfiguration config = configmanager.getConfig(ConfigManager.ConfigFile.SHOP); + ConfigurationSection configurationSection = config.getConfigurationSection("shop.items"); + configurationSection.set(ItemStackSerializer.serialize(item), price); + ShardsPlugin.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.SHOP).saveConfig(); + } +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/struct/ShardBalanceUpdateType.java b/Shards/src/main/java/net/crankedpvp/shards/struct/ShardBalanceUpdateType.java new file mode 100644 index 0000000..ef84432 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/struct/ShardBalanceUpdateType.java @@ -0,0 +1,13 @@ +package net.crankedpvp.shards.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +public enum ShardBalanceUpdateType { + + INCREASE, + DECREASE + ; + +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/struct/ShardTransaction.java b/Shards/src/main/java/net/crankedpvp/shards/struct/ShardTransaction.java new file mode 100644 index 0000000..3b572b5 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/struct/ShardTransaction.java @@ -0,0 +1,18 @@ +package net.crankedpvp.shards.struct; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +import java.io.Serializable; +import java.util.UUID; + +@AllArgsConstructor +@Getter +@Setter +public class ShardTransaction implements Serializable { + private UUID buyer; + private double price; + private long time; + private String itemName; +} diff --git a/Shards/src/main/java/net/crankedpvp/shards/utils/ConfigManager.java b/Shards/src/main/java/net/crankedpvp/shards/utils/ConfigManager.java new file mode 100644 index 0000000..faa3be9 --- /dev/null +++ b/Shards/src/main/java/net/crankedpvp/shards/utils/ConfigManager.java @@ -0,0 +1,52 @@ +package net.crankedpvp.shards.utils; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.crankedpvp.crankedutils.utils.config.AbstractConfig; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; + +public class ConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public ConfigManager(JavaPlugin plugin) { + for (ConfigFile configFile : ConfigFile.values()) { + AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName()); + configs.put(configFile, abstractConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AbstractConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AbstractConfig::reloadConfig); + } + + public AbstractConfig getAbstractConfig(ConfigFile configFile) { + return configs.get(configFile); + } + + public FileConfiguration getConfig(ConfigFile configFile) { + return getAbstractConfig(configFile).getConfig(); + } + + @Getter + @RequiredArgsConstructor + public enum ConfigFile { + + SHOP("shop.yml"), + SETTINGS("settings.yml"), + ; + + private final String fileName; + + } + +} diff --git a/Shards/src/main/resources/language.yml b/Shards/src/main/resources/language.yml new file mode 100644 index 0000000..d78dda7 --- /dev/null +++ b/Shards/src/main/resources/language.yml @@ -0,0 +1,25 @@ +HELP: + - "&b&lShards Help" + - "&7Add help message here bro, don't be lazy" +NO_PERMISSION: "&cYou do not have permission to do this" +BALANCE: "&b&lShards &8➥ &7You have &b%balance%&7 shards." +ADMIN_RELOADING: "&b&lShards &8➥ &7Reloading configs now..." +ADMIN_RELOADED: "&b&lShards &8➥ &7Reloaded configs and other cool stuff. Took &d%took%ms&7." +SUCCESSFUL_ITEM_PURCHASE: "&b&lShards &8➥ &7You have successfuly purchased %itemName%&7 for &b%price%&7 Shards." +NOT_ENOUGH_SHARDS: "&b&lShards &8➥ &7You need &b%missing%&7 Shards to purchase %itemName%" +EMPTY_HAND: "&cPlease hold the item you wish to add/remove to the shop" +NOT_IN_SHOP: "&cThis item is not in the shards shop!" +REMOVED_ITEM_SHOP: "&cRemoved the item in your hand from the shards shop!" +ADDED_ITEM_SHOP: "&cAdded the item in your hand to the shards shop!" +SHARDS_ADDED: "&b&lShards &8➥ &b%amount%&7 Shards have been added to your balance." +SHARDS_REMOVED: "&b&lShards &8➥ &b%amount%&7 Shards have been removed from your balance." +SHARDS_SET: "&b&lShards &8➥ &7Your shard balance has been updated. It is now &b%amount% Shards" +SHARDS_RESET: "&b&lShards &8➥ &7Your shard balance has been reset" +REWARD_ON_COOLDOWN: "&b&lShards &8➥ &7You cannot claim your Daily Reward yet. You need to wait another %time%" +DAILY_SHARDS: 50 +PRICE_LINE: "&b&l* &fPrice: &3♦&b{price}" +DISCOUNTED_PRICE_LINE: "&b&l* &fPrice: &c&m{price}&3 ♦&b{discounted-price} &7(Satan Discount)" +SHARDS_GIVING: "&b&lShards &8➥ &7Giving &f%player% &b%amount% &7Shards.." +SHARDS_REMOVING: "&b&lShards &8➥ &7Removing &f%player% &b%amount% &7Shards.." +SHARDS_RESETTING: "&b&lShards &8➥ &7Resetting &f%player% &7Shards.." +SHARDS_SETTING: "&b&lShards &8➥ &7Setting &f%player% &b%amount% &7Shards.." \ No newline at end of file diff --git a/Shards/src/main/resources/plugin.yml b/Shards/src/main/resources/plugin.yml new file mode 100644 index 0000000..1e7d640 --- /dev/null +++ b/Shards/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedShards +main: net.crankedpvp.shards.ShardsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - StorageUtil \ No newline at end of file diff --git a/Shards/src/main/resources/settings.yml b/Shards/src/main/resources/settings.yml new file mode 100644 index 0000000..4357435 --- /dev/null +++ b/Shards/src/main/resources/settings.yml @@ -0,0 +1 @@ +satan-discount: 15 \ No newline at end of file diff --git a/Shards/src/main/resources/shop.yml b/Shards/src/main/resources/shop.yml new file mode 100644 index 0000000..02cec5b --- /dev/null +++ b/Shards/src/main/resources/shop.yml @@ -0,0 +1,2 @@ +shop: + items: {} \ No newline at end of file diff --git a/Shop/pom.xml b/Shop/pom.xml new file mode 100644 index 0000000..73808fc --- /dev/null +++ b/Shop/pom.xml @@ -0,0 +1,26 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Shop + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + + \ No newline at end of file diff --git a/Shop/src/main/java/net/crankedpvp/shop/ShopPlugin.java b/Shop/src/main/java/net/crankedpvp/shop/ShopPlugin.java new file mode 100644 index 0000000..2a778f9 --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/ShopPlugin.java @@ -0,0 +1,73 @@ +package net.crankedpvp.shop; + + +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.shop.commands.SellCommand; +import net.crankedpvp.shop.commands.ShopCommand; +import net.crankedpvp.shop.handlers.ShopHandler; +import net.crankedpvp.shop.handlers.ShopsFile; +import net.crankedpvp.shop.listeners.MainMenuClick; +import net.crankedpvp.shop.listeners.ShopClick; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.plugin.java.JavaPlugin; + +@Getter +public class ShopPlugin extends JavaPlugin { + + @Getter + private static ShopPlugin instance; + @Getter + private static Economy econ; + + private static ShopsFile shopsFile; + private static ShopHandler shopHandler; + + @Override + public void onEnable() { + instance = this; + econ = EconomyUtils.getEconomy(); + reloadConfig(); + + ShopPlugin.loadStuff(); + + this.getCommand("shop").setExecutor(new ShopCommand()); + this.getCommand("sell").setExecutor(new SellCommand()); + + Bukkit.getPluginManager().registerEvents(new MainMenuClick(), this); + Bukkit.getPluginManager().registerEvents(new ShopClick(), this); + } + + @Override + public void onDisable() { + instance = null; + } + + @Override + public void reloadConfig() { + super.reloadConfig(); + saveDefaultConfig(); + getConfig().options().copyDefaults(true); + saveConfig(); + } + + public static void loadStuff() { + shopsFile = new ShopsFile(getInstance()); + shopHandler = new ShopHandler(getInstance()); + } + + + public static ShopsFile getShopsFile() { + return shopsFile; + } + + public static ShopHandler getShopHandler() { + return shopHandler; + } + + public static String color(String input) { + return ChatColor.translateAlternateColorCodes('&', input); + } +} diff --git a/Shop/src/main/java/net/crankedpvp/shop/commands/SellCommand.java b/Shop/src/main/java/net/crankedpvp/shop/commands/SellCommand.java new file mode 100644 index 0000000..041dc6b --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/commands/SellCommand.java @@ -0,0 +1,66 @@ +package net.crankedpvp.shop.commands; + +import net.crankedpvp.shop.ShopPlugin; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.text.NumberFormat; + +public class SellCommand implements CommandExecutor { + + @Override + public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { + if(!sender.hasPermission("shopguiplus.sell.hand")) { + sender.sendMessage("§c§l(!)§c You haven't unlocked this feature!"); + return true; + } + + + if(args.length == 0) { + sender.sendMessage("§c§l(!)§c /sell hand - Sell held item"); + sender.sendMessage("§c§l(!)§c /sell all - Sell all items in inventory"); + return true; + } + + Player p = (Player) sender; + + if(args[0].equalsIgnoreCase("hand") && sender.hasPermission("shopguiplus.sell.hand")) { + ItemStack item = p.getItemInHand(); + double price = ShopPlugin.getShopHandler().getSellPrice(item); + if(price <= 0) { + p.sendMessage("§c§l(!) §cCannot sell this item!"); + return true; + } + + p.sendMessage("§a§l(!)§f You sold §a"+item.getAmount()+"x items§f for §a$"+ NumberFormat.getInstance().format(price*item.getAmount())); + p.setItemInHand(new ItemStack(Material.AIR)); + + ShopPlugin.getEcon().depositPlayer(p, price*item.getAmount()); + return true; + } else if(args[0].equalsIgnoreCase("all") && sender.hasPermission("shopguiplus.sell.all")) { + int sell = 0; + int amount = 0; + for(int i = 0; i < p.getInventory().getSize(); i++) { + ItemStack item = p.getInventory().getItem(i); + if(item == null) + continue; + double price = ShopPlugin.getShopHandler().getSellPrice(item); + if(price == 0) { + continue; + } + + sell += price * item.getAmount(); + amount += item.getAmount(); + p.getInventory().setItem(i, new ItemStack(Material.AIR)); + } + + p.sendMessage("§a§l(!)§f You sold §a"+amount+"x items§f for §a$"+ NumberFormat.getInstance().format(sell)); + ShopPlugin.getEcon().depositPlayer(p, sell); + } + return true; + } +} diff --git a/Shop/src/main/java/net/crankedpvp/shop/commands/ShopCommand.java b/Shop/src/main/java/net/crankedpvp/shop/commands/ShopCommand.java new file mode 100644 index 0000000..613e349 --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/commands/ShopCommand.java @@ -0,0 +1,59 @@ +package net.crankedpvp.shop.commands; + +import net.crankedpvp.shop.ShopPlugin; +import net.crankedpvp.shop.nbt.NBTApi; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.List; + +public class ShopCommand implements CommandExecutor { + + @Override + public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { + if(args.length > 0 && sender.hasPermission("shop.reload")) { + ShopPlugin.loadStuff(); + ShopPlugin.getInstance().reloadConfig(); + sender.sendMessage("§aShop has been reloaded!"); + return true; + } + open((Player)sender); + return true; + } + + public static void open(Player p) { + Inventory inv = Bukkit.createInventory(null, ShopPlugin.getInstance().getConfig().getInt("shopMenuSize"), + ShopPlugin.color(ShopPlugin.getInstance().getConfig().getString("shopMenuName"))); + for(String item : ShopPlugin.getInstance().getConfig().getConfigurationSection("shopMenuItems").getKeys(false)) { + String path = "shopMenuItems."+item; + + ItemStack i = new ItemStack(Material.matchMaterial(ShopPlugin.getInstance().getConfig().getString(path+".item.material"))); + i.setDurability((short) ShopPlugin.getInstance().getConfig().getInt(path+".item.damage")); + ItemMeta im = i.getItemMeta(); + + String name = ShopPlugin.getInstance().getConfig().getString(path+".item.name"); + im.setDisplayName(ShopPlugin.color(name)); + + List list = new ArrayList<>(); + for(String line : ShopPlugin.getInstance().getConfig().getStringList(path+".item.lore")) { + list.add(ShopPlugin.color(line)); + } + + im.setLore(list); + i.setItemMeta(im); + + i = NBTApi.setKey(i, "menu", ShopPlugin.getInstance().getConfig().getString(path+".shop")); + inv.setItem(ShopPlugin.getInstance().getConfig().getInt(path+".slot"), i); + } + + p.openInventory(inv); + } +} diff --git a/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopHandler.java b/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopHandler.java new file mode 100644 index 0000000..35b60c1 --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopHandler.java @@ -0,0 +1,202 @@ +package net.crankedpvp.shop.handlers; + +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.shop.ShopPlugin; + +import net.crankedpvp.shop.nbt.NBTApi; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.*; +import java.util.stream.Collectors; + +public class ShopHandler { + + // String category, ShopItem material + private static HashMap> items = new HashMap<>(); + + // String category, String invName + private static HashMap shopNames = new HashMap<>(); + + // int slot, String itemName + private static HashMap mainMenu = new HashMap<>(); + + public ShopHandler(JavaPlugin instance) { + FileConfiguration fc = ShopPlugin.getShopsFile().getFc(); + for(String shop : fc.getConfigurationSection("shops").getKeys(false)) { + String invName = ShopPlugin.color(fc.getString("shops."+shop+".name")); + shopNames.put(shop, invName); + + List itemsList = new ArrayList<>(); + for (String item : fc.getConfigurationSection("shops." + shop + ".items").getKeys(false)) { + String path = "shops."+shop+".items."+item; + + boolean command = !fc.getString(path+".type").equalsIgnoreCase("item"); + boolean spawner = fc.getBoolean(path+".item.spawner"); + String mt = fc.getString(path+".item.material"); + + if(spawner) { + mt = "MOB_SPAWNER"; + } + + Material m = Material.matchMaterial(mt); + + int damage = fc.getInt(path+".item.damage"); + int quantity = fc.getInt(path+".item.quantity"); + + double sellPrice = fc.getDouble(path+".sellPrice")/quantity; + double buyPrice = fc.getDouble(path+".buyPrice")/quantity; + + String name = fc.getString(path+".item.name"); + if(name != null) { + name = ShopPlugin.color(name); + } + + List lore = new ArrayList<>(); + if(fc.contains(path+".item.lore")) { + for(String line : fc.getStringList(path+".item.lore")) { + lore.add(ShopPlugin.color(line)); + } + } + ShopItem shopItem = new ShopItem(m, damage, command, path, buyPrice, sellPrice, quantity, name, + !command ? null : fc.getStringList(path+".commands").get(0), !spawner ? null : fc.getString(path+".item.mob"), lore); + itemsList.add(shopItem); + } + items.put(shop, itemsList); + } + + for(String item : instance.getConfig().getConfigurationSection("shopMenuItems").getKeys(false)) { + mainMenu.put(instance.getConfig().getInt("shopMenuItems."+item+".slot"), item); + } + } + + public String getShopNameByInvName(String input) { + for(Map.Entry names : shopNames.entrySet()) { + if(!names.getValue().equalsIgnoreCase(input)) + continue; + + return names.getKey(); + } + return null; + } + + public double getSellPrice(ItemStack item) { + if(item == null) + return 0; + + if(item.hasItemMeta()) { + ItemMeta im = item.getItemMeta(); + if(im.hasLore()) { + return 0; + } + + if(im.hasDisplayName()) + return 0; + + if(im.hasEnchants()) + return 0; + } + + Material m = item.getType(); + short dur = item.getDurability(); + + if(m.equals(Material.MOB_SPAWNER)) + return 0; + + for(Map.Entry> entry : items.entrySet()) { + for(ShopItem si : entry.getValue()) { + if( + si.getMaterial().equals(m) && + si.getDamage() == dur && + !si.isCommand() && + si.getSpawner() == null + ) { + return si.getSellPrice(); + } + } + } + return 0; + } + + public double getBuyPrice(ItemStack item) { + if(item == null) + return 0; + + if(item.hasItemMeta()) { + ItemMeta im = item.getItemMeta(); + if(im.hasLore()) { + return 0; + } + + if(im.hasDisplayName()) + return 0; + + if(im.hasEnchants()) + return 0; + } + + Material m = item.getType(); + short dur = item.getDurability(); + + if(m.equals(Material.MOB_SPAWNER)) + return 0; + + for(Map.Entry> entry : items.entrySet()) { + for(ShopItem si : entry.getValue()) { + if( + si.getMaterial().equals(m) && + si.getDamage() == dur && + !si.isCommand() && + si.getSpawner() == null + ) { + return si.getBuyPrice(); + } + } + } + return 0; + } + + public String getInvNameByShop(String input) { + return shopNames.get(input); + } + + public List getItems(String shop) { + return items.get(shop); + } + + public ShopItem getShopItem(Material m, int damage, String shop, String spawner, String cmd) { + for(ShopItem si : getItems(shop).stream().filter(s->m.equals(s.getMaterial())).collect(Collectors.toList())) { + if(si.getMaterial().equals(m) && si.getDamage() == damage) { + if(spawner != null) { + if(spawner.equalsIgnoreCase(si.getSpawner())) { + return si; + } else { + continue; + } + } + if(cmd != null) { + if(cmd.equalsIgnoreCase(si.getCmd())) { + return si; + } else { + continue; + } + } + return si; + } + } + + return null; + } + + public String getItemName(int slot) { + return mainMenu.get(slot); + } + + public String getItemName(ItemStack i) { + if (ItemUtils.isAirOrNull(i)) return "none"; + return NBTApi.getKey(i, "menu"); + } +} diff --git a/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopItem.java b/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopItem.java new file mode 100644 index 0000000..19f6208 --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopItem.java @@ -0,0 +1,84 @@ +package net.crankedpvp.shop.handlers; + +import org.bukkit.Material; + +import java.util.List; + +public class ShopItem { + + private Material m; + private boolean command; + + private int damage; + + private String path; + + private double buyPrice; + + private List lore; + private double sellPrice; + + private int quantity; + + String name; + String cmd; + String spawner; + + public ShopItem(Material material, int damage, boolean command, String path, double buyPrice, double sellPrice, int quanity, String name, String cmd, String spawner, List lore) { + this.m = material; + this.damage = damage; + this.command = command; + this.path = path; + this.buyPrice = buyPrice; + this.sellPrice = sellPrice; + this.quantity = quanity; + this.name = name; + this.cmd = cmd; + this.spawner = spawner; + this.lore = lore; + } + + public String getPath() { + return path; + } + + public boolean isCommand() { + return command; + } + + public double getBuyPrice() { + return buyPrice; + } + + public double getSellPrice() { + return sellPrice; + } + + public int getQuantity() { + return quantity; + } + + public Material getMaterial() { + return m; + } + + public int getDamage() { + return damage; + } + + public String getName() { + return name; + } + + public String getCmd() { + return cmd; + } + + public String getSpawner() { + return spawner; + } + + public List getLore() { + return lore; + } +} diff --git a/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopsFile.java b/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopsFile.java new file mode 100644 index 0000000..6a23fce --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/handlers/ShopsFile.java @@ -0,0 +1,28 @@ +package net.crankedpvp.shop.handlers; + +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; + +public class ShopsFile { + + private File f; + private FileConfiguration fc = new YamlConfiguration(); + + public ShopsFile(JavaPlugin instance) { + this.f = new File(instance.getDataFolder(), "shops.yml"); + if (!this.f.exists()) instance.saveResource("shops.yml", false); + + try { + fc.load(f); + } catch (Exception ev) { + ev.printStackTrace(); + } + } + + public FileConfiguration getFc() { + return fc; + } +} diff --git a/Shop/src/main/java/net/crankedpvp/shop/listeners/MainMenuClick.java b/Shop/src/main/java/net/crankedpvp/shop/listeners/MainMenuClick.java new file mode 100644 index 0000000..9e36ba4 --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/listeners/MainMenuClick.java @@ -0,0 +1,168 @@ +package net.crankedpvp.shop.listeners; + +import net.crankedpvp.shop.ShopPlugin; + +import net.crankedpvp.shop.handlers.ShopItem; +import net.crankedpvp.shop.nbt.NBTApi; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class MainMenuClick implements Listener { + + @EventHandler(ignoreCancelled = true) + public void onClick(InventoryClickEvent e) { + if(e.getCurrentItem() == null) + return; + + if(e.getClickedInventory() == null) + return; + + if(!e.getInventory().getName().equalsIgnoreCase(ShopPlugin.color(ShopPlugin.getInstance().getConfig().getString("shopMenuName")))) + return; + + e.setCancelled(true); + int slot = e.getSlot(); + + Player p = (Player) e.getWhoClicked(); + + if(p.getOpenInventory().getTopInventory().getSize()-1 < slot) + return; + + if (!p.getOpenInventory().getTopInventory().equals(e.getClickedInventory())) return; + + String shop = ShopPlugin.getShopHandler().getItemName(e.getCurrentItem()); + + if(shop == null) + return; + + List items = ShopPlugin.getShopHandler().getItems(shop); + String invName = ShopPlugin.getShopHandler().getInvNameByShop(shop); + if(invName == null) + return; + + int size = getSize(items.size()); + if(size < 54) { + size+=9; + } + Inventory inv = Bukkit.createInventory(null, size, invName); + for(ShopItem si : items) { + ItemStack item = new ItemStack(si.getMaterial(), si.getQuantity(), (byte) si.getDamage()).clone(); + item.setDurability((short)si.getDamage()); + ItemMeta im = item.getItemMeta(); + + im.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); + + List lore = new ArrayList<>(si.getLore()); + lore.add(" "); + + if(si.getBuyPrice() > 0) { + lore.add("§aBuy Price"); + lore.add("§a $"+NumberFormat.getInstance().format(si.getBuyPrice())+"/ea"); + lore.add(" "); + } + if(si.getSellPrice() > 0) { + lore.add("§cSell Price"); + lore.add("§c $"+NumberFormat.getInstance().format(si.getSellPrice())+"/ea"); + lore.add(" "); + } + + lore.add("§7§m "); + + int count = 0; + + if(si.isCommand()) { + if(si.getBuyPrice() > 0) { + lore.add("§aLeft-Click §7to buy §ax" + si.getQuantity()); + } + } else { + if(si.getBuyPrice() > 0) { + count = Arrays.asList(p.getOpenInventory().getBottomInventory().getContents()) + .stream().filter(l-> l == null).collect(Collectors.toList()).size()*si.getMaterial().getMaxStackSize(); + + lore.add("§aLeft-Click §7to buy §ax1"); + if(count > 0) { + lore.add("§aShift Left-Click §7to buy §ax"+si.getMaterial().getMaxStackSize()); + lore.add("§aMiddle §7to buy inventory §ax" + count); + lore.add(" "); + } + } + + if(si.getSellPrice() > 0) { + lore.add("§aRight-Click§7 to sell §ax1"); + lore.add("§aShift Right-Click§7 to sell §ax"+si.getMaterial().getMaxStackSize()); + } + } + + if(si.getName() != null) { + im.setDisplayName(si.getName()); + } + + im.setLore(lore); + item.setItemMeta(im); + + item = NBTApi.setKey(item, "buy", "" + (si.getBuyPrice() > 0)); + item = NBTApi.setKey(item, "sell", "" + (si.getSellPrice() > 0)); + item = NBTApi.setKey(item, "count", "" + count); + item = NBTApi.setKey(item, "damage", "" + si.getDamage()); + + if(si.getSpawner() != null) + item = NBTApi.setKey(item, "spawner", "" + si.getSpawner()); + if(si.isCommand()) { + item = NBTApi.setKey(item, "command", si.getCmd()); + } + + inv.addItem(item); + } + + ItemStack back = new ItemStack(Material.matchMaterial(ShopPlugin.getInstance().getConfig().getString("buttons.goBack.item.material"))); + ItemMeta backMeta = back.getItemMeta(); + + backMeta.setDisplayName(ShopPlugin.color(ShopPlugin.getInstance().getConfig().getString("buttons.goBack.item.name"))); + + List lore = new ArrayList<>(); + for(String line : ShopPlugin.getInstance().getConfig().getStringList("buttons.goBack.item.lore")) { + lore.add(ShopPlugin.color(line)); + } + + backMeta.setLore(lore); + back.setItemMeta(backMeta); + + inv.setItem(inv.getSize()-1, back); + + p.openInventory(inv); + } + + public static int getSlot(int size) { + size-=5; + + return size; + } + + private int getSize(int count) { + double number = count/9.0; + if(number > (int)number) { + number++; + } + + int f = (int)number*9; + if(f > 54) { + return 54; + } + + return f; + } +} diff --git a/Shop/src/main/java/net/crankedpvp/shop/listeners/ShopClick.java b/Shop/src/main/java/net/crankedpvp/shop/listeners/ShopClick.java new file mode 100644 index 0000000..388f36b --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/listeners/ShopClick.java @@ -0,0 +1,247 @@ +package net.crankedpvp.shop.listeners; + +import net.crankedpvp.shop.ShopPlugin; + +import net.crankedpvp.shop.commands.ShopCommand; +import net.crankedpvp.shop.handlers.ShopItem; +import net.crankedpvp.shop.nbt.NBTApi; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.text.NumberFormat; + +public class ShopClick implements Listener { + + @EventHandler(ignoreCancelled = true) + public void onClick(InventoryClickEvent e) { + if (e.getCurrentItem() == null) + return; + + if (e.getClickedInventory() == null) + return; + + String shop = ShopPlugin.getShopHandler().getShopNameByInvName(e.getInventory().getName()); + if (shop == null) + return; + + e.setCancelled(true); + + Player p = (Player) e.getWhoClicked(); + int slot = e.getSlot(); + + if (slot > p.getOpenInventory().getTopInventory().getSize()) + return; + + if (!p.getOpenInventory().getTopInventory().equals(e.getClickedInventory())) return; + + if (slot == e.getInventory().getSize() - 1) { + ShopCommand.open(p); + return; + } + + if (e.getCurrentItem().getType().equals(Material.AIR)) + return; + + ShopItem si = ShopPlugin.getShopHandler().getShopItem(e.getCurrentItem().getType(), + NBTApi.containsKey(e.getCurrentItem(), "damage") ? + Integer.parseInt(NBTApi.getKey(e.getCurrentItem(), "damage")) : + 0, + shop, + NBTApi.containsKey(e.getCurrentItem(), "spawner") ? NBTApi.getKey(e.getCurrentItem(), "spawner") : null, + NBTApi.containsKey(e.getCurrentItem(), "command") ? NBTApi.getKey(e.getCurrentItem(), "command") : null + ); + if (si == null) + return; + + ClickType ct = e.getClick(); + if (ct.equals(ClickType.LEFT)) { + if (si.getBuyPrice() <= 0) + return; + + + if (p.getInventory().firstEmpty() == -1) { + p.sendMessage("§c§l(!)§c Your inventory is full!"); + return; + } + if (!take(p, si.getBuyPrice())) { + return; + } + + if (si.isCommand()) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), si.getCmd().replaceAll("%player%", p.getName())); + return; + } + + if (si.getSpawner() != null) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), ("givespawner %player% " + si.getSpawner() + " 1").replaceAll("%player%", p.getName())); + return; + } + + p.getInventory().addItem(new ItemStack(si.getMaterial(), 1, (byte) si.getDamage())); + } else if (ct.equals(ClickType.SHIFT_LEFT)) { + if (si.isCommand()) + return; + + + if (p.getInventory().firstEmpty() == -1) { + p.sendMessage("§c§l(!)§c Your inventory is full!"); + return; + } + if (si.getBuyPrice() <= 0) + return; + + if (!take(p, si.getBuyPrice() * si.getMaterial().getMaxStackSize())) { + return; + } + + if (si.isCommand()) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), si.getCmd().replaceAll("%player%", p.getName())); + return; + } + if (si.getSpawner() != null) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), ("givespawner %player% " + si.getSpawner() + " " + 64).replaceAll("%player%", p.getName())); + return; + } + + p.getInventory().addItem(new ItemStack(si.getMaterial(), si.getMaterial().getMaxStackSize(), (byte) si.getDamage())); + } else if (ct.equals(ClickType.MIDDLE)) { + if (si.getBuyPrice() <= 0) + return; + + + if (p.getInventory().firstEmpty() == -1) { + p.sendMessage("§c§l(!)§c Your inventory is full!"); + return; + } + if (si.isCommand()) + return; + + int amount = Integer.parseInt(NBTApi.getKey(e.getCurrentItem(), "count")); + + if (!take(p, si.getBuyPrice() * amount)) { + return; + } + + if (si.isCommand()) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), si.getCmd().replaceAll("%player%", p.getName())); + return; + } + + if (si.getSpawner() != null) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), ("givespawner %player% " + si.getSpawner() + " " + amount).replaceAll("%player%", p.getName())); + return; + } + + for (int times = 0; times < amount / si.getMaterial().getMaxStackSize(); times++) { + p.getInventory().addItem(new ItemStack(si.getMaterial(), si.getMaterial().getMaxStackSize(), (byte) si.getDamage())); + } + } else if (ct.equals(ClickType.RIGHT)) { + if (si.getSellPrice() <= 0) + return; + + if (si.isCommand()) + return; + + if (!add(p, si.getSellPrice(), new ItemStack(si.getMaterial(), 1, (byte) si.getDamage()))) { + return; + } + } else if (ct.equals(ClickType.SHIFT_RIGHT)) { + if (si.getSellPrice() <= 0) + return; + + if (si.isCommand()) + return; + + if (!add(p, si.getSellPrice(), new ItemStack(si.getMaterial(), si.getMaterial().getMaxStackSize(), (byte) si.getDamage()))) { + return; + } + } + } + + private boolean take(Player p, double amount) { + if (ShopPlugin.getEcon().getBalance(p) < amount) { + p.sendMessage("§c§l(!) §cCannot afford this transaction!"); + return false; + } + + ShopPlugin.getEcon().withdrawPlayer(p, amount); + p.sendMessage("§c§l- $" + NumberFormat.getInstance().format(amount) + ""); + return true; + } + + private boolean add(Player p, double amount, ItemStack item) { + int count = 0; + + Material m = item.getType(); + short dur = item.getDurability(); + for (ItemStack i : p.getInventory().getContents()) { + if (i == null) + continue; + + if (!i.getEnchantments().isEmpty()) + continue; + + if (i.hasItemMeta()) { + ItemMeta im = i.getItemMeta(); + if (im.hasDisplayName()) + continue; + if (im.hasLore()) + continue; + } + + if (i.getType().equals(m) && i.getDurability() == dur) { + count += i.getAmount(); + } + } + + if (count < item.getAmount()) { + p.sendMessage("§cYou do not have enough materials to sell."); + return false; + } + + count = item.getAmount(); + + for (int i = 0; i < p.getInventory().getSize(); i++) { + if (count <= 0) { + break; + } + + ItemStack it = p.getInventory().getItem(i); + if (it == null) + continue; + + if (!it.getEnchantments().isEmpty()) + continue; + + if (it.hasItemMeta()) { + ItemMeta im = it.getItemMeta(); + if (im.hasDisplayName()) + continue; + if (im.hasLore()) + continue; + } + + if (it.getType().equals(m) && it.getDurability() == dur) { + if (count >= it.getAmount()) { + count -= it.getAmount(); + p.getInventory().setItem(i, new ItemStack(Material.AIR)); + p.updateInventory(); + } else { + it.setAmount(it.getAmount() - count); + break; + } + } + } + + ShopPlugin.getEcon().depositPlayer(p, amount * item.getAmount()); + p.sendMessage("§a§l+ $" + NumberFormat.getInstance().format(amount * item.getAmount()) + ""); + return true; + } +} diff --git a/Shop/src/main/java/net/crankedpvp/shop/nbt/NBTApi.java b/Shop/src/main/java/net/crankedpvp/shop/nbt/NBTApi.java new file mode 100644 index 0000000..ab15ff9 --- /dev/null +++ b/Shop/src/main/java/net/crankedpvp/shop/nbt/NBTApi.java @@ -0,0 +1,24 @@ +package net.crankedpvp.shop.nbt; + +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.inventory.ItemStack; + +public class NBTApi { + + public static ItemStack setKey(ItemStack i, String key, String value) { + NBTItem il = new NBTItem(i); + il.setString(key, value); + return il.getItem(); + } + + public static String getKey(ItemStack i, String key) { + NBTItem il = new NBTItem(i); + return il.getString(key); + } + + public static boolean containsKey(ItemStack i, String key) { + NBTItem il = new NBTItem(i); + return il.hasKey(key); + } + +} diff --git a/Shop/src/main/resources/config.yml b/Shop/src/main/resources/config.yml new file mode 100644 index 0000000..03d4d6b --- /dev/null +++ b/Shop/src/main/resources/config.yml @@ -0,0 +1,173 @@ +shopMenuName: "&8Shop Menu" +# Size of the main GUI, valid values are 9, 18, 27, 36, 45 and 54 +shopMenuSize: 18 + +# Sell hand command settings +sellHand: + # When set to true, players will be able to sell any quantity of the item (the price will be calculated from the base price) + allowAllQuantites: true + # When set to true, /sell hand will work same way as /sell handall does + sellsAllItems: false + +# Sell all command settings +sellAll: + # When set to true, players will get a detailed summary with prices of each item stack sold + detailedSummary: false + +buttons: + goBack: + item: + # Material name, full list can be found here: http://wiki.brcdev.net/Materials + material: Arrow + # Amount of the item + amount: 1 + # (optional) Data value, for example 1 for WOOD:1 means spruce wood planks + damage: 0 + # (optional) Custom name + name: "&c<- Go Back" + # (optional) Lore, can contain multiple lines + lore: + - "&7Click to go back." + # Slot in each shop's GUI + slot: 49 + +shopMenuItems: + 1: + item: + material: POTION + quantity: 1 + damage: 0 + name: "&a&lPotion Shop" + lore: + - "&7Click to view this category." + shop: "PotionShop" + slot: 0 + 2: + item: + material: REDSTONE + quantity: 1 + damage: 0 + name: "&a&lRaid Shop" + lore: + - "&7Click to view this category." + shop: "RaidShop" + slot: 1 + 3: + item: + material: MOB_SPAWNER + quantity: 1 + damage: 0 + name: "&a&lSpawner Shop" + lore: + - "&7Click to view this category." + shop: "Spawnershop" + slot: 2 + 4: + item: + material: SMOOTH_BRICK + quantity: 1 + damage: 0 + name: "&a&lBuilding Blocks" + lore: + - "&7Click to view this category." + shop: "Buildingshop" + slot: 3 + 5: + item: + material: EMERALD + quantity: 1 + damage: 0 + name: "&a&lOres and Gems" + lore: + - "&7Click to view this category." + shop: "Oreandgemshop" + slot: 4 + 6: + item: + material: COOKED_BEEF + quantity: 1 + damage: 0 + name: "&a&lFood and Farming" + lore: + - "&7Click to view this category." + shop: "foodandfarmingshop" + slot: 5 + 7: + item: + material: BLAZE_ROD + quantity: 1 + damage: 0 + name: "&a&lMob Drops" + lore: + - "&7Click to view this category." + shop: "MobdropShop" + slot: 6 + 8: + item: + material: EYE_OF_ENDER + quantity: 1 + damage: 0 + name: "&a&lSpeciality" + lore: + - "&7Click to view this category." + shop: "specialityshop" + slot: 7 + 9: + item: + material: BREWING_STAND_ITEM + quantity: 1 + damage: 0 + name: "&a&lBrewing" + lore: + - "&7Click to view this category." + shop: "BrewingShop" + slot: 8 + 10: + item: + material: WOOL + quantity: 1 + damage: 0 + name: "&a&lWool" + lore: + - "&7Click to view this category." + shop: "WoolShop" + slot: 11 + 11: + item: + material: GLASS + quantity: 1 + damage: 0 + name: "&a&lGlass" + lore: + - "&7Click to view this category." + shop: "GlassShop" + slot: 12 + 12: + item: + material: CLAY + quantity: 1 + damage: 0 + name: "&a&lClay" + lore: + - "&7Click to view this category." + shop: "ClayShop" + slot: 14 + 13: + item: + material: RED_ROSE + quantity: 1 + damage: 0 + name: "&a&lFlowers" + lore: + - "&7Click to view this category." + shop: "FlowerShop" + slot: 15 + +specialElements: + balance: + item: + material: GOLD_INGOT + quantity: 1 + name: "&6&lYour balance" + lore: + - "&7$%balance%" \ No newline at end of file diff --git a/Shop/src/main/resources/plugin.yml b/Shop/src/main/resources/plugin.yml new file mode 100644 index 0000000..64d2bc1 --- /dev/null +++ b/Shop/src/main/resources/plugin.yml @@ -0,0 +1,12 @@ +name: CrankedShop +main: net.crankedpvp.shop.ShopPlugin +version: 1.0 +depend: + - CrankedUtils + - Vault + - Essentials +commands: + shop: + description: "Server Items Shop" + sell: + description: "Sell Inventory Items" \ No newline at end of file diff --git a/Shop/src/main/resources/shops.yml b/Shop/src/main/resources/shops.yml new file mode 100644 index 0000000..36267e2 --- /dev/null +++ b/Shop/src/main/resources/shops.yml @@ -0,0 +1,2206 @@ +shops: + PotionShop: + name: "&7Shop Items (Potion Shop)" + items: + 1: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lRegeneration Potion II (0:22)" + damage: 8225 + commands: + - "give %player% 373:8225 1" + buyPrice: 120 + slot: 11 + 2: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lRegeneration Splash II (0:16)" + damage: 16417 + commands: + - "give %player% 373:16417 1" + buyPrice: 145 + slot: 12 + 3: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lSwiftness Potion II (1:30)" + damage: 8226 + commands: + - "give %player% 373:8226 1" + buyPrice: 30 + slot: 13 + 4: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lSwiftness Splash II (1:07)" + damage: 16418 + commands: + - "give %player% 373:16418 1" + buyPrice: 55 + slot: 14 + 5: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lWater Breathing Potion (8:00)" + damage: 8269 + commands: + - "give %player% 373:8269 1" + buyPrice: 225 + slot: 15 + 6: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lStrength Splash II (1:07)" + damage: 16425 + commands: + - "give %player% 373:16425 1" + buyPrice: 110 + slot: 30 + 7: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lStrength Potion II (1:30)" + damage: 8233 + commands: + - "give %player% 373:8233 1" + buyPrice: 85 + slot: 31 + 8: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lInstant Health II" + damage: 16421 + commands: + - "give %player% 373:16421 1" + buyPrice: 75 + slot: 22 + 9: + type: command + item: + material: POTION + quantity: 1 + name: "&a&lFire Resistance Potion (8:00)" + damage: 8259 + commands: + - "give %player% 373:8259 1" + buyPrice: 1000 + slot: 32 + RaidShop: + name: "&7Shop Items (Raid Shop)" + items: + 1: + type: item + item: + material: REDSTONE + quantity: 1 + buyPrice: 125 + sellPrice: 0.23 + slot: 0 + 2: + type: item + item: + material: PISTON_STICKY_BASE + quantity: 1 + buyPrice: 1750 + sellPrice: 50 + slot: 1 + 3: + type: item + item: + material: PISTON_BASE + quantity: 1 + buyPrice: 900 + sellPrice: 25 + slot: 2 + 4: + type: item + item: + material: STONE + quantity: 1 + buyPrice: 5.47 + sellPrice: 1.48 + slot: 3 + 5: + type: item + item: + material: GLOWSTONE + quantity: 1 + buyPrice: 7.03 + sellPrice: 2.50 + slot: 4 + 6: + type: item + item: + material: SAND + quantity: 1 + buyPrice: 3.05 + sellPrice: 0.05 + slot: 5 + 7: + type: item + item: + material: ICE + quantity: 1 + buyPrice: 250 + sellPrice: 0.50 + slot: 6 + 8: + type: item + item: + material: WEB + quantity: 1 + buyPrice: 40 + sellPrice: 0.20 + slot: 7 + 9: + type: item + item: + material: SPONGE + quantity: 1 + buyPrice: 8000 + sellPrice: 100 + slot: 8 + 10: + type: item + item: + material: QUARTZ + quantity: 1 + buyPrice: 3.05 + sellPrice: 0.01 + slot: 9 + 11: + type: item + item: + material: TNT + quantity: 1 + buyPrice: 360 + sellPrice: 8.12 + slot: 10 + 12: + type: item + item: + material: GLASS + quantity: 1 + buyPrice: 4.06 + sellPrice: 1.27 + slot: 11 + 13: + type: item + item: + material: WATER_BUCKET + quantity: 1 + buyPrice: 1250 + sellPrice: 50 + slot: 12 + 14: + type: item + item: + material: LAVA_BUCKET + quantity: 16 + buyPrice: 1750 + sellPrice: 1 + slot: 13 + 15: + type: item + item: + material: STEP + quantity: 1 + buyPrice: 80.86 + sellPrice: 12.28 + slot: 14 + 16: + type: item + item: + material: REDSTONE_TORCH_ON + quantity: 1 + buyPrice: 25 + sellPrice: 5 + slot: 15 + 17: + type: item + item: + material: REDSTONE_COMPARATOR + quantity: 1 + buyPrice: 150 + sellPrice: 25 + slot: 16 + 18: + type: item + item: + material: DIODE + quantity: 1 + buyPrice: 250 + sellPrice: 10 + slot: 17 + 19: + type: item + item: + material: DISPENSER + quantity: 1 + buyPrice: 2000 + sellPrice: 100 + slot: 18 + 20: + type: item + item: + material: DROPPER + quantity: 1 + buyPrice: 100 + sellPrice: 25 + slot: 19 + 21: + type: item + item: + material: LADDER + quantity: 1 + buyPrice: 10 + sellPrice: 0.50 + slot: 20 + 22: + type: item + item: + material: MONSTER_EGG + quantity: 1 + damage: 50 + buyPrice: 800000 + sellPrice: 25000 + slot: 21 + 23: + type: item + item: + material: STONE_BUTTON + quantity: 1 + buyPrice: 5.50 + sellPrice: 0.20 + slot: 22 + 24: + type: item + item: + material: LEVER + quantity: 1 + buyPrice: 20 + sellPrice: 0.50 + slot: 23 + Spawnershop: + name: "&7Shop Items (Spawner Shop)" + items: + 1: + type: item + item: + spawner: true + name: "&a&lIron Golem &fSpawner" + mob: VILLAGERGOLEM + quantity: 1 + buyPrice: 8000000 + sellPrice: -1 + slot: 0 + 2: + type: item + item: + spawner: true + name: "&a&lBlaze &fSpawner" + mob: BLAZE + quantity: 1 + buyPrice: 2800000 + sellPrice: -1 + slot: 1 + 3: + type: item + item: + spawner: true + name: "&a&lCreeper &fSpawner" + mob: CREEPER + quantity: 1 + buyPrice: 2750000 + sellPrice: -1 + slot: 2 + 4: + type: item + item: + spawner: true + name: "&a&lEnderman &fSpawner" + mob: ENDERMAN + quantity: 1 + buyPrice: 1800000 + sellPrice: -1 + slot: 3 + 5: + type: item + item: + spawner: true + name: "&a&lGhast &fSpawner" + mob: GHAST + quantity: 1 + buyPrice: 30000000 + sellPrice: -1 + slot: 4 + 6: + type: item + item: + spawner: true + name: "&a&lSlime &fSpawner" + mob: SLIME + quantity: 1 + buyPrice: 3000000 + sellPrice: -1 + slot: 5 + 7: + type: item + item: + spawner: true + name: "&a&lCave Spider &fSpawner" + mob: CAVESPIDER + quantity: 1 + buyPrice: 1750000 + sellPrice: -1 + slot: 6 + 8: + type: item + item: + spawner: true + name: "&a&lSpider &fSpawner" + mob: SPIDER + quantity: 1 + buyPrice: 1750000 + sellPrice: -1 + slot: 7 + 9: + type: item + item: + spawner: true + name: "&a&lSkeleton &fSpawner" + mob: SKELETON + quantity: 1 + buyPrice: 3500000 + sellPrice: -1 + slot: 8 + 10: + type: item + item: + spawner: true + name: "&a&lZombie &fSpawner" + mob: ZOMBIE + quantity: 1 + buyPrice: 2500000 + sellPrice: -1 + slot: 9 + 11: + type: item + item: + spawner: true + name: "&a&lCow &fSpawner" + mob: COW + quantity: 1 + buyPrice: 1250000 + sellPrice: -1 + slot: 10 + 12: + type: item + item: + spawner: true + name: "&a&lSheep &fSpawner" + mob: SHEEP + quantity: 1 + buyPrice: 200000 + sellPrice: -1 + slot: 11 + 13: + type: item + item: + spawner: true + name: "&a&lChicken &fSpawner" + mob: CHICKEN + quantity: 1 + buyPrice: 250000 + sellPrice: -1 + slot: 12 + 14: + type: item + item: + spawner: true + name: "&a&lPig &fSpawner" + mob: PIG + quantity: 1 + buyPrice: 250000 + sellPrice: -1 + slot: 13 + 15: + type: item + item: + spawner: true + name: "&a&lWitch &fSpawner" + mob: WITCH + quantity: 1 + buyPrice: 40000000 + sellPrice: -1 + slot: 14 + 16: + type: item + item: + spawner: true + name: "&a&lVillager &fSpawner" + mob: VILLAGER + quantity: 1 + buyPrice: 24000000 + sellPrice: -1 + slot: 15 + 17: + type: item + item: + spawner: true + name: "&a&lSilver Fish &fSpawner" + mob: SILVERFISH + quantity: 1 + buyPrice: 50000000 + sellPrice: -1 + slot: 16 + Buildingshop: + name: "&7Shop Items (Building Shop)" + items: + 1: + type: item + item: + material: GRASS + quantity: 1 + buyPrice: 3 + sellPrice: 0.69 + slot: 0 + 2: + type: item + item: + material: LOG + quantity: 1 + buyPrice: 8.12 + sellPrice: 2.03 + slot: 1 + 3: + type: item + item: + material: LOG + damage: 2 + quantity: 1 + buyPrice: 8.12 + sellPrice: 2.03 + slot: 2 + 4: + type: item + item: + material: LOG + damage: 3 + quantity: 1 + buyPrice: 8.12 + sellPrice: 2.03 + slot: 3 + 5: + type: item + item: + material: DIRT + quantity: 1 + buyPrice: 3 + sellPrice: 0.69 + slot: 4 + 6: + type: item + item: + material: DIRT + damage: 2 + quantity: 1 + buyPrice: 10.94 + sellPrice: 3.75 + slot: 5 + 7: + type: item + item: + material: MYCEL + quantity: 1 + buyPrice: 10.16 + sellPrice: 3.33 + slot: 6 + 8: + type: item + item: + material: STONE + quantity: 1 + buyPrice: 5.47 + sellPrice: 1.48 + slot: 7 + 9: + type: item + item: + material: COBBLESTONE + quantity: 1 + buyPrice: 4.06 + sellPrice: 1.02 + slot: 8 + 10: + type: item + item: + material: SMOOTH_BRICK + quantity: 1 + buyPrice: 6.56 + sellPrice: 1.23 + slot: 9 + 11: + type: item + item: + material: SMOOTH_BRICK + damage: 1 + quantity: 1 + buyPrice: 6.56 + sellPrice: 1.23 + slot: 10 + 12: + type: item + item: + material: SMOOTH_BRICK + damage: 2 + quantity: 1 + buyPrice: 6.56 + sellPrice: 1.23 + slot: 11 + 13: + type: item + item: + material: SMOOTH_BRICK + damage: 3 + quantity: 1 + buyPrice: 6.56 + sellPrice: 1.23 + slot: 12 + 14: + type: item + item: + material: SANDSTONE + quantity: 1 + buyPrice: 12.19 + sellPrice: 2.98 + slot: 13 + 15: + type: item + item: + material: SANDSTONE + damage: 1 + quantity: 1 + buyPrice: 12.19 + sellPrice: 2.98 + slot: 14 + 16: + type: item + item: + material: SANDSTONE + damage: 2 + quantity: 1 + buyPrice: 48.78 + sellPrice: 10.76 + slot: 15 + 17: + type: item + item: + material: QUARTZ_BLOCK + quantity: 1 + buyPrice: 12.19 + sellPrice: 1.78 + slot: 16 + 18: + type: item + item: + material: QUARTZ_BLOCK + damage: 1 + quantity: 1 + buyPrice: 48.78 + sellPrice: 10.76 + slot: 17 + 19: + type: item + item: + material: QUARTZ_BLOCK + damage: 2 + quantity: 1 + buyPrice: 12.19 + sellPrice: 1.78 + slot: 18 + 20: + type: item + item: + material: NETHERRACK + damage: 2 + quantity: 1 + buyPrice: 2.34 + sellPrice: 0.94 + slot: 19 + 21: + type: item + item: + material: NETHER_BRICK + quantity: 1 + buyPrice: 5.47 + sellPrice: 1.28 + slot: 20 + 22: + type: item + item: + material: GLOWSTONE + quantity: 1 + buyPrice: 7.03 + sellPrice: 2.50 + slot: 21 + 23: + type: item + item: + material: SOUL_SAND + quantity: 1 + buyPrice: 7.06 + sellPrice: 1.28 + slot: 22 + 24: + type: item + item: + material: ENDER_STONE + quantity: 1 + buyPrice: 7.03 + sellPrice: 1.18 + slot: 23 + 25: + type: item + item: + material: SAND + quantity: 1 + buyPrice: 3.05 + sellPrice: 0.05 + slot: 24 + 26: + type: item + item: + material: GRAVEL + quantity: 1 + buyPrice: 3.52 + sellPrice: 0.12 + slot: 25 + 27: + type: item + item: + material: OBSIDIAN + quantity: 1 + buyPrice: 14.84 + sellPrice: 5.47 + slot: 26 + 28: + type: item + item: + material: ICE + quantity: 1 + buyPrice: 50 + sellPrice: 0.50 + slot: 27 + 29: + type: item + item: + material: PACKED_ICE + quantity: 1 + buyPrice: 75 + sellPrice: 0.75 + slot: 28 + 30: + type: item + item: + material: SNOW_BLOCK + quantity: 1 + buyPrice: 250 + sellPrice: -1 + slot: 29 + Oreandgemshop: + name: "&7Shop Items (Ores and Gem Shop)" + items: + 1: + type: item + item: + material: IRON_BLOCK + quantity: 1 + buyPrice: 1170 + sellPrice: 360 + slot: 0 + 2: + type: item + item: + material: IRON_INGOT + quantity: 1 + buyPrice: 130 + sellPrice: 40 + slot: 1 + 3: + type: item + item: + material: GOLD_INGOT + quantity: 1 + buyPrice: 100 + sellPrice: 50 + slot: 2 + 4: + type: item + item: + material: COAL + quantity: 1 + buyPrice: 9.06 + sellPrice: 0.94 + slot: 3 + 5: + type: item + item: + material: COAL_BLOCK + quantity: 1 + buyPrice: 80 + sellPrice: 8 + slot: 4 + 6: + type: item + item: + material: GOLD_BLOCK + quantity: 1 + buyPrice: 1850 + sellPrice: 450 + slot: 5 + 7: + type: item + item: + material: INK_SACK + damage: 4 + quantity: 1 + buyPrice: 18.12 + sellPrice: 1.25 + slot: 6 + 8: + type: item + item: + material: LAPIS_BLOCK + quantity: 1 + buyPrice: 160 + sellPrice: 9 + slot: 7 + 9: + type: item + item: + material: REDSTONE + quantity: 1 + buyPrice: 16.25 + sellPrice: 0.23 + slot: 8 + 10: + type: item + item: + material: REDSTONE_BLOCK + quantity: 1 + buyPrice: 195 + sellPrice: 10 + slot: 9 + 11: + type: item + item: + material: DIAMOND + quantity: 1 + buyPrice: 390 + sellPrice: 100 + slot: 10 + 12: + type: item + item: + material: DIAMOND_BLOCK + quantity: 1 + buyPrice: 3500 + sellPrice: 800 + slot: 11 + 13: + type: item + item: + material: EMERALD + quantity: 1 + buyPrice: 1150 + sellPrice: 200 + slot: 12 + 14: + type: item + item: + material: EMERALD_BLOCK + quantity: 1 + buyPrice: 8775 + sellPrice: 1250 + slot: 13 + foodandfarmingshop: + name: "&7Shop Items (Food and Farming Shop)" + items: + 1: + type: item + item: + material: CACTUS + quantity: 1 + buyPrice: 18.75 + sellPrice: 1.88 + slot: 0 + 2: + type: item + item: + material: SUGAR_CANE + quantity: 1 + buyPrice: 16.25 + sellPrice: 3.12 + slot: 1 + 3: + type: item + item: + material: MELON + quantity: 1 + buyPrice: 20.31 + sellPrice: 3.14 + slot: 2 + 4: + type: item + item: + material: PUMPKIN + quantity: 1 + buyPrice: 325 + sellPrice: 2.65 + slot: 3 + 5: + type: item + item: + material: WHEAT + quantity: 1 + buyPrice: 11.88 + sellPrice: 6.25 + slot: 4 + 6: + type: item + item: + material: APPLE + quantity: 1 + buyPrice: 25 + sellPrice: 10 + slot: 5 + 7: + type: item + item: + material: GOLDEN_APPLE + quantity: 1 + buyPrice: 1500 + sellPrice: 125 + slot: 6 + 8: + type: item + item: + material: CAKE + quantity: 1 + buyPrice: 50 + sellPrice: 5 + slot: 7 + 9: + type: item + item: + material: BREAD + quantity: 1 + buyPrice: 31.25 + sellPrice: 12.75 + slot: 8 + 10: + type: item + item: + material: COOKED_BEEF + quantity: 1 + buyPrice: 11.88 + sellPrice: 10 + slot: 9 + 11: + type: item + item: + material: GRILLED_PORK + quantity: 1 + buyPrice: 11.88 + sellPrice: 1.88 + slot: 10 + 12: + type: item + item: + material: CARROT_ITEM + quantity: 1 + buyPrice: 25 + sellPrice: 1.56 + slot: 11 + 13: + type: item + item: + material: POTATO_ITEM + quantity: 1 + buyPrice: 50 + sellPrice: -1 + slot: 12 + MobdropShop: + name: "&7Shop Items (Mob Drops Shop)" + items: + 1: + type: item + item: + material: SULPHUR + quantity: 1 + buyPrice: 25 + sellPrice: 4.38 + slot: 0 + 2: + type: item + item: + material: ARROW + quantity: 1 + buyPrice: 6.25 + sellPrice: 2.19 + slot: 1 + 3: + type: item + item: + material: FEATHER + quantity: 1 + buyPrice: 8.12 + sellPrice: 1.09 + slot: 2 + 4: + type: item + item: + material: BLAZE_ROD + quantity: 1 + buyPrice: 62.5 + sellPrice: 28.75 + slot: 3 + 5: + type: item + item: + material: WATER_LILY + quantity: 1 + buyPrice: 20 + sellPrice: 5 + slot: 4 + 6: + type: item + item: + material: ROTTEN_FLESH + quantity: 1 + buyPrice: 2.5 + sellPrice: 1.09 + slot: 5 + 7: + type: item + item: + material: STRING + quantity: 1 + buyPrice: 8.12 + sellPrice: 1.88 + slot: 6 + 8: + type: item + item: + material: LEATHER + quantity: 1 + buyPrice: 16.25 + sellPrice: 5.62 + slot: 7 + 9: + type: item + item: + material: ENDER_PEARL + quantity: 1 + buyPrice: 25 + sellPrice: 10 + slot: 8 + 10: + type: item + item: + material: BONE + quantity: 1 + buyPrice: 6.25 + sellPrice: 0.50 + slot: 9 + 11: + type: item + item: + material: EMERALD + quantity: 1 + buyPrice: 1150 + sellPrice: 200 + slot: 10 + 12: + type: item + item: + material: DIAMOND + quantity: 1 + buyPrice: 390 + sellPrice: 100 + slot: 11 + 13: + type: item + item: + material: GOLD_INGOT + quantity: 1 + buyPrice: 100 + sellPrice: 50 + slot: 12 + specialityshop: + name: "&7Shop Items (Speciality Shop)" + items: + 1: + type: item + item: + material: CHEST + quantity: 1 + buyPrice: 15 + sellPrice: -1 + slot: 0 + 2: + type: item + item: + material: TRAPPED_CHEST + quantity: 1 + buyPrice: 150 + sellPrice: -1 + slot: 1 + 3: + type: item + item: + material: ENCHANTMENT_TABLE + damage: 2 + quantity: 1 + buyPrice: 25000 + sellPrice: -1 + slot: 2 + 4: + type: item + item: + material: ANVIL + quantity: 1 + buyPrice: 1500 + sellPrice: 400 + slot: 3 + 5: + type: item + item: + material: ENDER_CHEST + quantity: 1 + buyPrice: 6430 + sellPrice: -1 + slot: 4 + 6: + type: item + item: + material: BEACON + damage: 2 + quantity: 1 + buyPrice: 250000 + sellPrice: 17500 + slot: 5 + 7: + type: item + item: + material: FLINT_AND_STEEL + quantity: 1 + buyPrice: 145 + sellPrice: 25 + slot: 6 + 8: + type: item + item: + material: DAYLIGHT_DETECTOR + quantity: 1 + buyPrice: 640 + sellPrice: 250 + slot: 7 + 9: + type: item + item: + material: TRIPWIRE_HOOK + quantity: 1 + buyPrice: 100 + sellPrice: -1 + slot: 8 + 10: + type: item + item: + material: PISTON_STICKY_BASE + quantity: 1 + buyPrice: 325 + sellPrice: 50 + slot: 9 + 11: + type: item + item: + material: PISTON_BASE + quantity: 1 + buyPrice: 195 + sellPrice: 25 + slot: 10 + 12: + type: item + item: + material: REDSTONE_LAMP_OFF + damage: 3 + quantity: 1 + buyPrice: 730 + sellPrice: 200 + slot: 11 + 13: + type: item + item: + material: WEB + quantity: 1 + buyPrice: 40 + sellPrice: 0.20 + slot: 12 + 14: + type: item + item: + material: DISPENSER + quantity: 1 + buyPrice: 2000 + sellPrice: 100 + slot: 13 + 15: + type: item + item: + material: ICE + quantity: 1 + buyPrice: 250 + sellPrice: 0.50 + slot: 14 + 16: + type: item + item: + material: PACKED_ICE + quantity: 1 + buyPrice: 75 + sellPrice: 0.75 + slot: 15 + 17: + type: item + item: + material: SPONGE + quantity: 1 + buyPrice: 2000 + sellPrice: 100 + slot: 16 + 18: + type: item + item: + material: FISHING_ROD + quantity: 1 + buyPrice: 175 + sellPrice: -1 + slot: 17 + 19: + type: command + item: + name: "&e&lChunk Hopper" + lore: + - "&7Items that are dropped into this chunk" + - "&7will automatically enter this hopper." + - "" + - "&a&lPOSITIVES" + - "&f&l* &7Better in performance" + - "&f&l* &7x10 Times Faster" + - "&f&l* &7Efficient" + - "&f&l* &7Only 1 per chunk" + - "&f&l* &7Filter (Option)" + - "&f&l* &7Cheaper" + - "" + - "&c&lNEGATIVES" + - "&f&l* &7None" + - "" + material: HOPPER + quantity: 1 + buyPrice: 500 + sellPrice: -1 + commands: + - "givehopper %player% 1" + slot: 31 + 20: + type: command + item: + name: "&a&lVertical Gen Bucket &7(Cobblestone)" + lore: + - "&7Click here to purchase this gen bucket." + - "" + material: LAVA_BUCKET + quantity: 1 + buyPrice: 400 + sellPrice: -1 + commands: + - "genbucket give %player% cobble vertical 1" + slot: 36 + 21: + type: command + item: + name: "&a&lHorizontal Gen Bucket &7(Cobblestone)" + lore: + - "&7Click here to purchase this gen bucket." + - "" + material: LAVA_BUCKET + quantity: 1 + buyPrice: 400 + sellPrice: -1 + commands: + - "genbucket give %player% cobble horizontal 1" + slot: 37 + 22: + type: command + item: + name: "&a&lVertical Gen Bucket &7(Obsidian)" + lore: + - "&7Click here to purchase this gen bucket." + - "" + material: LAVA_BUCKET + quantity: 1 + buyPrice: 600 + sellPrice: -1 + commands: + - "genbucket give %player% obsidian vertical 1" + slot: 38 + 23: + type: command + item: + name: "&a&lHorizontal Gen Bucket &7(Obsidian)" + lore: + - "&7Click here to purchase this gen bucket." + - "" + material: LAVA_BUCKET + quantity: 1 + buyPrice: 600 + sellPrice: -1 + commands: + - "genbucket give %player% obsidian horizontal 1" + slot: 39 + 24: + type: command + item: + name: "&a&lVertical Gen Bucket &7(Cobblestone)" + lore: + - "&7Click here to purchase this gen bucket." + - "" + material: LAVA_BUCKET + quantity: 32 + buyPrice: 12800 + sellPrice: -1 + commands: + - "genbucket give %player% cobble vertical 32" + slot: 41 + 25: + type: command + item: + name: "&a&lHorizontal Gen Bucket &7(Cobblestone)" + lore: + - "&7Click here to purchase this gen bucket." + - "" + material: LAVA_BUCKET + quantity: 32 + buyPrice: 12800 + sellPrice: -1 + commands: + - "genbucket give %player% cobble horizontal 32" + slot: 42 + 26: + type: command + item: + name: "&a&lVertical Gen Bucket &7(Obsidian)" + lore: + - "&7Click here to purchase this gen bucket." + - "" + material: LAVA_BUCKET + quantity: 32 + buyPrice: 19200 + sellPrice: -1 + commands: + - "genbucket give %player% obsidian vertical 32" + slot: 43 + 27: + type: command + item: + name: "&a&lHorizontal Gen Bucket &7(Obsidian)" + lore: + - "&7Click here to purchase this gen bucket." + - "" + material: LAVA_BUCKET + quantity: 32 + buyPrice: 19200 + sellPrice: -1 + commands: + - "genbucket give %player% obsidian horizontal 32" + slot: 44 + BrewingShop: + name: "&7Shop Items (Brewing Shop)" + items: + 1: + type: item + item: + material: SPIDER_EYE + quantity: 1 + buyPrice: 130 + sellPrice: 7.5 + slot: 0 + 2: + type: item + item: + material: GHAST_TEAR + quantity: 1 + buyPrice: 97.50 + sellPrice: 40 + slot: 1 + 3: + type: item + item: + material: BREWING_STAND_ITEM + quantity: 1 + buyPrice: 315 + sellPrice: -1 + slot: 2 + 4: + type: item + item: + material: POTION + quantity: 1 + buyPrice: -1 + sellPrice: -1 + slot: 3 + 5: + type: item + item: + material: GOLDEN_CARROT + quantity: 1 + buyPrice: 73.12 + sellPrice: 25.5 + slot: 4 + 6: + type: item + item: + material: GLOWSTONE_DUST + quantity: 1 + buyPrice: 5 + sellPrice: 0.10 + slot: 5 + 7: + type: item + item: + material: SUGAR + quantity: 1 + buyPrice: 5 + sellPrice: 0.10 + slot: 6 + 8: + type: item + item: + material: SLIME_BALL + quantity: 1 + buyPrice: 200 + sellPrice: 25 + slot: 7 + 9: + type: item + item: + material: NETHER_STALK + quantity: 1 + buyPrice: 16.25 + sellPrice: 4.06 + slot: 8 + 10: + type: item + item: + material: SPECKLED_MELON + quantity: 1 + buyPrice: 38.75 + sellPrice: 12.25 + slot: 9 + WoolShop: + name: "&7Shop Items (Wool Shop)" + items: + 1: + type: item + item: + material: WOOL + quantity: 1 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 0 + 2: + type: item + item: + material: WOOL + quantity: 1 + damage: 1 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 1 + 3: + type: item + item: + material: WOOL + quantity: 1 + damage: 2 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 2 + 4: + type: item + item: + material: WOOL + quantity: 1 + damage: 3 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 3 + 5: + type: item + item: + material: WOOL + quantity: 1 + damage: 4 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 4 + 6: + type: item + item: + material: WOOL + quantity: 1 + damage: 5 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 5 + 7: + type: item + item: + material: WOOL + quantity: 1 + damage: 6 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 6 + 8: + type: item + item: + material: WOOL + quantity: 1 + damage: 7 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 7 + 9: + type: item + item: + material: WOOL + quantity: 1 + damage: 8 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 8 + 10: + type: item + item: + material: WOOL + quantity: 1 + damage: 9 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 9 + 11: + type: item + item: + material: WOOL + quantity: 1 + damage: 10 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 10 + 12: + type: item + item: + material: WOOL + quantity: 1 + damage: 11 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 11 + 13: + type: item + item: + material: WOOL + quantity: 1 + damage: 12 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 12 + 14: + type: item + item: + material: WOOL + quantity: 1 + damage: 13 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 13 + 15: + type: item + item: + material: WOOL + quantity: 1 + damage: 14 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 14 + 16: + type: item + item: + material: WOOL + quantity: 1 + damage: 15 + buyPrice: 2.34 + sellPrice: 1.25 + slot: 15 + 17: + type: item + item: + material: CARPET + quantity: 1 + damage: 13 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 16 + 18: + type: item + item: + material: CARPET + quantity: 1 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 17 + 19: + type: item + item: + material: CARPET + quantity: 1 + damage: 1 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 18 + 20: + type: item + item: + material: CARPET + quantity: 1 + damage: 2 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 19 + 21: + type: item + item: + material: CARPET + quantity: 1 + damage: 3 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 20 + 22: + type: item + item: + material: CARPET + quantity: 1 + damage: 4 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 21 + 23: + type: item + item: + material: CARPET + quantity: 1 + damage: 5 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 22 + 24: + type: item + item: + material: CARPET + quantity: 1 + damage: 6 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 23 + 25: + type: item + item: + material: CARPET + quantity: 1 + damage: 7 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 24 + 26: + type: item + item: + material: CARPET + quantity: 1 + damage: 8 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 25 + 27: + type: item + item: + material: CARPET + quantity: 1 + damage: 9 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 26 + 28: + type: item + item: + material: CARPET + quantity: 1 + damage: 10 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 27 + 29: + type: item + item: + material: CARPET + quantity: 1 + damage: 11 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 28 + 30: + type: item + item: + material: CARPET + quantity: 1 + damage: 12 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 29 + GlassShop: + name: "&7Shop Items (Glass Shop)" + items: + 1: + type: item + item: + material: GLASS + quantity: 1 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 0 + 2: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 1 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 1 + 3: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 2 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 2 + 4: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 3 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 3 + 5: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 4 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 4 + 6: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 5 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 5 + 7: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 6 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 6 + 8: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 7 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 7 + 9: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 8 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 8 + 10: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 9 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 9 + 11: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 10 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 10 + 12: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 11 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 11 + 13: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 12 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 12 + 14: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 13 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 13 + 15: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 14 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 14 + 16: + type: item + item: + material: STAINED_GLASS + quantity: 1 + damage: 15 + buyPrice: 4.06 + sellPrice: 0.88 + slot: 15 + 17: + type: item + item: + material: THIN_GLASS + quantity: 1 + damage: 13 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 16 + 18: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + buyPrice: 2.34 + sellPrice: 0.05 + slot: 17 + 19: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 1 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 18 + 20: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 2 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 19 + 21: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 3 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 20 + 22: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 4 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 21 + 23: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 5 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 22 + 24: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 6 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 23 + 25: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 7 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 24 + 26: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 8 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 25 + 27: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 9 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 26 + 28: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 10 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 27 + 29: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 11 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 28 + 30: + type: item + item: + material: STAINED_GLASS_PANE + quantity: 1 + damage: 12 + buyPrice: 1.56 + sellPrice: 0.05 + slot: 29 + ClayShop: + name: "&7Shop Items (Clay Shop)" + items: + 1: + type: item + item: + material: STAINED_CLAY + quantity: 1 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 0 + 2: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 1 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 1 + 3: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 2 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 2 + 4: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 3 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 3 + 5: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 4 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 4 + 6: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 5 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 5 + 7: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 6 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 6 + 8: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 7 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 7 + 9: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 8 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 8 + 10: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 9 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 9 + 11: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 10 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 10 + 12: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 11 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 11 + 13: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 12 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 12 + 14: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 13 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 13 + 15: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 14 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 14 + 16: + type: item + item: + material: STAINED_CLAY + quantity: 1 + damage: 15 + buyPrice: 6.25 + sellPrice: 1.25 + slot: 15 + FlowerShop: + name: "&7Shop Items (Flower Shop)" + items: + 1: + type: item + item: + material: RED_ROSE + quantity: 1 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 0 + 2: + type: item + item: + material: RED_ROSE + quantity: 1 + damage: 1 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 1 + 3: + type: item + item: + material: RED_ROSE + quantity: 1 + damage: 2 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 2 + 4: + type: item + item: + material: RED_ROSE + quantity: 1 + damage: 3 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 3 + 5: + type: item + item: + material: RED_ROSE + quantity: 1 + damage: 4 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 4 + 6: + type: item + item: + material: RED_ROSE + quantity: 1 + damage: 5 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 5 + 7: + type: item + item: + material: RED_ROSE + quantity: 1 + damage: 6 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 6 + 8: + type: item + item: + material: RED_ROSE + quantity: 1 + damage: 7 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 7 + 9: + type: item + item: + material: RED_ROSE + quantity: 1 + damage: 8 + buyPrice: 18.75 + sellPrice: 9.88 + slot: 8 + 10: + type: item + item: + material: FLOWER_POT_ITEM + quantity: 1 + buyPrice: 300 + sellPrice: 150 + slot: 9 \ No newline at end of file diff --git a/Showcase/pom.xml b/Showcase/pom.xml new file mode 100644 index 0000000..64e6ff2 --- /dev/null +++ b/Showcase/pom.xml @@ -0,0 +1,33 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Showcase + + + 8 + 8 + + + + + + Utils + net.crankedpvp + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + \ No newline at end of file diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/ShowcasePlugin.java b/Showcase/src/main/java/net/crankedpvp/showcase/ShowcasePlugin.java new file mode 100644 index 0000000..019a049 --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/ShowcasePlugin.java @@ -0,0 +1,52 @@ +package net.crankedpvp.showcase; + +import com.google.gson.reflect.TypeToken; +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.showcase.commands.ShowcaseCommand; +import net.crankedpvp.showcase.data.ShowcaseItem; +import net.crankedpvp.showcase.data.ShowcaseManager; +import net.crankedpvp.showcase.typeadapter.ShowcaseItemSerializer; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.gson.Gson; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +import java.lang.reflect.Type; +import java.util.List; + +@Getter +public class ShowcasePlugin extends JavaPlugin { + + @Getter + public static ShowcasePlugin instance; + + private final Type listType = new TypeToken>(){}.getType(); + + private ShowcaseManager showcaseManager; + private CommandManager commandManager; + private Gson gson; + + public void onEnable() { + instance = this; + + this.gson = StorageUtils.getInstance() + .getGson() + .newBuilder() + .registerTypeAdapter(this.listType, new ShowcaseItemSerializer()).setLenient() + .create(); + + this.showcaseManager = new ShowcaseManager(this); + this.showcaseManager.loadAll(); + this.commandManager = new CommandManager(this, false); + this.commandManager.register(new ShowcaseCommand()); + Bukkit.getScheduler().runTaskTimerAsynchronously(this, ()-> { + showcaseManager.saveAll(); + }, 40L, 10*60*20); + } + + public void onDisable() { + this.showcaseManager.saveAll(); + instance = null; + } +} diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/commands/ShowcaseCommand.java b/Showcase/src/main/java/net/crankedpvp/showcase/commands/ShowcaseCommand.java new file mode 100644 index 0000000..8fe9bcb --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/commands/ShowcaseCommand.java @@ -0,0 +1,27 @@ +package net.crankedpvp.showcase.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.showcase.guis.ShowcaseGUI; +import org.bukkit.entity.Player; + +@Command("showcase") +@Alias("showcases") +public class ShowcaseCommand extends CommandBase { + + @Default + public void onDefault(Player player) { + + } + + @Default + public void onShowcaseOther(Player player, @Optional @Completion("#players") Player other) { + ShowcaseGUI showcaseGUI; + if (other != null) { + showcaseGUI = new ShowcaseGUI(other); + } else { + showcaseGUI = new ShowcaseGUI(player); + } + showcaseGUI.getPaginatedGui().open(player); + } +} diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcaseItem.java b/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcaseItem.java new file mode 100644 index 0000000..19396f8 --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcaseItem.java @@ -0,0 +1,15 @@ +package net.crankedpvp.showcase.data; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.inventory.ItemStack; + +@Getter +@Setter +@AllArgsConstructor +public class ShowcaseItem { + private ItemStack showcaseItemStack; + private long showcaseTime; + +} diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcaseManager.java b/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcaseManager.java new file mode 100644 index 0000000..817040e --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcaseManager.java @@ -0,0 +1,33 @@ +package net.crankedpvp.showcase.data; + +import net.crankedpvp.showcase.ShowcasePlugin; +import net.crankedpvp.storageutils.struct.NewSaveLoadManager; + +import java.util.UUID; + +public class ShowcaseManager extends NewSaveLoadManager { + + public ShowcaseManager(ShowcasePlugin plugin) { + super(plugin, plugin.getGson(), "/data", ShowcasePlayer.class); + } + + public ShowcasePlayer getShowcasePlayer(UUID uuid) { + if (!containsKey(uuid)) { + ShowcasePlayer showcasePlayer = new ShowcasePlayer(uuid); + addToCache(showcasePlayer); + } + + return getFromCache(uuid); + } + + @Override + public String serialize(UUID uuid) { + return String.valueOf(uuid); + } + + @Override + public UUID deserialize(String s) { + return UUID.fromString(s); + } + +} \ No newline at end of file diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcasePlayer.java b/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcasePlayer.java new file mode 100644 index 0000000..0bfd831 --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/data/ShowcasePlayer.java @@ -0,0 +1,39 @@ +package net.crankedpvp.showcase.data; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.storageutils.struct.NewKeyToSave; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +@Getter +@Setter +public class ShowcasePlayer implements NewKeyToSave { + + private UUID uuid; + private final List showcaseItems; + + public ShowcasePlayer(UUID uuid) { + this.uuid = uuid; + this.showcaseItems = new ArrayList<>(); + } + + @Override + public UUID getKey() { + return this.uuid; + } + + @Override + public void setKey(UUID uuid) { + this.uuid = uuid; + } + + public void addShowcaseItem(ItemStack item) { + this.showcaseItems.add(new ShowcaseItem(item, System.currentTimeMillis())); + } + + public void removeShowcaseItem(ShowcaseItem showcaseItem) { + this.showcaseItems.remove(showcaseItem); + } +} diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseConfirmAddItemGUI.java b/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseConfirmAddItemGUI.java new file mode 100644 index 0000000..4980d57 --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseConfirmAddItemGUI.java @@ -0,0 +1,32 @@ +package net.crankedpvp.showcase.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.showcase.ShowcasePlugin; +import net.crankedpvp.showcase.data.ShowcaseItem; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +@Getter +public class ShowcaseConfirmAddItemGUI { + private Gui gui; + public ShowcaseConfirmAddItemGUI(Player player, ItemStack item) { + this.gui = new Gui(1, "Showcase Confirm"); + gui.setDefaultClickAction(event -> event.setCancelled(true)); + this.gui.setItem(0, new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.LIME.getWoolData()).setName("&a&lConfirm").addLore("&7Click to confirm adding this item to your showcase").colorize().build(), event -> { + ShowcasePlugin.getInstance().getShowcaseManager().getShowcasePlayer(player.getUniqueId()).addShowcaseItem(item.clone()); + player.getInventory().remove(item); + ShowcaseGUI showcaseGUI = new ShowcaseGUI(player); + showcaseGUI.getPaginatedGui().open(player); + })); + this.gui.setItem(4, new GuiItem(item)); + this.gui.setItem(8, new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.RED.getWoolData()).setName("&c&lCancel").addLore("&7Click to cancel adding this item to your showcase").colorize().build(), event -> { + ShowcaseGUI showcaseGUI = new ShowcaseGUI(player); + showcaseGUI.getPaginatedGui().open(player); + })); + } +} diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseConfirmDeleteItemGUI.java b/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseConfirmDeleteItemGUI.java new file mode 100644 index 0000000..2a1b647 --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseConfirmDeleteItemGUI.java @@ -0,0 +1,30 @@ +package net.crankedpvp.showcase.guis; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.showcase.ShowcasePlugin; +import net.crankedpvp.showcase.data.ShowcaseItem; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +@Getter +public class ShowcaseConfirmDeleteItemGUI { + private Gui gui; + public ShowcaseConfirmDeleteItemGUI(Player player, ShowcaseItem showcaseItem) { + this.gui = new Gui(1, "Showcase Confirm"); + gui.setDefaultClickAction(event -> event.setCancelled(true)); + this.gui.setItem(0, new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.LIME.getWoolData()).setName("&a&lConfirm").addLore("&7Click to confirm deleting this item from your showcase").colorize().build(), event -> { + ShowcasePlugin.getInstance().getShowcaseManager().getShowcasePlayer(player.getUniqueId()).removeShowcaseItem(showcaseItem); + ShowcaseGUI showcaseGUI = new ShowcaseGUI(player); + showcaseGUI.getPaginatedGui().open(player); + })); + this.gui.setItem(4, new GuiItem(showcaseItem.getShowcaseItemStack())); + this.gui.setItem(8, new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.RED.getWoolData()).setName("&c&lCancel").addLore("&7Click to cancel deleting this item from your showcase").colorize().build(), event -> { + ShowcaseGUI showcaseGUI = new ShowcaseGUI(player); + showcaseGUI.getPaginatedGui().open(player); + })); + } +} diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseGUI.java b/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseGUI.java new file mode 100644 index 0000000..7983489 --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/guis/ShowcaseGUI.java @@ -0,0 +1,54 @@ +package net.crankedpvp.showcase.guis; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.showcase.ShowcasePlugin; +import net.crankedpvp.showcase.data.ShowcaseItem; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.ItemStack; + +import java.text.SimpleDateFormat; +import java.util.Date; + +@Getter +public class ShowcaseGUI { + private PaginatedGui paginatedGui; + private Player player; + private final SimpleDateFormat format = new SimpleDateFormat("MMMM dd, yyyy"); + private static final ItemStack PREV_PAGE_ITEM = new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.").colorize().build(); + private static final ItemStack NEXT_PAGE_ITEM = new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.").colorize().build(); + public ShowcaseGUI(Player player) { + this.player = player; + this.paginatedGui = new PaginatedGui(6, 54, player.getName() + "'s Showcase"); + this.paginatedGui.getFiller().fillBottom(new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.BLACK.getWoolData()).setName("&7").colorize().build())); + this.paginatedGui.setDefaultClickAction(event -> { + if (event.getClickedInventory().getType() == InventoryType.PLAYER && event.getWhoClicked().getUniqueId().equals(player.getUniqueId())) { + event.setCancelled(true); + ShowcaseConfirmAddItemGUI showcaseConfirmAddItemGUI = new ShowcaseConfirmAddItemGUI((Player) event.getWhoClicked(),event.getCurrentItem().clone()); + showcaseConfirmAddItemGUI.getGui().open(event.getWhoClicked()); + } else { + event.setCancelled(true); + } + }); + this.paginatedGui.setItem(6, 1, new GuiItem(PREV_PAGE_ITEM, event -> this.paginatedGui.previous())); + this.paginatedGui.setItem(6, 9, new GuiItem(NEXT_PAGE_ITEM, event -> this.paginatedGui.next())); + + for (ShowcaseItem showcaseItem : ShowcasePlugin.getInstance().getShowcaseManager().getShowcasePlayer(player.getUniqueId()).getShowcaseItems()) { + this.getPaginatedGui().addItem(getShowcaseGuiItem(showcaseItem)); + } + } + + public GuiItem getShowcaseGuiItem(ShowcaseItem showcaseItem) { + return new GuiItem(new ItemBuilder(showcaseItem.getShowcaseItemStack().clone()).addLore("").addLore("&c&l" + format.format(new Date(showcaseItem.getShowcaseTime()))).colorize().build(), event -> { + if (event.isRightClick() && event.getWhoClicked().getUniqueId().equals(player.getUniqueId())) { + ShowcaseConfirmDeleteItemGUI showcaseConfirmDeleteItemGUI = new ShowcaseConfirmDeleteItemGUI((Player) event.getWhoClicked(), showcaseItem); + showcaseConfirmDeleteItemGUI.getGui().open(event.getWhoClicked()); + } + }); + } +} diff --git a/Showcase/src/main/java/net/crankedpvp/showcase/typeadapter/ShowcaseItemSerializer.java b/Showcase/src/main/java/net/crankedpvp/showcase/typeadapter/ShowcaseItemSerializer.java new file mode 100644 index 0000000..32a6d95 --- /dev/null +++ b/Showcase/src/main/java/net/crankedpvp/showcase/typeadapter/ShowcaseItemSerializer.java @@ -0,0 +1,28 @@ +package net.crankedpvp.showcase.typeadapter; + +import net.crankedpvp.crankedutils.utils.serializer.item.ItemStackSerializer; +import net.crankedpvp.showcase.data.ShowcaseItem; +import net.crankedpvp.storageutils.gson.JsonArray; +import net.crankedpvp.storageutils.gson.JsonObject; +import net.crankedpvp.storageutils.gson.JsonSerializationContext; +import net.crankedpvp.storageutils.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.List; + +public class ShowcaseItemSerializer implements JsonSerializer> { + + @Override + public net.crankedpvp.storageutils.gson.JsonElement serialize(List showcaseItems, Type type, JsonSerializationContext context) { + JsonArray jsonArray = new JsonArray(); + + for (ShowcaseItem showcaseItem : showcaseItems) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("showcaseTime", showcaseItem.getShowcaseTime()); + jsonObject.addProperty("showcaseItemStack", ItemStackSerializer.serialize(showcaseItem.getShowcaseItemStack())); + jsonArray.add(jsonObject); + } + + return jsonArray; + } +} diff --git a/Showcase/src/main/resources/plugin.yml b/Showcase/src/main/resources/plugin.yml new file mode 100644 index 0000000..eb9745c --- /dev/null +++ b/Showcase/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedShowcase +main: net.crankedpvp.showcase.ShowcasePlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - StorageUtil \ No newline at end of file diff --git a/SlotBot/pom.xml b/SlotBot/pom.xml new file mode 100644 index 0000000..c10c8ed --- /dev/null +++ b/SlotBot/pom.xml @@ -0,0 +1,34 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + SlotBot + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + LootTable + net.crankedpvp + + + net.crankedpvp + LootFilter + + + + \ No newline at end of file diff --git a/SlotBot/src/main/java/net/crankedpvp/slotbot/SlotBotAPI.java b/SlotBot/src/main/java/net/crankedpvp/slotbot/SlotBotAPI.java new file mode 100644 index 0000000..5b98471 --- /dev/null +++ b/SlotBot/src/main/java/net/crankedpvp/slotbot/SlotBotAPI.java @@ -0,0 +1,32 @@ +package net.crankedpvp.slotbot; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CustomItemUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.slotbot.struct.SlotBotType; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class SlotBotAPI { + + public static boolean isSlotBot(final ItemStack itemStack) { + return CustomItemUtils.getCrankedCustomItem(itemStack).equals("slotBotTicket"); + } + + public static SlotBotType getSlotBotType(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return null; + if(!isSlotBot(itemStack)) return null; + NBTItem nbtItem = new NBTItem(itemStack); + if (nbtItem.getString("slotBotType") == null) return SlotBotType.SLOT_BOT; + if (nbtItem.getString("slotBotType").equals("")) return SlotBotType.SLOT_BOT; + return SlotBotType.valueOf(nbtItem.getString("slotBotType")); + } + + public static List getRewards() { + return LootTableAPI.getAllLootFromLootTable(LootTableType.SLOTBOT); + } + +} diff --git a/SlotBot/src/main/java/net/crankedpvp/slotbot/SlotBotPlugin.java b/SlotBot/src/main/java/net/crankedpvp/slotbot/SlotBotPlugin.java new file mode 100644 index 0000000..8e4ae03 --- /dev/null +++ b/SlotBot/src/main/java/net/crankedpvp/slotbot/SlotBotPlugin.java @@ -0,0 +1,31 @@ +package net.crankedpvp.slotbot; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.slotbot.commands.SlotBotCommand; +import net.crankedpvp.slotbot.listeners.SlotBotTempFix; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class SlotBotPlugin extends JavaPlugin { + + @Getter + private static SlotBotPlugin instance; + + @Override + public void onEnable() { + + instance = this; + CommandManager commandManager = new CommandManager(this); + commandManager.register(new SlotBotCommand(this)); + + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new SlotBotTempFix(this), this); + + } + + @Override + public void onDisable() { + instance = null; + } +} diff --git a/SlotBot/src/main/java/net/crankedpvp/slotbot/commands/SlotBotCommand.java b/SlotBot/src/main/java/net/crankedpvp/slotbot/commands/SlotBotCommand.java new file mode 100644 index 0000000..6da12ee --- /dev/null +++ b/SlotBot/src/main/java/net/crankedpvp/slotbot/commands/SlotBotCommand.java @@ -0,0 +1,52 @@ +package net.crankedpvp.slotbot.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.slotbot.SlotBotPlugin; +import net.crankedpvp.slotbot.inventory.SlotBotInventory; +import net.crankedpvp.slotbot.struct.SlotBotType; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("slot") +@Alias({"slotbot", "bot", "roll", "rollbot"}) +public class SlotBotCommand extends CommandBase { + + private final SlotBotPlugin plugin; + public SlotBotCommand(SlotBotPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final CommandSender commandSender) { + + final SlotBotInventory slotBotInventory = new SlotBotInventory((Player) commandSender); + slotBotInventory.getSlotBotInventory().open((Player)commandSender); + + } + + @SubCommand("give") + @Permission("cranked.admin") + @WrongUsage("&c/slotbot give [amount]") + public void giveCommand(final CommandSender commandSender, @Completion("#players") final Player receiver, @Optional Integer amount) { + if(amount == null) amount = 1; + receiver.getInventory().addItem(SlotBotType.SLOT_BOT.build(amount)); + } + + @SubCommand("heroic") + @Permission("cranked.admin") + @WrongUsage("&c/slotbot give [amount]") + public void giveHeroicCommand(final CommandSender commandSender, @Completion("#players") final Player receiver, @Optional Integer amount) { + if(amount == null) amount = 1; + receiver.getInventory().addItem(SlotBotType.HEROIC_SLOT_BOT.build(amount)); + } + + @SubCommand("mastery") + @Permission("cranked.admin") + @WrongUsage("&c/slotbot give [amount]") + public void giveMasteryCommand(final CommandSender commandSender, @Completion("#players") final Player receiver, @Optional Integer amount) { + if(amount == null) amount = 1; + receiver.getInventory().addItem(SlotBotType.MASTERY_SLOT_BOT.build(amount)); + } + +} diff --git a/SlotBot/src/main/java/net/crankedpvp/slotbot/inventory/LootPreviewInventory.java b/SlotBot/src/main/java/net/crankedpvp/slotbot/inventory/LootPreviewInventory.java new file mode 100644 index 0000000..19f83a5 --- /dev/null +++ b/SlotBot/src/main/java/net/crankedpvp/slotbot/inventory/LootPreviewInventory.java @@ -0,0 +1,64 @@ +package net.crankedpvp.slotbot.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.slotbot.SlotBotAPI; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Objects; + +public class LootPreviewInventory { + + private final PaginatedGui slotBotPreviewInventory; + + public PaginatedGui getUI() { + return this.slotBotPreviewInventory; + } + + + public LootPreviewInventory(Player player) { + + this.slotBotPreviewInventory = new PaginatedGui(6, 28, "Roll Bot Loot"); + this.slotBotPreviewInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.slotBotPreviewInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + ItemStack prevPage = new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.").colorize().build(); + ItemStack nextPage = new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.").colorize().build(); + this.slotBotPreviewInventory.setItem(6, 1, new GuiItem(prevPage, event -> { + this.slotBotPreviewInventory.previous(); + event.setCancelled(true); + })); + this.slotBotPreviewInventory.setItem(6, 9, new GuiItem(nextPage, event -> { + this.slotBotPreviewInventory.next(); + event.setCancelled(true); + })); + + + this.slotBotPreviewInventory.updateItem(6, 5, new GuiItem(new ItemBuilder(Material.BED, "&cReturn to Roll Bot").colorize().build(), event -> { + player.closeInventory(); + SlotBotInventory slotBotInventory = new SlotBotInventory(player); + slotBotInventory.getSlotBotInventory().open(player); + })); + + SlotBotAPI.getRewards().stream() + .filter(Objects::nonNull) + .filter(ItemStack::hasItemMeta) + .forEach(itemStack -> this.slotBotPreviewInventory.addItem(new GuiItem(itemStack, event -> { + if(player.hasPermission("cranked.admin")) player.getInventory().addItem(itemStack); + }))); + ; + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cCranked&fPvP")); + item.setItemMeta(meta); + return item; + } +} diff --git a/SlotBot/src/main/java/net/crankedpvp/slotbot/inventory/SlotBotInventory.java b/SlotBot/src/main/java/net/crankedpvp/slotbot/inventory/SlotBotInventory.java new file mode 100644 index 0000000..7aa0f6f --- /dev/null +++ b/SlotBot/src/main/java/net/crankedpvp/slotbot/inventory/SlotBotInventory.java @@ -0,0 +1,310 @@ +package net.crankedpvp.slotbot.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.lootfilter.LootFilterAPI; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.slotbot.SlotBotAPI; +import net.crankedpvp.slotbot.SlotBotPlugin; +import net.crankedpvp.slotbot.struct.GameStatus; +import net.crankedpvp.slotbot.struct.SlotBotType; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; + +public class SlotBotInventory { + + private GameStatus gameStatus = GameStatus.WAITING; + private final Player player; + private boolean isSpinning = false; + private int insertedTickets = 0; + private int taskID = 0; + private boolean given = false; + + private SlotBotType slotBotType = null; + + @Getter + private final Gui slotBotInventory; + + public SlotBotInventory(Player player) { + this.player = player; + this.slotBotInventory = new Gui(3, "Slot Bot"); + this.slotBotInventory.setDefaultClickAction(event -> event.setCancelled(true)); + + handleInventoryClosure(); + enableSlotBotAddition(); + setupHowToPlayItem(); + setupLootTableItem(); + updateSpinItem(); + setupGlassSlots(); + } + + + private void putSlotBotInMenu() { + ItemStack itemStack = this.slotBotType.build(); + int index = (3 + this.insertedTickets); + this.slotBotInventory.updateItem(1, index, new GuiItem(getAvailableRollGlass())); + this.slotBotInventory.updateItem(3, index, new GuiItem(getAvailableRollGlass())); + this.slotBotInventory.updateItem(2, index, new GuiItem(itemStack, event -> { + this.slotBotInventory.updateItem(2, index, new GuiItem(getRewardSlot())); + this.slotBotInventory.updateItem(1, index, new GuiItem(getFillingGlass())); + this.slotBotInventory.updateItem(3, index, new GuiItem(getFillingGlass())); + this.insertedTickets--; + this.player.getInventory().addItem(itemStack); + this.updateSpinItem(); + })); + } + + private void updateSpinItem() { + ItemStack spinItem = getSpinItem(); + this.slotBotInventory.updateItem(2, 9, new GuiItem(spinItem, event -> { + if(this.isSpinning) { + handleItemRewarding(); + return; + } + + if(checkNoInsertedTickets()) return; + this.gameStatus = GameStatus.SPINNING; + this.isSpinning = true; + updateSpinItem(); + updateItemTask(player); + this.slotBotInventory.updateItem(2, 3, new GuiItem(getRewardRowGlass())); + this.slotBotInventory.updateItem(2, 7, new GuiItem(getRewardRowGlass())); + })); + } + + private boolean checkNoInsertedTickets() { + if(this.insertedTickets == 0) { + this.player.sendMessage(CC.translate("&cYou have no tickets inserted")); + this.player.playSound(this.player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return true; + } + return false; + } + + private void handleItemRewarding() { + SlotBotPlugin plugin = SlotBotPlugin.getInstance(); + plugin.getServer().getScheduler().cancelTask(this.taskID); + int rewards = this.insertedTickets; + this.insertedTickets = 0; + this.isSpinning = false; + this.gameStatus = GameStatus.FINISHING; + if(this.player.getOpenInventory().getTopInventory().getTitle().equals("Slot Bot")) { + for(int i = 0; i < rewards; i++) { + ItemStack randomReward = LootTableAPI.getRandomLootItem(LootTableType.SLOTBOT); + this.slotBotInventory.updateItem(12 + i, new GuiItem(randomReward)); + LootFilterAPI.giveLootTableItem(player, LootTableType.SLOTBOT, randomReward); + } + resetSlotBotInventory(); + return; + } + + for(int i = 0; i < rewards; i++) { + ItemStack randomReward = this.slotBotType.getRandomItem(); + LootFilterAPI.giveLootTableItem(player, LootTableType.SLOTBOT, randomReward); + } + } + + private void moveItemSlotsDownOneRow() { + for(int i = 0; i < this.insertedTickets; i++) { + this.slotBotInventory.updateItem(21 + i, Objects.requireNonNull(this.slotBotInventory.getGuiItem(21 + i - 9))); + this.slotBotInventory.updateItem(21 + i - 9, Objects.requireNonNull(this.slotBotInventory.getGuiItem(21 + i - 9 - 9))); + this.slotBotInventory.updateItem(21 + i - 9 - 9, new GuiItem(this.slotBotType.getRandomItem())); + } + } + + private void updateItemTask(Player player) { + SlotBotPlugin plugin = SlotBotPlugin.getInstance(); + AtomicInteger counter = new AtomicInteger(); + this.taskID = player.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, () -> { + if(!player.getOpenInventory().getTopInventory().getTitle().contains("Slot Bot")) plugin.getServer().getScheduler().cancelTask(this.taskID); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 1.0F, 1.0F); + moveItemSlotsDownOneRow(); + counter.getAndIncrement(); + if(counter.get() == 20) { + plugin.getServer().getScheduler().cancelTask(this.taskID); + plugin.getServer().getScheduler().runTaskLater(plugin, this::handleItemRewarding, 5L); + } + }, 0L, 4L); + } + + private void resetSlotBotInventory() { + SlotBotPlugin.getInstance().getServer().getScheduler().runTaskLater(SlotBotPlugin.getInstance(), () -> { + setupGlassSlots(); + updateSpinItem(); + this.isSpinning = false; + this.slotBotInventory.removeItem(2, 3); + this.slotBotInventory.removeItem(2, 7); + this.gameStatus = GameStatus.WAITING; + }, 40L); + } + + private ItemStack getSpinItem() { + Material material = this.insertedTickets == 0 ? Material.MAGMA_CREAM : Material.SLIME_BALL; + String name = this.gameStatus == GameStatus.SPINNING ? "&a&lSpinning..." : this.insertedTickets == 0 ? "&c&lSpin (&7Missing Ticket&c&l)" : "&a&lSpin (&7" + this.insertedTickets + " Tickets&a&l)"; + + List lore = + this.isSpinning ? + Arrays.asList( + "&7Your roll bot tickets are", + "&7currently rolling in the machine", + "", + "&7Click to skip the animation") + + : this.insertedTickets == 0 ? Arrays.asList( + "&7You must insert at least", + "&7one ticket before you can", + "&7roll the roll bot machine") : Collections.singletonList("&7Click to spin the bot"); + + ItemBuilder itemBuilder = new ItemBuilder(material, name, lore).colorize(); + return itemBuilder.colorize().build(); + } + + private void enableSlotBotAddition() { + this.slotBotInventory.setPlayerInventoryAction(event -> { + if(this.isSpinning) return; + if(this.gameStatus == GameStatus.FINISHING) return; + ItemStack clickedItem = event.getCurrentItem(); + if(!SlotBotAPI.isSlotBot(clickedItem)) return; + if(this.slotBotType != null && !this.slotBotType.equals(clickedItem)) return; + if(this.insertedTickets == 3) return; + this.insertedTickets++; + final int amount = clickedItem.getAmount(); + this.slotBotType = SlotBotAPI.getSlotBotType(clickedItem); + if (amount <= 1) { + event.setCurrentItem(null); + } else { + clickedItem.setAmount(amount - 1); + event.setCurrentItem(clickedItem); + } + putSlotBotInMenu(); + this.updateSpinItem(); + this.player.updateInventory(); + }); + } + + + + + + + + + + + + private void setupLootTableItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.BEACON, "&b&lLoot Table", + "&7Click to view all of the possible", + "&7loot inside of the roll bot machine" + ); + this.slotBotInventory.setItem(1, 1, new GuiItem(itemBuilder.colorize().build(), event -> { + this.player.closeInventory(); + LootPreviewInventory lootPreviewInventory = new LootPreviewInventory(this.player); + lootPreviewInventory.getUI().open(this.player); + })); + } + + private void handleInventoryClosure() { + this.slotBotInventory.setCloseGuiAction(inventoryCloseEvent -> { + if(inventoryCloseEvent.getPlayer().hasMetadata("SlotBotReturnTickets") || this.given) { + System.out.println("[SlotBot] RETURNING INVENTORY CLOSURE - DUPE PREVENTION"); + return; + } + if(this.isSpinning) { + SlotBotPlugin.getInstance().getServer().getScheduler().cancelTask(this.taskID); + for(int i = 0; i < this.insertedTickets; i++) { + ItemStack randomReward = this.slotBotType.getRandomItem(); + LootFilterAPI.giveLootTableItem(player, LootTableType.SLOTBOT, randomReward); + } + this.given = true; + return; + } + + if(insertedTickets == 0) return; + this.player.getInventory().addItem(this.slotBotType.build(this.insertedTickets)); + this.player.sendMessage(CC.translate("&aYour &n" + this.insertedTickets + "&r &aroll tickets were returned to your inventory")); + this.given = true; + }); + } + + private void setupHowToPlayItem() { + ItemBuilder itemBuilder = new ItemBuilder(Material.BOOK, "&b&lHow to Play", + "&e&l1. &7Insert up to 3 roll tickets", + "&7into the machine from your inventory", + "", + "&e&l2. &7Click \"Spin\" (on the right) to roll.", + "&7the bot or, click \"Return\" (on the left)", + "&7to withdraw all inserted tickets", + "", + "&e&l3. &7Watch as the bot spins items.", + "&7The item which lands on the reward slot", + "&7when the bot finishes spinning, is the item", + "&7that you'll receive.", + "", + "&e&lTIP: &7Exiting the machine early will", + "&7give you the rewards you would of won if", + "&7you had stayed in the machine while spinning.", + "&7If the machine is not spinning when you exit,", + "&7your tickets will be refunded and no items will", + "&7be given." + ); + + this.slotBotInventory.setItem(3, 1, new GuiItem(itemBuilder.colorize().build())); + } + + private ItemStack getRewardSlot() { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.LIME.getData(), "&a&lReward Slot", + "&7The item which lands on this slot", + "&7will be the item that you receive").colorize().build(); + } + + private ItemStack getRewardRowGlass() { + return new ItemBuilder(Material.STAINED_GLASS_PANE, 1, DyeColor.BLACK.getData(), "&a&lReward Row", + "&7The item(s) which land in this row", + "&7are the item(s) you will receive").setGlowing().colorize().build(); + } + + private ItemStack getFillingGlass() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(""); + item.setItemMeta(meta); + return item; + } + + private ItemStack getAvailableRollGlass() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.WHITE.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(" "); + item.setItemMeta(meta); + return item; + } + + private void setupGlassSlots() { + this.slotBotInventory.updateItem(2, 4, new GuiItem(getRewardSlot())); + this.slotBotInventory.updateItem(2, 5, new GuiItem(getRewardSlot())); + this.slotBotInventory.updateItem(2, 6, new GuiItem(getRewardSlot())); + + this.slotBotInventory.updateItem(1, 4, new GuiItem(getFillingGlass())); + this.slotBotInventory.updateItem(1, 5, new GuiItem(getFillingGlass())); + this.slotBotInventory.updateItem(1, 6, new GuiItem(getFillingGlass())); + + this.slotBotInventory.updateItem(3, 4, new GuiItem(getFillingGlass())); + this.slotBotInventory.updateItem(3, 5, new GuiItem(getFillingGlass())); + this.slotBotInventory.updateItem(3, 6, new GuiItem(getFillingGlass())); + } +} diff --git a/SlotBot/src/main/java/net/crankedpvp/slotbot/listeners/SlotBotTempFix.java b/SlotBot/src/main/java/net/crankedpvp/slotbot/listeners/SlotBotTempFix.java new file mode 100644 index 0000000..8db51e9 --- /dev/null +++ b/SlotBot/src/main/java/net/crankedpvp/slotbot/listeners/SlotBotTempFix.java @@ -0,0 +1,32 @@ +package net.crankedpvp.slotbot.listeners; + +import net.crankedpvp.slotbot.SlotBotPlugin; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.metadata.FixedMetadataValue; + +public class SlotBotTempFix implements Listener { + + private SlotBotPlugin plugin; + public SlotBotTempFix(SlotBotPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void playerJoin(PlayerJoinEvent event) { + if(event.getPlayer() == null) return; + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> { + if(!event.getPlayer().isOnline()) return; + event.getPlayer().removeMetadata("SlotBotReturnTickets", this.plugin); + }, 50L); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void playerQuit(PlayerQuitEvent event) { + if(event.getPlayer() == null) return; + event.getPlayer().setMetadata("SlotBotReturnTickets", new FixedMetadataValue(this.plugin, "SlotBotReturnTickets")); + } +} diff --git a/SlotBot/src/main/java/net/crankedpvp/slotbot/struct/GameStatus.java b/SlotBot/src/main/java/net/crankedpvp/slotbot/struct/GameStatus.java new file mode 100644 index 0000000..e1ce081 --- /dev/null +++ b/SlotBot/src/main/java/net/crankedpvp/slotbot/struct/GameStatus.java @@ -0,0 +1,5 @@ +package net.crankedpvp.slotbot.struct; + +public enum GameStatus { + SPINNING, FINISHING, WAITING +} diff --git a/SlotBot/src/main/java/net/crankedpvp/slotbot/struct/SlotBotType.java b/SlotBot/src/main/java/net/crankedpvp/slotbot/struct/SlotBotType.java new file mode 100644 index 0000000..c628f3c --- /dev/null +++ b/SlotBot/src/main/java/net/crankedpvp/slotbot/struct/SlotBotType.java @@ -0,0 +1,61 @@ +package net.crankedpvp.slotbot.struct; + +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.loottable.LootTableAPI; +import net.crankedpvp.loottable.struct.LootTableType; +import net.crankedpvp.slotbot.SlotBotAPI; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +@Getter +public enum SlotBotType { + SLOT_BOT("", Material.PAPER, Collections.emptyList()), + HEROIC_SLOT_BOT("&5&ki&r&d&lHeroic&5&ki&r ", Material.PAPER, Arrays.asList("", "&7This /slot ticket will &fnot &7give", "&7common or uncommon rewards.")), + MASTERY_SLOT_BOT("&c&ki&r&4&lMastery&c&ki&r ", Material.PAPER, Arrays.asList("", "&7This /slot ticket will &fnot &7give", "&7common, uncommon or rare rewards.")), + ; + + private final String fancyName; + private final Material material; + private final List additionalLore; + + SlotBotType(String fancyName, Material material, List additionalLore) { + this.fancyName = fancyName; + this.material = material; + this.additionalLore = additionalLore; + } + + public boolean equals(ItemStack itemStack) { + return (this == SlotBotAPI.getSlotBotType(itemStack)); + } + + public ItemStack build() { + return this.build(1); + } + + public ItemStack build(int amount) { + ItemBuilder itemBuilder = new ItemBuilder(this.getMaterial(), this.fancyName + "&c&lSlot &f&lBot &c&lTicket", + "&7Right-Click the Slot Bot located", + "&7at &f/spawn &7or use &f/bot &7to", + "&7open the slot bot machinery.", + "", + "&7Left-Click to insert a slot bot", + "&7ticket into the machine"); + itemBuilder.addLore(this.additionalLore); + ItemStack itemStack = itemBuilder.colorize().build(); + itemStack.setAmount(amount); + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("crankedCustomItem", "slotBotTicket"); + nbtItem.setString("slotBotType", this.name()); + return nbtItem.getItem(); + } + + public ItemStack getRandomItem() { + return LootTableAPI.getRandomLootItem(LootTableType.SLOTBOT); + } +} diff --git a/SlotBot/src/main/resources/plugin.yml b/SlotBot/src/main/resources/plugin.yml new file mode 100644 index 0000000..e58011e --- /dev/null +++ b/SlotBot/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedSlotBot +main: net.crankedpvp.slotbot.SlotBotPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/Spawners/pom.xml b/Spawners/pom.xml new file mode 100644 index 0000000..83e4592 --- /dev/null +++ b/Spawners/pom.xml @@ -0,0 +1,95 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Spawners + + + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + com.golfing.wineSpigot + winespigot + 1.0 + system + ${project.basedir}/../.lib/WineSpigot-V1.4.4.3.jar + + + coreprotect + coreprotect + 1.0 + system + ${project.basedir}/../.lib/CoreProtect_2.12.0.jar + + + Utils + net.crankedpvp + + + Lootboxes + net.crankedpvp + + + Masks + net.crankedpvp + + + Pets + net.crankedpvp + + + com.massivecraft + Factions + + + net.crankedpvp + Captcha + + + net.crankedpvp + Shop + + + Keys + net.crankedpvp + + + net.crankedpvp + FactionLogs + 1.0 + + + Enchants + net.crankedpvp + + + net.crankedpvp + CustomExplosions + + + net.crankedpvp + Leaderboards + + + Armor + net.crankedpvp + + + net.crankedpvp + Shards + + + \ No newline at end of file diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/SpawnerPlugin.java b/Spawners/src/main/java/net/crankedpvp/spawners/SpawnerPlugin.java new file mode 100644 index 0000000..fc9cf69 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/SpawnerPlugin.java @@ -0,0 +1,128 @@ +package net.crankedpvp.spawners; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.crankedutils.utils.PluginUtils; +import net.crankedpvp.spawners.commands.*; +import net.crankedpvp.spawners.guis.AntiAFKGrindingGUI; +import net.crankedpvp.spawners.language.LanguageHandler; +import net.crankedpvp.spawners.listeners.*; +import net.crankedpvp.spawners.struct.ftop.FactionsTopManager; +import net.crankedpvp.spawners.struct.ftop.RecalculationTask; +import net.crankedpvp.spawners.struct.grinding.GrindingManager; +import net.crankedpvp.spawners.struct.spawners.SpawnerManager; +import net.crankedpvp.spawners.utils.ConfigManager; +import net.crankedpvp.spawners.utils.MobStackerUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.*; + +@Getter +public class SpawnerPlugin extends JavaPlugin { + + @Getter + private static SpawnerPlugin instance; + + @Getter + public static List coolDownSpawnerPlace = new ArrayList<>(); + @Getter + private List waitingForAfkGrindingVerification; + @Getter + private Map afkGrinders; + private LanguageHandler languagehandler; + private ConfigManager configManager; + private FactionsTopManager factionsTopManager; + private MobStackerUtils mobStackerUtils; + private CommandManager commandManager; + private SpawnerManager spawnerManager; + private GrindingManager grindingManager; + + @Override + public void onEnable() { + instance = this; + + this.mobStackerUtils = new MobStackerUtils(); + + this.languagehandler = new LanguageHandler(this); + this.languagehandler.load(); + this.configManager = new ConfigManager(this); + this.configManager.setupFiles(); + + this.factionsTopManager = new FactionsTopManager(this); + + this.commandManager = new CommandManager(this, true); + registerCommandParameters(); + commandManager.register(new CommandAdminFactionsTop(this), new CommandFactionsTop(this),new CommandAdminSpawner(), new CommandGiveSpawner(), new CommandSplitSpawners(), new CommandStackSpawners(), new CommandStopSpawnersPlace()); + + this.spawnerManager = new SpawnerManager(this); + spawnerManager.loadAll(); + + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, ()-> { + spawnerManager.saveAll(); + }, 60L, 5*20*60); + + new RecalculationTask(this).runTaskTimerAsynchronously(this, 100L, 18000L); + + this.grindingManager = new GrindingManager(); + this.registerListeners(); + this.afkGrinders = new HashMap<>(); + this.waitingForAfkGrindingVerification = new ArrayList<>(); + + Bukkit.getScheduler().runTaskLater(this, MobStackerUtils::onEnable, 20L); + + } + + @Override + public void onDisable() { + spawnerManager.saveAll(); + instance = null; + } + + public void registerListeners() { + PluginUtils.registerListeners(this, + new SpawnerBreakListener(), + new CombineSpawnersInventoryListener(), + new EntityStackerListener(this), + new MobSpawnerListener(this), + new FtopCommandListener(this), + new GrindingGuiClose(), + new SpawnerSpawnListener(this) + ); + } + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(EntityType.class, argument -> { + EntityType type = EntityType.valueOf(String.valueOf(argument).toUpperCase()); + return new TypeResult(type, argument); + }); + } + + public void addPlayerToAfkGrinding(Player p) { + UUID uuid = p.getUniqueId(); + + if (afkGrinders.containsKey(uuid)) { + int amount = afkGrinders.get(uuid); + afkGrinders.put(uuid, amount+1); + } else { + afkGrinders.put(uuid, 1); + } + + int amount = afkGrinders.get(uuid); + if (amount >= 5000) { + p.closeInventory(); + //CaptchaAPI.forceCaptchaForPlayer(p); + this.afkGrinders.put(uuid, 1); + AntiAFKGrindingGUI antiAFKGrindingGUI = new AntiAFKGrindingGUI(p); + antiAFKGrindingGUI.getAntiAfkGrindingGui().open(p); + } + + + } + + + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandAdminFactionsTop.java b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandAdminFactionsTop.java new file mode 100644 index 0000000..032c96a --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandAdminFactionsTop.java @@ -0,0 +1,28 @@ +package net.crankedpvp.spawners.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.struct.ftop.FactionsTopManager; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +@Command("aftop") +public class CommandAdminFactionsTop extends CommandBase { + + private final FactionsTopManager factionsTopManager; + + public CommandAdminFactionsTop(SpawnerPlugin plugin) { + this.factionsTopManager = plugin.getFactionsTopManager(); + } + + @Default + @Permission("ftop.recalculate") + public void onCommand(CommandSender sender) { + this.factionsTopManager.recalculateFactionsTop(); + sender.sendMessage(CC.GreenB + "(!) " + CC.Green + "Forcefully recalculated F-Top!"); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandAdminSpawner.java b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandAdminSpawner.java new file mode 100644 index 0000000..0267373 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandAdminSpawner.java @@ -0,0 +1,23 @@ +package net.crankedpvp.spawners.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.spawners.SpawnerPlugin; +import org.bukkit.command.CommandSender; + +@Command("aspawner") +@Alias("as") +public class CommandAdminSpawner extends CommandBase { + + @Default + @Permission("cranked.admin") + public void onReload(CommandSender sender) { + SpawnerPlugin.getInstance().getConfigManager().reloadFiles(); + + sender.sendMessage(CC.translate("&aReload Config files...")); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandFactionsTop.java b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandFactionsTop.java new file mode 100644 index 0000000..714bf4d --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandFactionsTop.java @@ -0,0 +1,65 @@ +package net.crankedpvp.spawners.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Optional; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.ftop.FactionData; +import net.crankedpvp.spawners.struct.ftop.FactionsTopManager; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Map; + +@Command("ftop") +@Alias("ftopp") +public class CommandFactionsTop extends CommandBase { + + private final FactionsTopManager factionsTopManager; + + public CommandFactionsTop(SpawnerPlugin plugin) { + this.factionsTopManager = plugin.getFactionsTopManager(); + } + + @Default + public void onCommand(CommandSender sender, @Optional Integer page) { + Player player = (Player)sender; + if (page == null) { + page = 1; + } + page = Math.min(5, Math.max(1, page)); + player.sendMessage(""); + player.sendMessage(CC.GoldB + "Top Factions (" + CC.WhiteB + page + CC.Gold + "/" + CC.WhiteB + "5" + CC.GoldB + ")"); + int pos = 1; + int from = (page - 1) * 9; + int to = (page - 1) * 9 + 9; + Map data = this.factionsTopManager.getTopFactions(from, to); + for (int x = from; x < to; x++) { + if (data.containsKey(x)) { + FactionData faction = data.get(x); + TextComponent msg = new TextComponent(CC.GoldB + pos + ". " + CC.Green + faction.getFaction().getTag() + CC.Gold + " - " + CC.WhiteB + "$" + NumberUtils.formatMoney(faction.getSpawnerValue())); + String builder = CC.GoldB + CC.Underline + faction.getFaction().getTag() + "\n\n" + + CC.White + "Member Wealth: " + CC.Gold + "$" + NumberUtils.formatMoney(faction.getMemberValue()) + "\n" + + CC.White + "Spawner Value: " + CC.Gold + "$" + NumberUtils.formatMoney(faction.getSpawnerValue()) + "\n" + + CC.White + "Spawners: " + CC.Gold + faction.getSpawnerCount() + "\n" + + CC.White + "Stacked Spawners: " + CC.Gold + faction + .getStackedSpawnerCount() + + "\n" + + CC.White + "Richest Member:\n" + + " " + CC.GoldB + faction.getRichestPlayer() + ": $" + NumberUtils.formatMoney(faction.getRichestPlayerBalance()); + msg.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, (new ComponentBuilder(builder)).create())); + player.sendMessage(msg); + pos++; + } + } + player.sendMessage(""); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandGiveSpawner.java b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandGiveSpawner.java new file mode 100644 index 0000000..1f7d6ac --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandGiveSpawner.java @@ -0,0 +1,33 @@ +package net.crankedpvp.spawners.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.spawners.items.ItemSpawner; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Iterator; + + +@Command("givespawner") +@Alias("givespawners") +public class CommandGiveSpawner extends CommandBase { + + @Permission("cranked.admin") + @Default + @WrongUsage("&cUsage: /givespawner [IGN] [Type] [Amount]") + public void onCommand(CommandSender sender, @Completion("#players") Player forPlayer, @Completion("#enum") EntityType type, @Optional Integer amount) { + if (amount == null) { + amount = 1; + } + PlayerUtils.giveOrDropProtectedItem(forPlayer, ItemSpawner.getItem(type, amount), 60); + sender.sendMessage(CC.translate("&a&l(!)&a Given " + forPlayer.getName() + " " + amount + "x " + type.getName() + " Spawners.")); + + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandSplitSpawners.java b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandSplitSpawners.java new file mode 100644 index 0000000..e37e894 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandSplitSpawners.java @@ -0,0 +1,46 @@ +package net.crankedpvp.spawners.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.WrongUsage; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.spawners.items.ItemSpawner; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +@Command("splitspawner") +@Alias("splitspawners") +public class CommandSplitSpawners extends CommandBase { + + @Default + @WrongUsage("&cUsage: /splitspawners [count]") + public void onCommand(CommandSender sender, Integer amount) { + Player player = (Player) sender; + ItemStack item = player.getItemInHand(); + if(amount <= 0) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You cannot split 0 or less spawners"); + return; + } + int count = ItemSpawner.getSpawnerAmount(item); + EntityType type = ItemSpawner.getEntityTypeFromItem(item); + if(type == null || count <= -1) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "That is not a valid spawner!"); + return; + } + + if(amount >= count) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You have to choose a count lower than the spawner count."); + return; + } + player.getInventory().addItem(ItemSpawner.getItem(type, amount)); + player.setItemInHand(ItemSpawner.getItem(type, count - amount)); + player.playSound(player.getLocation(), Sound.ANVIL_USE, 0.75F, 2F); + } + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandStackSpawners.java b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandStackSpawners.java new file mode 100644 index 0000000..0e975c9 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandStackSpawners.java @@ -0,0 +1,65 @@ +package net.crankedpvp.spawners.commands; + + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.spawners.items.ItemSpawner; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +@Command("stackspawner") +@Alias("stackspawners") +public class CommandStackSpawners extends CommandBase { + @Default + public void onCommand(CommandSender sender) { + Map spawners = new HashMap<>(); + Player player = ((Player) sender).getPlayer(); + + for (ItemStack item : player.getInventory().getContents()) { + + int amount = ItemSpawner.getSpawnerAmount(item); + EntityType type = ItemSpawner.getEntityTypeFromItem(item); + + + + if(type == null || amount <= -1) { + continue; + } + + if (item.getAmount() >1) { + amount *=item.getAmount(); + } + + player.getInventory().remove(item); + if (spawners.containsKey(type)) { + int currentAmount = spawners.get(type); + spawners.put(type, currentAmount+amount); + } else { + spawners.put(type, amount); + } + } + + if (spawners.isEmpty()) { + player.sendMessage(CC.translate("&c&l(!)&c Could not find valid spawners to stack.")); + return; + } + + for (Map.Entry entry : spawners.entrySet()) { + EntityType type = entry.getKey(); + int amount = entry.getValue(); + PlayerUtils.giveOrDropProtectedItem(player, ItemSpawner.getItem(type, amount), -1); + } + player.sendMessage(CC.translate("&a&l(!)&a Stacked all the spawners in your inventory.")); + + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandStopSpawnersPlace.java b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandStopSpawnersPlace.java new file mode 100644 index 0000000..4b515c8 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/commands/CommandStopSpawnersPlace.java @@ -0,0 +1,45 @@ +package net.crankedpvp.spawners.commands; + + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.utils.ConfigManager; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +@Command("stopspawners") +@Alias({"stopspawner", "stopspawnerplace", "stopspawnersplace"}) +public class CommandStopSpawnersPlace extends CommandBase { + + @Permission("cranked.admin") + @Default + public void onCommand(CommandSender commandSender) { + + + boolean allowSpawners = SpawnerPlugin.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.PRIMARY).getBoolean("spawners.can-place"); + + + Bukkit.broadcastMessage(CC.translate("")); + if (!allowSpawners) { + Bukkit.broadcastMessage(CC.translate("&a&l** SPAWNER PLACEMENT HAS BEEN ENABLED **")); + Bukkit.broadcastMessage(CC.translate("&7&o( You can now place spawners again for FTOP value. )")); + Bukkit.broadcastMessage(CC.translate("")); + SpawnerPlugin.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.PRIMARY).set("spawners.can-place", true); + + + } else { + Bukkit.broadcastMessage(CC.translate("&c&l** SPAWNER PLACEMENT HAS BEEN DISABLED **")); + Bukkit.broadcastMessage(CC.translate("&7&o( You can no longer place spawners for FTOP value anymore. )")); + Bukkit.broadcastMessage(CC.translate("")); + SpawnerPlugin.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.PRIMARY).set("spawners.can-place", false); + } + SpawnerPlugin.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).saveConfig(); + SpawnerPlugin.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).reloadConfig(); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/data/ftop/FactionData.java b/Spawners/src/main/java/net/crankedpvp/spawners/data/ftop/FactionData.java new file mode 100644 index 0000000..823f7bf --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/data/ftop/FactionData.java @@ -0,0 +1,85 @@ +package net.crankedpvp.spawners.data.ftop; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.spawners.SpawnerData; +import net.crankedpvp.spawners.struct.ftop.FactionsTopManager; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; + +import java.util.Map; + +public class FactionData { + + private final Faction faction; + private final Object[] richestMember; + private long memberValue; + private long spawnerValue; + private long spawnerAmount; + private long stackedSpawners; + + public FactionData(Faction faction) { + this.faction = faction; + this.spawnerValue = 0L; + this.memberValue = 0L; + this.spawnerAmount = 0L; + this.stackedSpawners = 0L; + this.richestMember = new Object[2]; + double cash = 0.0D; + String richest = ""; + for (FPlayer player : faction.getFPlayers()) { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(player.getName()); + if (offlinePlayer == null) + continue; + double balance = EconomyUtils.getBalance(offlinePlayer); + if (balance > cash) { + cash = balance; + richest = offlinePlayer.getName(); + } + this.memberValue = (long)(this.memberValue + balance); + } + this.richestMember[0] = richest; + this.richestMember[1] = (long) cash; + String tag = this.faction.getTag(); + for (SpawnerData data : SpawnerPlugin.getInstance().getSpawnerManager().getCacheValues()) { + Location location = SpawnerData.locationFromString(data.getKey()); + if (FactionUtils.getFactionAt(location).getTag().contentEquals(tag)) { + this.stackedSpawners++; + this.spawnerAmount += data.getSpawnerAmount(); + this.spawnerValue += SpawnerPlugin.getInstance().getFactionsTopManager().getValueOfSpawner(data.getEntityType()) * data.getSpawnerAmount(); + } + } + } + + public long getSpawnerCount() { + return this.spawnerAmount; + } + + public long getSpawnerValue() { + return this.spawnerValue; + } + + public long getMemberValue() { + return this.memberValue; + } + + public long getStackedSpawnerCount() { + return this.stackedSpawners; + } + + public Faction getFaction() { + return this.faction; + } + + public String getRichestPlayer() { + return (String)this.richestMember[0]; + } + + public long getRichestPlayerBalance() { + return (Long) this.richestMember[1]; + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/data/spawners/SpawnerData.java b/Spawners/src/main/java/net/crankedpvp/spawners/data/spawners/SpawnerData.java new file mode 100644 index 0000000..b6b0cdf --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/data/spawners/SpawnerData.java @@ -0,0 +1,60 @@ +package net.crankedpvp.spawners.data.spawners; + +import net.crankedpvp.storageutils.utils.KeyToSave; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.EntityType; + + +public class SpawnerData implements KeyToSave { + + public int spawnerAmount; + private final EntityType type; + private Location location; + + public SpawnerData(EntityType type, int spawnerAmount, Location location) { + this.spawnerAmount = spawnerAmount; + this.type = type; + this.location = location; + } + + public EntityType getEntityType() { + return this.type; + } + + public int getSpawnerAmount() { + return this.spawnerAmount; + } + + public void setSpawnerAmount(int spawnerAmount) { + this.spawnerAmount = spawnerAmount; + } + + + + public static String locationToString(Location location) { + return location.getWorld().getName().replace("_","|") + "_" + location.getBlockX()+ "_" + location.getBlockY()+ "_" + location.getBlockZ(); + } + + + public static Location locationFromString(String location) { + String[] locationSplit = location.split("_"); + World world = Bukkit.getWorld(locationSplit[0].replace("|", "_")); + double x = Double.parseDouble(locationSplit[1]); + double y = Double.parseDouble(locationSplit[2]); + double z = Double.parseDouble(locationSplit[3]); + + return new Location(world, x, y, z); + } + + @Override + public String getKey() { + return locationToString(location); + } + + @Override + public void setKey(String key) { + this.location = locationFromString(key); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/data/spawners/SpawnerPlaceCooldown.java b/Spawners/src/main/java/net/crankedpvp/spawners/data/spawners/SpawnerPlaceCooldown.java new file mode 100644 index 0000000..c4fed8c --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/data/spawners/SpawnerPlaceCooldown.java @@ -0,0 +1,10 @@ +package net.crankedpvp.spawners.data.spawners; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class SpawnerPlaceCooldown extends CurrentCooldown { + + public SpawnerPlaceCooldown() { + super("spawner-cooldown", 500L); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/events/SpawnerBreakEvent.java b/Spawners/src/main/java/net/crankedpvp/spawners/events/SpawnerBreakEvent.java new file mode 100644 index 0000000..2c0f022 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/events/SpawnerBreakEvent.java @@ -0,0 +1,39 @@ +package net.crankedpvp.spawners.events; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.Location; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@RequiredArgsConstructor +@Getter +public class SpawnerBreakEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean canceled = false; + @Getter + private final Location location; + + @Override + public boolean isCancelled() { + return this.canceled; + } + + @Override + public void setCancelled(boolean b) { + this.canceled = b; + } + + @Override + public HandlerList getHandlers() { + return SpawnerBreakEvent.handlers; + } + + public static HandlerList getHandlerList() { + return SpawnerBreakEvent.handlers; + } + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/events/SpawnerPlaceEvent.java b/Spawners/src/main/java/net/crankedpvp/spawners/events/SpawnerPlaceEvent.java new file mode 100644 index 0000000..c5644c9 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/events/SpawnerPlaceEvent.java @@ -0,0 +1,38 @@ +package net.crankedpvp.spawners.events; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.Location; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +@RequiredArgsConstructor +@Getter +public class SpawnerPlaceEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean canceled = false; + @Getter + private final Location location; + + @Override + public boolean isCancelled() { + return this.canceled; + } + + @Override + public void setCancelled(boolean b) { + this.canceled = b; + } + + @Override + public HandlerList getHandlers() { + return SpawnerPlaceEvent.handlers; + } + + public static HandlerList getHandlerList() { + return SpawnerPlaceEvent.handlers; + } + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/events/StackedMobDeathEvent.java b/Spawners/src/main/java/net/crankedpvp/spawners/events/StackedMobDeathEvent.java new file mode 100644 index 0000000..f012fcd --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/events/StackedMobDeathEvent.java @@ -0,0 +1,103 @@ +package net.crankedpvp.spawners.events; + +import net.crankedpvp.shop.ShopPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +import java.util.EnumMap; +import java.util.Map; +import java.util.Random; + +public class StackedMobDeathEvent extends Event implements Cancellable { + + private boolean cancel; + private final Entity entity; + private final Entity damager; + + private static final HandlerList handlers; + private static final Map itemDrops = new EnumMap<>(EntityType.class); + private static final Map xpDrops = new EnumMap<>(EntityType.class); + private static final Map moneyDrops = new EnumMap<>(EntityType.class); + + + static { + Random random = new Random(); + itemDrops.put(EntityType.VILLAGER, new ItemStack(Material.EMERALD, random.nextInt((3 - 1) + 1) + 1)); + itemDrops.put(EntityType.CREEPER, new ItemStack(Material.TNT, 1)); + itemDrops.put(EntityType.WITCH, new ItemStack(Material.DIAMOND, random.nextInt((3 - 1) + 1) + 1)); + itemDrops.put(EntityType.IRON_GOLEM, new ItemStack(Material.IRON_INGOT, random.nextInt((3 - 1) + 1) + 1)); + itemDrops.put(EntityType.PIG_ZOMBIE, new ItemStack(Material.GOLD_INGOT, 1)); + itemDrops.put(EntityType.SKELETON, new ItemStack(Material.BONE)); + itemDrops.put(EntityType.ZOMBIE, new ItemStack(Material.ROTTEN_FLESH)); + itemDrops.put(EntityType.BLAZE, new ItemStack(Material.BLAZE_ROD, 1)); + } + + static { + Random random = new Random(); + xpDrops.put(EntityType.VILLAGER, random.nextInt((50 - 1) + 1) + 35); + xpDrops.put(EntityType.CREEPER, random.nextInt((25 - 1) + 1) + 15); + xpDrops.put(EntityType.WITCH, random.nextInt((50 - 1) + 1) + 35); + xpDrops.put(EntityType.IRON_GOLEM, random.nextInt((40 - 1) + 1) + 25); + xpDrops.put(EntityType.PIG_ZOMBIE, random.nextInt((40 - 1) + 1) + 20); + xpDrops.put(EntityType.SKELETON, random.nextInt((35 - 1) + 1) + 20); + xpDrops.put(EntityType.ZOMBIE, random.nextInt((35 - 1) + 1) + 20); + xpDrops.put(EntityType.BLAZE, random.nextInt((50 - 1) + 1) + 35); + } + + + + public StackedMobDeathEvent(Entity entity, Entity damager) { + this.entity = entity; + this.damager = damager; + } + + public static HandlerList getHandlerList() { + return StackedMobDeathEvent.handlers; + } + + public ItemStack getItemDrops(EntityType entityType) { + return itemDrops.get(entityType); + } + + public double getExp(EntityType entityType) { + return xpDrops.getOrDefault(entityType, 75); + } + + public double getMoney(EntityType entityType) { + return ShopPlugin.getShopHandler().getSellPrice(getItemDrops(entityType)); + } + + public Entity getDamager() { + return damager; + } + + @Override + public final HandlerList getHandlers() { + return StackedMobDeathEvent.handlers; + } + + + @Override + public final void setCancelled(final boolean cancel) { + this.cancel = cancel; + } + + @Override + public final boolean isCancelled() { + return this.cancel; + } + + static { + handlers = new HandlerList(); + } + + + public Entity getEntity() { + return entity; + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/guis/AntiAFKGrindingGUI.java b/Spawners/src/main/java/net/crankedpvp/spawners/guis/AntiAFKGrindingGUI.java new file mode 100644 index 0000000..db902e7 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/guis/AntiAFKGrindingGUI.java @@ -0,0 +1,47 @@ +package net.crankedpvp.spawners.guis; + + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.spawners.SpawnerPlugin; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import java.util.Random; +import java.util.UUID; + +@Getter +public class AntiAFKGrindingGUI { + private final PaginatedGui antiAfkGrindingGui; + private final SpawnerPlugin crankedSpawners; + private final Player player; + + public AntiAFKGrindingGUI(Player player) { + this.crankedSpawners = SpawnerPlugin.getInstance(); + this.antiAfkGrindingGui = new PaginatedGui(1, 1, CC.translate("&8Anti AFK Grinding Verification")); + this.player = player; + UUID uuid = player.getUniqueId(); + if (!crankedSpawners.getWaitingForAfkGrindingVerification().contains(uuid)) { + crankedSpawners.getWaitingForAfkGrindingVerification().add(uuid); + } + + + this.antiAfkGrindingGui.setDefaultClickAction(event -> event.setCancelled(true)); + Random random = new Random(); + int randomInt = random.nextInt(9) + 1; + this.antiAfkGrindingGui.setItem(1, randomInt, new GuiItem(new ItemBuilder(Material.NETHER_STAR, CC.translate("&a&lVerify!")).addLoreLine(CC.translate("&7Click here to verify you are not afk grinding!")).build(), event -> { + crankedSpawners.getAfkGrinders().put(uuid, 1); + crankedSpawners.getWaitingForAfkGrindingVerification().remove(uuid); + player.sendMessage(CC.translate("&a&l(!)&a You have completed the anti afk grinding captcha! You can now enjoy grinding again.")); + player.playSound(player.getLocation(), Sound.VILLAGER_YES, 50, 50); + player.closeInventory(); + })); + } + + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/items/ItemSpawner.java b/Spawners/src/main/java/net/crankedpvp/spawners/items/ItemSpawner.java new file mode 100644 index 0000000..9d0ba02 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/items/ItemSpawner.java @@ -0,0 +1,69 @@ +package net.crankedpvp.spawners.items; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EntityUtils; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.utils.ConfigManager; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Arrays; +import java.util.UUID; + + +public class ItemSpawner { + + public static ItemStack getItem(EntityType creatureType, int amount) { + ItemStack item = new ItemStack(Material.MOB_SPAWNER); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&c&l" + EntityUtils.getEntityName(creatureType) + " &f&lSpawner &7(" + amount + "x)")); + meta.setLore(Arrays.asList( + CC.translate("&8Stacked Spawner"), + CC.translate(""), + CC.translate("&4&lSpawner Info"), + CC.translate("&4┇ &cType: &7" + EntityUtils.getEntityName(creatureType)), + CC.translate("&4┇ &cAmount: &7" + amount), + CC.translate("&4┖") + + )); + item.setItemMeta(meta); + NBTItem nbtItem = new NBTItem(item); + NBTCompound compound = nbtItem.addCompound("spawnerData"); + compound.setString("spawnerType", creatureType.name()); + compound.setInteger("amount", amount); + compound.setString("uuid", UUID.randomUUID().toString()); + return nbtItem.getItem(); + } + + public static EntityType getEntityTypeFromItem(ItemStack item) { + if (item == null || item.getType() != Material.MOB_SPAWNER) { + return null; + } + NBTItem wrapper = new NBTItem(item); + if (!wrapper.hasKey("spawnerData")) { + return null; + } + NBTCompound compound = wrapper.getCompound("spawnerData"); + return EntityType.valueOf(compound.getString("spawnerType")); + } + + public static int getSpawnerAmount(ItemStack item) { + if (item == null || item.getType() != Material.MOB_SPAWNER) { + return -1; + } + NBTItem wrapper = new NBTItem(item); + if (!wrapper.hasKey("spawnerData")) { + return -1; + } + NBTCompound compound = wrapper.getCompound("spawnerData"); + return compound.getInteger("amount"); + } + + public static int getSpawnerLimit() { + return SpawnerPlugin.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.PRIMARY).getInt("spawners.max-stack-size"); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/language/Language.java b/Spawners/src/main/java/net/crankedpvp/spawners/language/Language.java new file mode 100644 index 0000000..fde729f --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/language/Language.java @@ -0,0 +1,95 @@ +package net.crankedpvp.spawners.language; + +import com.google.common.collect.ImmutableList; +import net.crankedpvp.crankedutils.utils.CC; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +public enum Language { + + GRINDING_MONEY_GIVE + ; + + private String value; + private ImmutableList valueList; + + public String getValue() { + return this.value != null ? this.value : this.name(); + } + + public String getValue(UnaryOperator function) { + return this.value != null ? function.apply(this.value) : this.name(); + } + + public String getPath() { + return this.name(); + } + + public List getValuesAsList() { + return this.valueList; + } + + public List getValuesAsList(String oldString, String newString) { + List list = new ArrayList<>(this.valueList); + list.replaceAll(s -> s.replace(oldString, newString)); + return list; + } + + void setValue(String value) { + this.value = CC.translate(value); + + List tempList = Arrays.stream(StringUtils.split(value, System.lineSeparator())) + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + void setValue(List valueList) { + this.value = CC.translate(valueList.parallelStream().collect(Collectors.joining(System.lineSeparator()))); + + List tempList = valueList.stream() + .map(CC::translate) + .collect(Collectors.toList()); + this.valueList = ImmutableList.copyOf(tempList); + } + + public void send(CommandSender sender, UnaryOperator function) { + sender.sendMessage(CC.translate(this.getValue(function))); + } + + public void send(CommandSender sender) { + sender.sendMessage(CC.translate(this.getValue())); + } + + + public void send(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void sendPlayers(List senders, UnaryOperator function) { + String msg = CC.translate(this.getValue(function)); + senders.forEach(sender -> sender.sendMessage(msg)); + } + + public void send(CommandSender ...senders) { + String msg = CC.translate(this.getValue()); + Arrays.asList(senders).forEach(sender -> sender.sendMessage(msg)); + } + + public String getMessage() { + return CC.translate(this.getValue()); + } + + public String getMessage(UnaryOperator function) { + return CC.translate(this.getValue(function)); + } + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/language/LanguageHandler.java b/Spawners/src/main/java/net/crankedpvp/spawners/language/LanguageHandler.java new file mode 100644 index 0000000..500ef07 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/language/LanguageHandler.java @@ -0,0 +1,82 @@ +package net.crankedpvp.spawners.language; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public final class LanguageHandler { + + private final File file; + private final FileConfiguration config; + private final String path; + private final JavaPlugin plugin; + + public LanguageHandler(JavaPlugin plugin) { + this.plugin = plugin; + this.path = "language.yml"; + file = new File(plugin.getDataFolder(), path); + config = new YamlConfiguration(); + } + + public void load() { + this.saveDefaultConfig(); + + this.loadConfigFromDisk(); + this.copyDefaults(); + this.save(); + + this.loadConfigFromDisk(); + + this.loadLangMessages(); + } + + private void loadLangMessages() { + for (Language entry : Language.values()) { + String path = entry.getPath(); + if (config.isList(path)) { + entry.setValue(config.getStringList(path)); + continue; + } + entry.setValue(config.getString(path)); + } + } + + private void loadConfigFromDisk() { + try { + config.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + } + + public void save() { + try { + config.save(file); + } catch (IOException e) { + plugin.getLogger().severe("Could not save config file for " + file.getPath() + "!"); + e.printStackTrace(); + } + } + + private void copyDefaults() { + InputStream defConfig = plugin.getResource(this.path); + if (defConfig != null) { + config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig))); + } + config.options().copyDefaults(true); + } + + private void saveDefaultConfig() { + if (!file.exists()) { + file.getParentFile().mkdirs(); + plugin.saveResource(file.getName(),false); + } + } + +} \ No newline at end of file diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/listeners/CombineSpawnersInventoryListener.java b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/CombineSpawnersInventoryListener.java new file mode 100644 index 0000000..f98d9d1 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/CombineSpawnersInventoryListener.java @@ -0,0 +1,51 @@ +package net.crankedpvp.spawners.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryClickUtils; +import net.crankedpvp.spawners.items.ItemSpawner; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; + +public class CombineSpawnersInventoryListener implements Listener { + @EventHandler(priority = EventPriority.HIGHEST) + public void onClick(InventoryClickEvent event) { + + if (event.getCurrentItem() != null && event.getCursor() != null) { + if (event.getCurrentItem().getType() != Material.MOB_SPAWNER + || event.getCursor().getType() != Material.MOB_SPAWNER) { + return; + } + if (event.getCurrentItem().getAmount() > 1 || event.getCursor().getAmount() > 1) { + event.getWhoClicked().sendMessage(CC.translate("&c&l(!)&c You cannot stack stacked spawners, type /stackspawners")); + ((Player) event.getWhoClicked()).playSound(event.getWhoClicked().getLocation(), Sound.ANVIL_LAND, 0.75F, 2F); + return; + } + if(event.isCancelled()) return; + // if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + int amount = ItemSpawner.getSpawnerAmount(event.getCursor()); + int other = ItemSpawner.getSpawnerAmount(event.getCurrentItem()); + EntityType type = ItemSpawner.getEntityTypeFromItem(event.getCursor()); + EntityType otherType = ItemSpawner.getEntityTypeFromItem(event.getCurrentItem()); + if (amount <= 0 || other <= 0 || otherType != type) { + return; + } + amount += other; + if(event.getCursor().getAmount() > 1) { + event.getCursor().setAmount(event.getCursor().getAmount() - 1); + } else { + event.setCursor(null); + } + event.setCurrentItem(ItemSpawner.getItem(type, amount)); + ((Player) event.getWhoClicked()).playSound(event.getWhoClicked().getLocation(), Sound.ANVIL_USE, 0.75F, 2F); + ((Player) event.getWhoClicked()).playSound(event.getWhoClicked().getLocation(), Sound.LEVEL_UP, 0.75F, 2F); + event.setCancelled(true); + } + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/listeners/EntityStackerListener.java b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/EntityStackerListener.java new file mode 100644 index 0000000..f2cf550 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/EntityStackerListener.java @@ -0,0 +1,193 @@ +package net.crankedpvp.spawners.listeners; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedarmor.struct.ArmorSet; +import net.crankedpvp.crankedenchants.struct.items.EnchantedItemBuilder; +import net.crankedpvp.crankedmasks.CrankedMasks; +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedpets.CrankedPets; +import net.crankedpvp.crankedpets.pets.ExperiencePet; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.cratekeys.CrankedCrateKeysAPI; +import net.crankedpvp.cratekeys.enums.CrateKeyType; +import net.crankedpvp.lootboxes.CrankedLootboxes; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.events.StackedMobDeathEvent; +import net.crankedpvp.spawners.struct.grinding.GrindingCache; +import net.crankedpvp.spawners.struct.grinding.GrindingManager; +import net.crankedpvp.spawners.utils.ConfigManager; +import net.crankedpvp.spawners.utils.MobStackerUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Creature; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; + +import java.util.*; + +public class EntityStackerListener implements Listener { + private final MobStackerUtils mobStackerUtils; + private final SpawnerPlugin plugin; + private final Map blazeCooldown; + private final GrindingManager grindingManager; + + public EntityStackerListener(SpawnerPlugin plugin) { + this.plugin = plugin; + this.mobStackerUtils = plugin.getMobStackerUtils(); + this.blazeCooldown = new HashMap<>(); + this.grindingManager = plugin.getGrindingManager(); + Bukkit.getScheduler().runTaskTimer(plugin, this.blazeCooldown::clear, 10, 5 * 20 * 60); + } + + + @EventHandler + public void onStackedEntityDeath(StackedMobDeathEvent event) { + Entity entity = event.getEntity(); + if (event.getDamager() instanceof Player) { + + + if (!mobStackerUtils.isStackedMob(entity)) return; + + if (event.getEntity().getLastDamageCause() != null) { + if (event.getEntity().getLastDamageCause().getCause() == EntityDamageEvent.DamageCause.FALL) return; + if (event.getEntity().getLastDamageCause().getCause() == EntityDamageEvent.DamageCause.FIRE) return; + if (event.getEntity().getLastDamageCause().getCause() == EntityDamageEvent.DamageCause.FIRE_TICK) + return; + } + + if (plugin.getWaitingForAfkGrindingVerification().contains(event.getDamager().getUniqueId())) { + event.setCancelled(true); + event.getDamager().sendMessage(CC.translate("&c&l(!)&c You cannot interact with blazes until you have solved the captcha, if you think there is an issue, relog and it will resolve it.")); + return; + } + + Player p = (Player) event.getDamager(); + /* + ArmorSet fortuneSet = CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID("fortune"); + boolean inFortuneSet = CrankedArmorAPI.getCurrentArmorSet(p) != null && CrankedArmorAPI.getCurrentArmorSet(p) == fortuneSet; + + */ + int amountMobsToKill = 1; + int keyGrindLevel = 1; + int exp = (int) event.getExp(entity.getType()); + GrindingCache grindingCache = grindingManager.getGrindingCache(p); + + /* + if (inFortuneSet && Math.random() < 0.2) { + amountMobsToKill++; + } + + + if (!ItemUtils.isAirOrNull(p.getItemInHand())) { + + EnchantedItemBuilder enchantedItemBuilder = new EnchantedItemBuilder(p.getItemInHand()); + keyGrindLevel = enchantedItemBuilder.hasEnchantment("jewels") ? (1 + (enchantedItemBuilder.getEnchantmentLevel("jewels"))) : 1; + + if (enchantedItemBuilder.hasEnchantment("plunder")) { + keyGrindLevel++; + exp *= 1.25; + } + double chefChance = SpawnerPlugin.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.PRIMARY).getDouble("chefRewardChance") * 0.01; + + if (enchantedItemBuilder.hasEnchantment("chef") && Math.random() < chefChance) { + try { + CrankedLootboxes.getInstance().getLootboxManager().giveLootbox(p, CrankedLootboxes.getInstance().getLootboxRegister().getLootbox("ValentineCube"), 1); + } catch (Exception e) { + e.printStackTrace(); + } + } + + } + + + */ + if (CrankedMasksAPI.hasMaskEquipped(p, CrankedMasks.getInstance().getMasksRegister().getMaskFromID("tinker"))) { + exp *= 1.5; + } + + + +/* + if (inFortuneSet) { + exp *= 2; + } + + */ + + if (((ExperiencePet) CrankedPets.getInstance().getPetRegister().getPetFromID("experience")).getPlayersUsingExpPet().contains(p.getUniqueId())) { + exp *= ((ExperiencePet) CrankedPets.getInstance().getPetRegister().getPetFromID("experience")).getExpMultiplier(); + } + + grindingCache.addMobKilled(amountMobsToKill); + for (int i = 0; i < amountMobsToKill; i++) { + grindingCache.addMoney(event.getMoney(entity.getType())); + grindingCache.addExp(exp); + handleKeyGiving(p, keyGrindLevel); + if (Math.random() < 0.02 * Math.max(1, keyGrindLevel / 2)) { + grindingCache.addShards(new Random().nextInt((3 - 1) + 1) + 1); + } + } + + plugin.addPlayerToAfkGrinding(p); + mobStackerUtils.setStackSize(entity, mobStackerUtils.getStackSize(entity) - amountMobsToKill); + } + } + + + @EventHandler + public void onMobDeath(EntityDamageByEntityEvent event) { + if (!(event.getEntity() instanceof Creature)) return; + + if (event.getEntity().getLastDamageCause() != null) { + if (event.getEntity().getLastDamageCause().getCause() == EntityDamageEvent.DamageCause.FALL) return; + if (event.getEntity().getLastDamageCause().getCause() == EntityDamageEvent.DamageCause.FIRE) return; + if (event.getEntity().getLastDamageCause().getCause() == EntityDamageEvent.DamageCause.FIRE_TICK) return; + } + + Creature entity = (Creature) event.getEntity(); + if (!mobStackerUtils.isStackedMob(entity)) { + return; + } + + if (this.blazeCooldown.containsKey(event.getEntity().getUniqueId())) { + if (System.currentTimeMillis() < this.blazeCooldown.get(event.getEntity().getUniqueId()) + (long) 83) { + event.setCancelled(true); + return; + } + } + this.blazeCooldown.put(event.getEntity().getUniqueId(), System.currentTimeMillis()); + + StackedMobDeathEvent stackedMobDeathEvent = new StackedMobDeathEvent(entity, event.getDamager()); + try { + Bukkit.getPluginManager().callEvent(stackedMobDeathEvent); + } catch (Exception ignored) { + } + entity.setHealth(entity.getMaxHealth()); + event.setCancelled(true); + } + + + public void handleKeyGiving(Player player, int keyGrindLevel) { + double MYTHIC_CHANCE = SpawnerPlugin.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.PRIMARY).getDouble("mythicKeyChance") *0.01; + if (Math.random() < (MYTHIC_CHANCE * Math.max(1, keyGrindLevel / 2))) { + CrankedCrateKeysAPI.givePlayerKeys(player, CrateKeyType.MYTHIC_KEY, 1); + return; + } + double RAREKEY_CHANCE = SpawnerPlugin.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.PRIMARY).getDouble("rareKeyChance") *0.01; + if (Math.random() < RAREKEY_CHANCE * Math.max(1, keyGrindLevel / 2)) { + CrankedCrateKeysAPI.givePlayerKeys(player, CrateKeyType.ABYSS_KEY, 1); + return; + } + double COMMON_CHANCE = SpawnerPlugin.getInstance().getConfigManager().getConfig(ConfigManager.ConfigFile.PRIMARY).getDouble("commonKeyChance") *0.01; + if (Math.random() < COMMON_CHANCE * Math.max(1, keyGrindLevel / 2)) { + CrankedCrateKeysAPI.givePlayerKeys(player, CrateKeyType.SEASON_KEY, 1); + } + } + + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/listeners/FtopCommandListener.java b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/FtopCommandListener.java new file mode 100644 index 0000000..193ba5b --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/FtopCommandListener.java @@ -0,0 +1,71 @@ +package net.crankedpvp.spawners.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.ftop.FactionData; +import net.crankedpvp.spawners.struct.ftop.FactionsTopManager; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +import java.util.Map; + +public class FtopCommandListener implements Listener { + + private final FactionsTopManager factionsTopManager; + + public FtopCommandListener(SpawnerPlugin plugin) { + this.factionsTopManager = plugin.getFactionsTopManager(); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onFactionCommand(final PlayerCommandPreprocessEvent event) { + final String cmd = event.getMessage().toLowerCase(); + Player player = event.getPlayer(); + if (cmd.startsWith("/f top")) { + event.setCancelled(true); + int page; + try { + page = Integer.parseInt(cmd.replace("/f top ", "")); + if (page > 5) { + page = 5; + } + } catch (NumberFormatException e) { + page = 1; + } + + player.sendMessage(""); + player.sendMessage(CC.GoldB + "Top Factions (" + CC.WhiteB + page + CC.Gold + "/" + CC.WhiteB + "5" + CC.Gold + ")"); + int pos = 1; + int from = (page - 1) * 9; + int to = (page - 1) * 9 + 9; + Map data = this.factionsTopManager.getTopFactions(from, to); + for (int x = from; x < to; x++) { + if (data.containsKey(x)) { + FactionData faction = data.get(x); + TextComponent msg = new TextComponent(CC.GoldB + pos + ". " + CC.Gold + faction.getFaction().getTag() + CC.Gold + " - " + CC.WhiteB + "$" + NumberUtils.formatMoney(faction.getSpawnerValue())); + String builder = CC.GoldB + CC.Underline + faction.getFaction().getTag() + "\n\n" + + CC.White + "Member Wealth: " + CC.Gold + "$" + NumberUtils.formatMoney(faction.getMemberValue()) + "\n" + + CC.White + "Spawner Value: " + CC.Gold + "$" + NumberUtils.formatMoney(faction.getSpawnerValue()) + "\n" + + CC.White + "Spawners: " + CC.Gold + faction.getSpawnerCount() + "\n" + + CC.White + "Stacked Spawners: " + CC.Gold + faction + .getStackedSpawnerCount() + + "\n" + + CC.White + "Richest Member:\n" + + " " + CC.Gold + faction.getRichestPlayer() + ": $" + NumberUtils.formatMoney(faction.getRichestPlayerBalance()); + msg.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, (new ComponentBuilder(builder)).create())); + player.sendMessage(msg); + pos++; + } + } + player.sendMessage(""); + + } + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/listeners/GrindingGuiClose.java b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/GrindingGuiClose.java new file mode 100644 index 0000000..f275b73 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/GrindingGuiClose.java @@ -0,0 +1,39 @@ +package net.crankedpvp.spawners.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.spawners.SpawnerPlugin; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class GrindingGuiClose implements Listener { + @EventHandler + public void onClose(InventoryCloseEvent e) { + if (SpawnerPlugin.getInstance().getWaitingForAfkGrindingVerification().contains(e.getPlayer().getUniqueId())) { + Bukkit.getScheduler().runTaskLater(SpawnerPlugin.getInstance(), () -> { + SpawnerPlugin.getInstance().getAfkGrinders().put(e.getPlayer().getUniqueId(), 1); + SpawnerPlugin.getInstance().getWaitingForAfkGrindingVerification().remove(e.getPlayer().getUniqueId()); + e.getPlayer().sendMessage(CC.translate("&a&l(!)&a You have completed the anti afk grinding captcha! You can now enjoy grinding again.")); + e.getPlayer().closeInventory(); + }, 2L); + } + + } + + + @EventHandler + public void cancelInteract(PlayerInteractEvent e) { + if (SpawnerPlugin.getInstance().getWaitingForAfkGrindingVerification().contains(e.getPlayer().getUniqueId())) { + e.setCancelled(true); + } + } + + @EventHandler + public void onQuit(PlayerQuitEvent e) { + SpawnerPlugin.getInstance().getWaitingForAfkGrindingVerification().remove(e.getPlayer().getUniqueId()); + SpawnerPlugin.getInstance().getAfkGrinders().remove(e.getPlayer().getUniqueId()); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/listeners/MobSpawnerListener.java b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/MobSpawnerListener.java new file mode 100644 index 0000000..e700392 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/MobSpawnerListener.java @@ -0,0 +1,270 @@ +package net.crankedpvp.spawners.listeners; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import net.coreprotect.CoreProtect; +import net.coreprotect.CoreProtectAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EntityUtils; +import net.crankedpvp.factionlogs.struct.impl.SpawnerPlace; +import net.crankedpvp.factionlogs.utils.FactionsLogsAPI; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.spawners.SpawnerData; +import net.crankedpvp.spawners.events.SpawnerPlaceEvent; +import net.crankedpvp.spawners.items.ItemSpawner; +import net.crankedpvp.spawners.struct.spawners.SpawnerManager; +import net.crankedpvp.spawners.utils.ConfigManager; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; + +public class MobSpawnerListener implements Listener { + + private final ConfigManager configManager; + private final SpawnerPlugin plugin; + private final CoreProtectAPI coreProtectAPI; + + public MobSpawnerListener(SpawnerPlugin plugin) { + this.configManager = plugin.getConfigManager(); + this.coreProtectAPI = CoreProtect.getInstance().getAPI(); + this.plugin = plugin; + } + + //This is when you place a new spawner + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + if (event.getBlockPlaced().getType() != Material.MOB_SPAWNER) { + return; + } + + boolean allowSpawners = this.configManager.getConfig(ConfigManager.ConfigFile.PRIMARY).getConfigurationSection("spawners").getBoolean("can-place"); + + if (!allowSpawners) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c Spawner placement has been disabled!")); + event.getPlayer().sendMessage(CC.translate("&7You can no longer place FTOP value.")); + event.setCancelled(true); + return; + } + + ItemStack item = event.getPlayer().getItemInHand(); + if (item.getAmount() > 1) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You cannot place stacked spawners!")); + event.getPlayer().sendMessage(CC.translate("&7Combine them by drag and dropping them together or type /stackspawners.")); + event.setCancelled(true); + return; + } + + + EntityType type = ItemSpawner.getEntityTypeFromItem(item); + + if (!SpawnerManager.canPlaceStackedSpawnerInThisChunk(event.getBlock().getChunk(), type)) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c This chunk already contains this spawner type.")); + event.getPlayer().sendMessage(CC.translate("&cPlease stack it on the existing spawner.")); + event.setCancelled(true); + return; + } + + if (type == null) { + event.setCancelled(true); + return; + } + + if (SpawnerPlugin.coolDownSpawnerPlace.contains(event.getPlayer())) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c Please be patient, you are still on spawner place cooldown.")); + event.setCancelled(true); + return; + } + + + int amount = ItemSpawner.getSpawnerAmount(item); + if (amount <= 0) { + event.setCancelled(true); + return; + } + int math = Math.min(amount, ItemSpawner.getSpawnerLimit()); + int spawnersLeft = amount - math; + event.getPlayer().sendMessage(CC.translate("&a&l+ &a&n" + amount + "&a " + EntityUtils.getEntityName(type) + " Spawner(s) &7[" + amount + " Total]")); + + SpawnerPlugin.coolDownSpawnerPlace.add(event.getPlayer()); + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + SpawnerPlugin.coolDownSpawnerPlace.remove(event.getPlayer()); + }, 20L); + + SpawnerData spawnerData = new SpawnerData(type, math, event.getBlock().getLocation()); + SpawnerPlugin.getInstance().getSpawnerManager().addToCache(spawnerData); + + event.getPlayer().setItemInHand(spawnersLeft <= 0 ? null : ItemSpawner.getItem(type, spawnersLeft)); + Location location = event.getBlockPlaced().getLocation(); + Bukkit.getScheduler().runTaskLater(plugin, (Runnable) new BukkitRunnable() { + @Override + public void run() { + location.getBlock().setType(Material.MOB_SPAWNER); + ((CreatureSpawner) location.getBlock().getState()).setSpawnedType(type); + SpawnerPlaceEvent spawnerPlaceEvent = new SpawnerPlaceEvent(location); + Bukkit.getPluginManager().callEvent(spawnerPlaceEvent); + + //TODO: look into fixing this +/* if (CollectorManager.DELEGATE.isCollectorContained(event.getBlock().getLocation())) { + Collector collector = CollectorManager.DELEGATE.getCollector(event.getBlock().getLocation()); + collector.clearSpawners(); + collector.scanSpawners(collector.getLocation()); + }*/ + } + + }, 1); + event.setCancelled(true); + + this.coreProtectAPI.logPlacement(event.getPlayer().getName(), event.getBlockPlaced().getLocation(), event.getBlockPlaced().getType(), event.getBlockPlaced().getData()); + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (!fPlayer.getFaction().isWilderness()) { + FactionsLogsAPI.log(fPlayer.getFaction().getId(), new SpawnerPlace(amount, location, type, fPlayer.getPlayer().getUniqueId())); + } + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.NOTE_PLING, 10f, 10f); + + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInteract(PlayerInteractEvent e) { + if (e.getClickedBlock() == null && e.getPlayer().getItemInHand() != null && e.getPlayer().getItemInHand().getType() == Material.MOB_SPAWNER) { + Player player = e.getPlayer(); + if(e.isCancelled()) return; + EntityType type = ItemSpawner.getEntityTypeFromItem(e.getItem()); + int amount = ItemSpawner.getSpawnerAmount(e.getItem()); + player.sendMessage(CC.translate("")); + player.sendMessage(CC.translate("&4&lSpawner Info")); + player.sendMessage(CC.RedB + " * " + CC.White + "Type: " + CC.Red + EntityUtils.getEntityName(type)); + player.sendMessage(CC.RedB + " * " + CC.White + "Amount: " + CC.Red + amount); + //player.sendMessage(CC.RedB + " * " + CC.White + "Income: " + CC.Red +"$" + NumberUtils.formatMoney(CollectorsPlugin.INSTANCE.getSpawnerUtil().getMoneyPerMinute(type)*60) + "/h"); + player.sendMessage(CC.translate("")); + + } + } + + + //This is when you place a spawner on a different spawner + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSpawnerPlaceOnSpawner(BlockPlaceEvent event) { + Block block = event.getBlock(); + if (block.getType() == Material.MOB_SPAWNER) { + if (event.getBlockAgainst().getType() == Material.MOB_SPAWNER) { + EntityType type = ((CreatureSpawner) event.getBlockAgainst().getState()).getSpawnedType(); + if (ItemSpawner.getEntityTypeFromItem(event.getPlayer().getItemInHand()) == type) { + int amount = ItemSpawner.getSpawnerAmount(event.getPlayer().getItemInHand()); + if (amount <= 0) { + event.setCancelled(true); + return; + } + + if (SpawnerPlugin.coolDownSpawnerPlace.contains(event.getPlayer())) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c Please be patient, you are still on spawner place cooldown.")); + event.setCancelled(true); + return; + } + + + //CHANGED + event.setCancelled(true); + Player player = event.getPlayer(); + SpawnerPlugin.coolDownSpawnerPlace.add(event.getPlayer()); + Bukkit.getScheduler().runTaskLaterAsynchronously(this.plugin, () -> { + SpawnerPlugin.coolDownSpawnerPlace.remove(event.getPlayer()); + }, 20L); + + SpawnerData found = plugin.getSpawnerManager().getSpawnerData(event.getBlockAgainst().getLocation()); + if (found != null) { + if (found.getSpawnerAmount() >= ItemSpawner.getSpawnerLimit()) { + player.sendMessage(CC.RedB + "(!) " + CC.Red + "You can not have more than " + + ItemSpawner.getSpawnerLimit() + " spawners stacked together!"); + event.setCancelled(true); + return; + } + + boolean allowSpawners = configManager.getConfig(ConfigManager.ConfigFile.PRIMARY).getConfigurationSection("spawners").getBoolean("can-place"); + + + if (!allowSpawners) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c Spawner placement has been disabled!")); + event.getPlayer().sendMessage(CC.translate("&7You can no longer place FTOP value.")); + event.setCancelled(true); + return; + } + + if (event.getItemInHand().getAmount() > 1) { + event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You cannot place stacked spawners!")); + event.getPlayer().sendMessage(CC.translate("&7Combine them by drag and dropping them together or type /stackspawners.")); + event.setCancelled(true); + return; + } + + int math = found.getSpawnerAmount() + amount >= ItemSpawner.getSpawnerLimit() + ? ItemSpawner.getSpawnerLimit() - found.getSpawnerAmount() + : amount; + int spawnersLeft = amount - math; + found.setSpawnerAmount(found.getSpawnerAmount() + math); + player.sendMessage(CC.translate("&a&l+ &a&n" + amount + "&a " + EntityUtils.getEntityName(type) + " Spawner(s) &7[" + found.getSpawnerAmount() + " Total]")); + player.playSound(player.getLocation(), Sound.NOTE_PLING, 10f, 10f); + SpawnerPlaceEvent spawnerPlaceEvent = new SpawnerPlaceEvent(block.getLocation()); + Bukkit.getPluginManager().callEvent(spawnerPlaceEvent); + /*if (CollectorManager.DELEGATE.isCollectorContained(event.getBlock().getLocation())) { + Collector collector = CollectorManager.DELEGATE.getCollector(event.getBlock().getLocation()); + collector.clearSpawners(); + collector.scanSpawners(collector.getLocation()); + }*/ + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (!fPlayer.getFaction().isWilderness()) { + FactionsLogsAPI.log(fPlayer.getFaction().getId(), new SpawnerPlace(amount, event.getBlockAgainst().getLocation(), type, fPlayer.getPlayer().getUniqueId())); + } + + player.setItemInHand( + spawnersLeft <= 0 ? null : ItemSpawner.getItem(type, spawnersLeft)); + } else { + player.sendMessage(CC.translate("&c&l(!)&c This is not a valid stacked spawner. Contact an administrator if you think this is an issue.")); + event.setCancelled(true); + return; + } + player.updateInventory(); + } + + + } + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onSpawnerInteract(PlayerInteractEvent event) { + if (event.isCancelled()) return; + if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getItem() == null) { + Block block = event.getClickedBlock(); + if (block.getType() == Material.MOB_SPAWNER) { + event.setCancelled(true); + EntityType type = ((CreatureSpawner) block.getState()).getSpawnedType(); + + SpawnerData found = plugin.getSpawnerManager().getSpawnerData(event.getClickedBlock().getLocation()); + Player player = event.getPlayer(); + player.sendMessage(""); + player.sendMessage(CC.DarkRedB + "Spawner Info"); + player.sendMessage(CC.RedB + " * " + CC.White + "Type: " + + CC.Red + EntityUtils.getEntityName(type)); + player.sendMessage(CC.RedB + " * " + CC.White + "Amount: " + CC.Red + + (found != null ? found.getSpawnerAmount() : 1) + "x"); + player.sendMessage(""); + player.playSound(player.getLocation(), Sound.NOTE_PLING, 10f, 10f); + } + + } + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/listeners/SpawnerBreakListener.java b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/SpawnerBreakListener.java new file mode 100644 index 0000000..664bd31 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/SpawnerBreakListener.java @@ -0,0 +1,136 @@ +package net.crankedpvp.spawners.listeners; + + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import net.coreprotect.CoreProtect; +import net.coreprotect.CoreProtectAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EntityUtils; +import net.crankedpvp.customexplosions.listeners.CreeperListener; +import net.crankedpvp.customexplosions.struct.CreeperTypes; +import net.crankedpvp.factionlogs.struct.impl.SpawnerBreak; +import net.crankedpvp.factionlogs.utils.FactionsLogsAPI; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.spawners.SpawnerData; +import net.crankedpvp.spawners.events.SpawnerBreakEvent; +import net.crankedpvp.spawners.items.ItemSpawner; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.EntityExplodeEvent; + +import java.util.List; + +public class SpawnerBreakListener implements Listener { + + private final CoreProtectAPI coreProtectAPI; + + public SpawnerBreakListener() { + this.coreProtectAPI = CoreProtect.getInstance().getAPI(); + + } + + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onExplode(EntityExplodeEvent event) { + double chance = event.getEntity() instanceof TNTPrimed ? 0.20 : event.getEntity() instanceof Creeper ? 0.30 : 0; + if (chance <= 0) { + return; + } + if (!(event.getEntity() instanceof Creeper) && !(event.getEntity() instanceof TNTPrimed)) { + return; + } + + if(event.getEntity() instanceof Creeper) { + Creeper c = (Creeper) event.getEntity(); + if(CreeperListener.creepers.containsKey(c.getUniqueId())) { + CreeperTypes egg_type = CreeperListener.creepers.get(c.getUniqueId()); + if(egg_type == CreeperTypes.LUCKY) { + chance = 0.5; + } + if(egg_type == CreeperTypes.RAID) { + chance = 1; + } + + } + } + + List blocks = event.blockList(); + for (int i = blocks.size() - 1; i >= 0; i--) { + Block block = blocks.get(i); + if (block.getType() == Material.MOB_SPAWNER) { + SpawnerData data = SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(block.getLocation()); + if (data != null) { + EntityType type = data.getEntityType(); + int amount = data.getSpawnerAmount(); + World world = block.getWorld(); + Location location = block.getLocation(); + int spawnerAmount = 0; + for(int pos = 0; pos < amount; pos++) { + if(chance > Math.random()) { + spawnerAmount++; + } + } + if (spawnerAmount > 0) { + world.dropItem(location, ItemSpawner.getItem(type, spawnerAmount)); + } + data.setSpawnerAmount(0); + SpawnerPlugin.getInstance().getSpawnerManager().removeFromCache(data); + + SpawnerBreakEvent spawnerBreakEvent = new SpawnerBreakEvent(block.getLocation()); + Bukkit.getPluginManager().callEvent(spawnerBreakEvent); + + +/* if (CollectorManager.DELEGATE.isCollectorContained(block.getLocation())) { + net.crankedpvp.collectors.collector.Collector collector = CollectorManager.DELEGATE.getCollector(block.getLocation()); + collector.clearSpawners(); + collector.scanSpawners(collector.getLocation()); + }*/ + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onMine(BlockBreakEvent event) { + if (event.getBlock().getType() == Material.MOB_SPAWNER) { + Block block = event.getBlock(); + SpawnerData data = SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(block.getLocation()); + if (data != null) { + this.coreProtectAPI.logRemoval(event.getPlayer().getName(), block.getLocation(), block.getType(), block.getData()); + + EntityType type = data.getEntityType(); + int amount = data.getSpawnerAmount(); + data.setSpawnerAmount(0); + block.getWorld().dropItem(block.getLocation(), ItemSpawner.getItem(type, amount)); + event.getPlayer().sendMessage(CC.translate("&c&l- &c&n" + amount + "&c " + EntityUtils.getEntityName(type) + " Spawner(s)")); + SpawnerPlugin.getInstance().getSpawnerManager().removeFromCache(data); + block.setType(Material.AIR); + event.setCancelled(true); + + SpawnerBreakEvent spawnerBreakEvent = new SpawnerBreakEvent(block.getLocation()); + Bukkit.getPluginManager().callEvent(spawnerBreakEvent); + +/* if (CollectorManager.DELEGATE.isCollectorContained(event.getBlock().getLocation())) { + Collector collector = CollectorManager.DELEGATE.getCollector(event.getBlock().getLocation()); + collector.clearSpawners(); + collector.scanSpawners(collector.getLocation()); + }*/ + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (!fPlayer.getFaction().isWilderness()) { + FactionsLogsAPI.log(fPlayer.getFaction().getId(), new SpawnerBreak(amount, event.getBlock().getLocation(), type, fPlayer.getPlayer().getUniqueId())); + } + } + } + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/listeners/SpawnerSpawnListener.java b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/SpawnerSpawnListener.java new file mode 100644 index 0000000..727ae3d --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/listeners/SpawnerSpawnListener.java @@ -0,0 +1,37 @@ +package net.crankedpvp.spawners.listeners; + +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.utils.MobStackerUtils; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.SpawnerSpawnEvent; + +import java.util.ArrayList; +import java.util.List; + +public class SpawnerSpawnListener implements Listener { + private final MobStackerUtils mobStackerUtils; + private List stackMobs; + + public SpawnerSpawnListener(SpawnerPlugin plugin) { + this.mobStackerUtils = plugin.getMobStackerUtils(); + this.stackMobs = new ArrayList<>(); + stackMobs.add(EntityType.BLAZE); + stackMobs.add(EntityType.SKELETON); + stackMobs.add(EntityType.ZOMBIE); + stackMobs.add(EntityType.SPIDER); + stackMobs.add(EntityType.CAVE_SPIDER); + } + + + @EventHandler(priority = EventPriority.LOW) + public void stopMobSpawn(SpawnerSpawnEvent e) { + if (stackMobs.contains(e.getEntityType())) { + mobStackerUtils.stackMobs(e); + } else { + e.setCancelled(true); + } + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/FactionCache.java b/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/FactionCache.java new file mode 100644 index 0000000..d4cffd5 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/FactionCache.java @@ -0,0 +1,18 @@ +package net.crankedpvp.spawners.struct.ftop; + +import com.google.common.collect.Maps; +import net.crankedpvp.spawners.data.ftop.FactionData; + +import java.util.Map; + +public class FactionCache { + private static Map factions = Maps.newHashMap(); + + public static Map getData() { + return factions; + } + + public static void setFactionData(Map factions) { + FactionCache.factions = factions; + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/FactionsTopManager.java b/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/FactionsTopManager.java new file mode 100644 index 0000000..e3aee43 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/FactionsTopManager.java @@ -0,0 +1,97 @@ +package net.crankedpvp.spawners.struct.ftop; + +import com.google.common.collect.Maps; +import com.massivecraft.factions.Faction; +import net.crankedpvp.crankedutils.utils.FactionUtils; +import net.crankedpvp.crankedutils.utils.SortUtils; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.ftop.FactionData; +import net.crankedpvp.spawners.utils.ConfigManager; +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.EntityType; + +import java.util.EnumMap; +import java.util.Map; +import java.util.logging.Level; + +public class FactionsTopManager { + + private final EnumMap spawnerWorth; + + public FactionsTopManager(SpawnerPlugin plugin) { + this.spawnerWorth = new EnumMap<>(EntityType.class); + + ConfigManager configmanager = plugin.getConfigManager(); + FileConfiguration config = configmanager.getConfig(ConfigManager.ConfigFile.PRIMARY); + ConfigurationSection configurationSection = config.getConfigurationSection("spawners.worth"); + + for (String key : configurationSection.getKeys(false)) { + int worth = configurationSection.getInt(key); + EntityType entityType; + + try { + entityType = EntityType.valueOf(key.toUpperCase()); + } catch (IllegalArgumentException e) { + Bukkit.getLogger().log(Level.WARNING, "Invalid Spawner type in config"); + continue; + } + + this.spawnerWorth.put(entityType, worth); + } + } + + public void recalculateFactionsTop() { + FactionCache.getData().clear(); + Bukkit.getScheduler().runTaskAsynchronously(SpawnerPlugin.getInstance(), () -> { + Map factions = Maps.newHashMap(); + for (Faction faction : FactionUtils.getAllFactions()) { + if (faction.isSafeZone() || faction.isWarZone() || faction.isWilderness()) + continue; + FactionData factionData = new FactionData(faction); + factions.put(factionData, factionData.getSpawnerValue()); + } + factions = SortUtils.sort(factions); + Map data = Maps.newLinkedHashMap(); + int pos = 0; + for (Map.Entry entry : factions.entrySet()) { + data.put(pos, entry.getKey()); + pos++; + } + FactionCache.setFactionData(data); + }); + } + + public Map getTopFactions(int from, int to) { + Map data = Maps.newHashMap(); + for (Map.Entry entry : FactionCache.getData().entrySet()) { + int value = entry.getKey(); + if (from <= value && to >= value) + data.put(value, entry.getValue()); + } + return data; + } + + public int getFactionTop(Faction faction) { + int place=0; + for (Map.Entry entry : getTopFactions(0, 9999).entrySet()) { + if (entry.getValue().getFaction().getId().equals(faction.getId())) { + place = entry.getKey(); + return place +1; + } + } + return place; + } + + public FactionData getFactionData(Faction faction) { + for(FactionData value : FactionCache.getData().values()) { + if(faction.equals(value.getFaction())) return value; + } + return null; + } + + public long getValueOfSpawner(EntityType type) { + return this.spawnerWorth.getOrDefault(type, 0); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/RecalculationTask.java b/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/RecalculationTask.java new file mode 100644 index 0000000..36d03cc --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/struct/ftop/RecalculationTask.java @@ -0,0 +1,18 @@ +package net.crankedpvp.spawners.struct.ftop; + +import net.crankedpvp.spawners.SpawnerPlugin; +import org.bukkit.scheduler.BukkitRunnable; + +public class RecalculationTask extends BukkitRunnable { + + private final FactionsTopManager factionsTopManager; + + public RecalculationTask(SpawnerPlugin plugin) { + this.factionsTopManager = plugin.getFactionsTopManager(); + } + + @Override + public void run() { + this.factionsTopManager.recalculateFactionsTop(); + } +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/struct/grinding/GrindingCache.java b/Spawners/src/main/java/net/crankedpvp/spawners/struct/grinding/GrindingCache.java new file mode 100644 index 0000000..0eac182 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/struct/grinding/GrindingCache.java @@ -0,0 +1,74 @@ +package net.crankedpvp.spawners.struct.grinding; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EconomyUtils; +import net.crankedpvp.crankedutils.utils.NumberUtils; +import net.crankedpvp.crankedutils.utils.XPUtils; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.shards.ShardsAPI; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.UUID; + +public class GrindingCache { + private int mobsKilled; + private double moneyEarned; + private int expEarned; + private int shardsEarned; + private UUID uuid; + + public GrindingCache(UUID uuid) { + this.moneyEarned = 0; + this.expEarned = 0; + this.shardsEarned = 0; + this.mobsKilled = 0; + this.uuid = uuid; + } + + public void claimGrindingRewards() { + if (expEarned == 0 && moneyEarned == 0 && shardsEarned == 0) { + return; + } + + Player player = Bukkit.getPlayer(uuid); + if (player == null || !player.isOnline()) return; + + XPUtils.addExperience(player, expEarned); + EconomyUtils.depositBalance(player,moneyEarned); + ShardsAPI.addShards(player, shardsEarned); + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).addEXPGained(expEarned); + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).addMobsKilled(this.mobsKilled); + + player.sendMessage(CC.translate("")); + player.sendMessage(CC.translate("&6&lGrinding Rewards")); + player.sendMessage(CC.translate("&8 ➥ &7EXP: &d" + NumberUtils.formatMoney(expEarned))); + player.sendMessage(CC.translate("&8 ➥ &7Money: &2$&a" + NumberUtils.formatMoney(moneyEarned))); + player.sendMessage(CC.translate("&8 ➥ &7Gold: &6⛃&e" + NumberUtils.formatMoney(shardsEarned))); + player.sendMessage(CC.translate("&8 ➥ &7Mobs Killed: &c" + NumberUtils.formatMoney(mobsKilled))); + player.sendMessage(CC.translate("&7&o(( Every &f10s&7&o you will receive your grinding rewards from the last 10s. ))")); + player.sendMessage(CC.translate("")); + + this.expEarned = 0; + this.moneyEarned = 0; + this.shardsEarned = 0; + this.mobsKilled = 0; + } + + public void addExp(int amount) { + this.expEarned += amount; + } + + public void addShards(int amount) { + this.shardsEarned += amount; + } + + public void addMoney(double amount) { + this.moneyEarned += amount; + } + + public void addMobKilled(int amount) { + this.mobsKilled += amount; + } + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/struct/grinding/GrindingManager.java b/Spawners/src/main/java/net/crankedpvp/spawners/struct/grinding/GrindingManager.java new file mode 100644 index 0000000..658e3ca --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/struct/grinding/GrindingManager.java @@ -0,0 +1,38 @@ +package net.crankedpvp.spawners.struct.grinding; + +import lombok.Getter; +import net.crankedpvp.spawners.SpawnerPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +@Getter +public class GrindingManager { + private Map grindingCacheMap; + + public GrindingManager() { + this.grindingCacheMap = new HashMap<>(); + /* + Bukkit.getScheduler().scheduleSyncRepeatingTask(SpawnerPlugin.getInstance(), ()-> { + for (GrindingCache grindingCache : grindingCacheMap.values()) { + grindingCache.claimGrindingRewards(); + } + }, 40L, 10*20L); + + */ + + } + + public GrindingCache getGrindingCache(Player player) { + UUID uuid = player.getUniqueId(); + if (!grindingCacheMap.containsKey(uuid)) { + grindingCacheMap.put(uuid, new GrindingCache(uuid)); + } + return grindingCacheMap.get(uuid); + } + + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/struct/spawners/SpawnerManager.java b/Spawners/src/main/java/net/crankedpvp/spawners/struct/spawners/SpawnerManager.java new file mode 100644 index 0000000..d2e7fdf --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/struct/spawners/SpawnerManager.java @@ -0,0 +1,51 @@ +package net.crankedpvp.spawners.struct.spawners; + +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.spawners.SpawnerData; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.utils.SaveLoadManager; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.block.BlockState; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.entity.EntityType; + +import java.util.HashMap; +import java.util.Map; + +public class SpawnerManager extends SaveLoadManager { + + + public SpawnerManager(SpawnerPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "/data", SpawnerData.class); + } + + public SpawnerData getSpawnerData(Location location, EntityType type, int amount) { + if (!containsKey(SpawnerData.locationToString(location))) { + SpawnerData spawnerData = new SpawnerData(type, amount, location); + addToCache(spawnerData); + } + return getFromCache(SpawnerData.locationToString(location)); + + } + + public SpawnerData getSpawnerData(Location location) { + return getFromCache(SpawnerData.locationToString(location)); + + } + + + public static boolean canPlaceStackedSpawnerInThisChunk(Chunk chunk, EntityType spawnertype) { + for (BlockState blockState : chunk.getTileEntities()) { + if (blockState instanceof CreatureSpawner) { + EntityType type = ((CreatureSpawner) blockState).getSpawnedType(); + if (type == spawnertype) { + return false; + } + } + } + return true; + } + +} + diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/utils/ConfigManager.java b/Spawners/src/main/java/net/crankedpvp/spawners/utils/ConfigManager.java new file mode 100644 index 0000000..b22d515 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/utils/ConfigManager.java @@ -0,0 +1,51 @@ +package net.crankedpvp.spawners.utils; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.crankedpvp.crankedutils.utils.config.AbstractConfig; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; + +public class ConfigManager { + + @Getter + private final Map configs = new HashMap<>(); + + public ConfigManager(JavaPlugin plugin) { + for (ConfigFile configFile : ConfigFile.values()) { + AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName()); + configs.put(configFile, abstractConfig); + } + } + + public void setupFiles() { + configs.values().forEach(AbstractConfig::setupConfigFile); + } + + public void reloadFiles() { + configs.values().forEach(AbstractConfig::reloadConfig); + } + + public AbstractConfig getAbstractConfig(ConfigFile configFile) { + return configs.get(configFile); + } + + public FileConfiguration getConfig(ConfigFile configFile) { + return getAbstractConfig(configFile).getConfig(); + } + + @Getter + @RequiredArgsConstructor + public enum ConfigFile { + + PRIMARY("config.yml"), + ; + + private final String fileName; + + } + +} diff --git a/Spawners/src/main/java/net/crankedpvp/spawners/utils/MobStackerUtils.java b/Spawners/src/main/java/net/crankedpvp/spawners/utils/MobStackerUtils.java new file mode 100644 index 0000000..0ae89d5 --- /dev/null +++ b/Spawners/src/main/java/net/crankedpvp/spawners/utils/MobStackerUtils.java @@ -0,0 +1,180 @@ +package net.crankedpvp.spawners.utils; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.ChunkUtils; +import net.crankedpvp.crankedutils.utils.EntityUtils; +import net.crankedpvp.spawners.SpawnerPlugin; +import net.crankedpvp.spawners.data.spawners.SpawnerData; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.SpawnerSpawnEvent; + +import java.util.HashMap; +import java.util.List; + + +public class MobStackerUtils { + + private final HashMap mobMap; + + public MobStackerUtils() { + this.mobMap = new HashMap<>(); + int delayS = 15; + + Bukkit.getScheduler().scheduleSyncRepeatingTask(SpawnerPlugin.getInstance(), () -> { + for (int i = 0; i < mobMap.keySet().size(); i++) { + Entity entity = (Entity) mobMap.keySet().toArray()[i]; + if (!entity.isValid() || entity.isDead()) { + mobMap.remove(entity); + continue; + } + stackMobs(entity); + } + }, 40L, delayS * 20L); + } + + public static void onEnable() { + for (World world : Bukkit.getWorlds()) { + for (Entity entity : world.getEntities()) { + if (!(entity instanceof Player) && !(entity instanceof ArmorStand)) { + entity.remove(); + } + } + } + } + + public HashMap getMobMap() { + return mobMap; + } + + public int getStackSize(Entity entity) { + return mobMap.getOrDefault(entity, 1); + } + + public void setStackSize(Entity entity, int size) { + entity.setCustomName(CC.RedB + EntityUtils.getEntityName(entity.getType()) + " " + CC.Gray + "[" + CC.White + "x " + CC.Underline + size + CC.Gray + "]"); + mobMap.put(entity, size); + } + + public boolean isStackedMob(Entity entity) { + return mobMap.containsKey(entity); + } + + public void removeStackedMob(Entity entity) { + if (!entity.isDead()) entity.remove(); + mobMap.remove(entity); + } + + public void stackMobs(SpawnerSpawnEvent event) { + Chunk chunk = ChunkUtils.getChunkIfLoaded((int) Math.floor(event.getEntity().getLocation().getChunk().getX()), (int) Math.floor(event.getEntity().getLocation().getChunk().getZ()), event.getLocation().getWorld()); + //Chunk chunk = event.getLocation().getChunk(); + + if (chunk == null) { + System.out.println("[Spawners] Skipping because chunk is null"); + event.setCancelled(true); + return; + } + List entities = ChunkUtils.getEntitiesInChunk(chunk); + int entityStack = 0; + Entity entity = event.getEntity(); + Location location = event.getSpawner().getLocation(); + SpawnerData data = SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(location); + + int size; + + if (entity.getType() == EntityType.BLAZE) { + size = entityStack + (data != null ? (data.getSpawnerAmount() * 10) + 100 : 100); + + + } else { + size = entityStack + (data != null ? data.getSpawnerAmount() : 100); + } + + int stackSize = 0; + Entity highestStackedEntity = null; + + + for (Entity nearbyEntity : entities) { + if (nearbyEntity.getType() != entity.getType()) continue; + if (!isStackedMob(nearbyEntity)) continue; + if (getStackSize(nearbyEntity) <= stackSize) continue; + highestStackedEntity = nearbyEntity; + stackSize = getStackSize(nearbyEntity); + } + if (highestStackedEntity == null) { + setStackSize(entity, size); + } else { + setStackSize(highestStackedEntity, stackSize + size); + removeStackedMob(entity); + event.setCancelled(true); + } + } + + public void stackMobs(Entity entity) { + int stack = getStackSize(entity); + Entity highestStackEntity = entity; + + for (Entity nearbyEntity : entity.getNearbyEntities(10, 4, 10)) { + if (nearbyEntity.getType() != entity.getType()) continue; + if (!isStackedMob(nearbyEntity)) continue; + int nearbyStack = getStackSize(nearbyEntity); + if (nearbyStack >= stack) { + highestStackEntity = nearbyEntity; + } + + } + if (highestStackEntity.getUniqueId() != entity.getUniqueId()) { + setStackSize(highestStackEntity, stack + getStackSize(highestStackEntity)); + removeStackedMob(entity); + } + } + + /*public void stackMobs(SpawnerSpawnEvent event) { + + Chunk chunk = event.getLocation().getChunk(); + Entity[] entities = chunk.getEntities(); + + + int entityStack = 0; + Entity entity = event.getEntity(); + Location location = event.getSpawner().getLocation(); + SpawnerData data = SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(location); + + int size = 0; + + if (entity.getType() == EntityType.BLAZE) { + size = entityStack + (data != null ? (data.getSpawnerAmount()*10)+100 : 100); + } else { + size = entityStack + (data != null ? data.getSpawnerAmount() : 100); + } + + + + int stackSize = 0; + Entity highestStackedEntity = null; + + + for (Entity nearbyEntity : entities) { + if (nearbyEntity.getType() != entity.getType()) continue; + if (!isStackedMob(nearbyEntity)) continue; + if (getStackSize(nearbyEntity) <= stackSize) continue; + highestStackedEntity = nearbyEntity; + stackSize = getStackSize(nearbyEntity); + } + if (highestStackedEntity == null) { + setStackSize(entity, size); + } else { + setStackSize(highestStackedEntity, stackSize + size); + removeStackedMob(entity); + event.setCancelled(true); + } + }*/ + +} diff --git a/Spawners/src/main/resources/config.yml b/Spawners/src/main/resources/config.yml new file mode 100644 index 0000000..c93b1bc --- /dev/null +++ b/Spawners/src/main/resources/config.yml @@ -0,0 +1,11 @@ +commonKeyChance: 4 +rareKeyChance: 1 +mythicKeyChance: 0.35 +chefRewardChance: 0.2 +spawners: + can-place: true + max-stack-size: 1000 + worth: + IRON_GOLEM: 5000000 + VILLAGER: 10000000 + WITCH: 8000000 diff --git a/Spawners/src/main/resources/language.yml b/Spawners/src/main/resources/language.yml new file mode 100644 index 0000000..7fddc45 --- /dev/null +++ b/Spawners/src/main/resources/language.yml @@ -0,0 +1 @@ +GRINDING_MONEY_GIVE: "&3&lSpawners &8➥ &7You have received &2$&a%amount%&7 from grinding stacked mobs." \ No newline at end of file diff --git a/Spawners/src/main/resources/plugin.yml b/Spawners/src/main/resources/plugin.yml new file mode 100644 index 0000000..e703eea --- /dev/null +++ b/Spawners/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: CrankedSpawners +main: net.crankedpvp.spawners.SpawnerPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils + - StorageUtil \ No newline at end of file diff --git a/Staff/pom.xml b/Staff/pom.xml new file mode 100644 index 0000000..4947219 --- /dev/null +++ b/Staff/pom.xml @@ -0,0 +1,40 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Staff + + + 8 + 8 + + + + + net.crankedpvp + Utils + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + com.earth2me.essentials + EssentialsX + 1.0 + system + ${project.basedir}/../.lib/EssentialsX-2.19.7.jar + + + + \ No newline at end of file diff --git a/Staff/src/main/java/net/crankedpvp/staff/StaffPlugin.java b/Staff/src/main/java/net/crankedpvp/staff/StaffPlugin.java new file mode 100644 index 0000000..3e793be --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/StaffPlugin.java @@ -0,0 +1,74 @@ +package net.crankedpvp.staff; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.staff.commands.*; +import net.crankedpvp.staff.listeners.*; +import net.crankedpvp.staff.managers.FreezeManager; +import net.crankedpvp.staff.managers.GhostMuteManager; +import net.crankedpvp.staff.managers.ReportManager; +import net.crankedpvp.staff.managers.StaffManager; +import net.crankedpvp.staff.tasks.FreezeTeleportTask; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class StaffPlugin extends JavaPlugin { + + public static String prefix = "&a&lStaff &8➥ "; + + @Getter + private static StaffPlugin instance; + + @Getter + private StaffManager staffManager; + + @Getter + private FreezeManager freezeManager; + + @Getter + private GhostMuteManager ghostMuteManager; + + @Getter + private ReportManager reportManager; + + private FreezeTeleportTask teleportTask; + + @Override + public void onEnable() { + instance = this; + this.staffManager = new StaffManager(this); + this.freezeManager = new FreezeManager(this); + this.reportManager = new ReportManager(this); + this.ghostMuteManager = new GhostMuteManager(this); + this.reportManager.loadAll(); + + CommandManager commandManager = new CommandManager(this); + commandManager.register(new StaffModeCommand(this)); + commandManager.register(new FreezeCommand(this)); + commandManager.register(new ReportCommand(this)); + commandManager.register(new ViewReportsCommand(this)); + commandManager.register(new GhostMuteCommand(this)); + this.registerListeners(); + + this.teleportTask = new FreezeTeleportTask(this); + this.teleportTask.runTaskTimer(this, 80L, 20L); + } + + @Override + public void onDisable() { + this.staffManager.getPlayersInStaffMode().forEach((player, staffMode) -> staffMode.removePlayerFromStaffMode()); + this.reportManager.saveAll(); + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new VanishToggleListener(this), this); + pluginManager.registerEvents(new RandomTeleportListener(this), this); + pluginManager.registerEvents(new PlayerListener(this), this); + pluginManager.registerEvents(new PlayerKickListener(this), this); + pluginManager.registerEvents(new PlayerQuitListener(this), this); + pluginManager.registerEvents(new FreezeListener(this), this); + pluginManager.registerEvents(new StaffJoinListener(this), this); + //pluginManager.registerEvents(new PlayerChatListener(this), this); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/commands/FreezeCommand.java b/Staff/src/main/java/net/crankedpvp/staff/commands/FreezeCommand.java new file mode 100644 index 0000000..a618369 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/commands/FreezeCommand.java @@ -0,0 +1,35 @@ +package net.crankedpvp.staff.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +@Command("freeze") +@Alias({"crankedfreeze"}) +public class FreezeCommand extends CommandBase { + + private StaffPlugin plugin; + public FreezeCommand(StaffPlugin plugin) { + this.plugin = plugin; + } + + @Default + @Permission("staff.freeze") + public void defaultCommand(Player player, @Completion("#players") Player toFreeze) { + if(this.plugin.getFreezeManager().getFrozenPlayers().containsKey(toFreeze)) { + this.plugin.getFreezeManager().getFrozenPlayers().remove(toFreeze); + Bukkit.getOnlinePlayers().stream().filter(loopPlayer -> loopPlayer.hasPermission("staff.freeze")).forEach(loopPlayer -> loopPlayer.sendMessage(CC.translate("&b&lFreeze &8" + Arrow.arrow() + " &7The player &f" + toFreeze.getName() + " &7has been unfrozen by &f" + player.getName()))); + return; + } + + this.plugin.getFreezeManager().getFrozenPlayers().put(toFreeze, toFreeze.getLocation().clone()); + Bukkit.getOnlinePlayers().stream().filter(loopPlayer -> loopPlayer.hasPermission("staff.freeze")).forEach(loopPlayer -> loopPlayer.sendMessage(CC.translate("&b&lFreeze &8" + Arrow.arrow() + " &7The player &f" + toFreeze.getName() + " &7has been frozen by &f" + player.getName()))); + TitleUtils.sendTitle(toFreeze, CC.translate("&c&lFROZEN"), CC.translate("&7DO NOT LOG OUT"), 1, 10, 1); + toFreeze.sendMessage(CC.translate("&b&lFreeze &8" + Arrow.arrow() + " &7You have been &c&lFROZEN&7. Join discord.gg/crankedpvp immediately.")); + } +} \ No newline at end of file diff --git a/Staff/src/main/java/net/crankedpvp/staff/commands/GhostMuteCommand.java b/Staff/src/main/java/net/crankedpvp/staff/commands/GhostMuteCommand.java new file mode 100644 index 0000000..98f4fef --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/commands/GhostMuteCommand.java @@ -0,0 +1,54 @@ +package net.crankedpvp.staff.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.managers.GhostMuteManager; +import org.bukkit.entity.Player; + +@Command("ghostmute") +@Alias({"gmute", "muteg", "tempmuteg"}) +public class GhostMuteCommand extends CommandBase { + + private final StaffPlugin plugin; + private final GhostMuteManager ghostMuteManager; + + public GhostMuteCommand(StaffPlugin plugin) { + this.plugin = plugin; + this.ghostMuteManager = plugin.getGhostMuteManager(); + } + + @Default + @Permission("ghostmute.use") + public void ghostMute(Player sender, @Completion("#players") Player toMute, @Optional String time) { + + if(time == null) { + sender.sendMessage(CC.translate("&3&lGhost Mute &8" + Arrow.arrow() + " &aYou have successfully ghost muted " + toMute.getName())); + if(toMute.hasPermission("ghostmute.bypass")) { + this.ghostMuteManager.addPlayerToGhostMute(sender); + } else { + this.ghostMuteManager.addPlayerToGhostMute(toMute); + } + return; + } + + sender.sendMessage(CC.translate("&3&lGhost Mute &8" + Arrow.arrow() + " &aYou have successfully ghost muted " + toMute.getName())); + if(toMute.hasPermission("ghostmute.bypass")) { + this.ghostMuteManager.addPlayerToGhostMute(sender); + } else { + this.ghostMuteManager.addPlayerToGhostMuteFor(toMute, time); + } + } + + @SubCommand("remove") + @Alias({"stop"}) + @Permission("ghostmute.use") + public void ghostUnmute(Player sender, @Completion("#players") Player toUnmute) { + + sender.sendMessage(CC.translate("&3&lGhost Mute &8" + Arrow.arrow() + " &aYou have successfully removed the ghost mute for " + toUnmute.getName())); + this.ghostMuteManager.removePlayerFromGhostMute(toUnmute); + + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/commands/ReportCommand.java b/Staff/src/main/java/net/crankedpvp/staff/commands/ReportCommand.java new file mode 100644 index 0000000..b613b46 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/commands/ReportCommand.java @@ -0,0 +1,36 @@ +package net.crankedpvp.staff.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Completion; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.WrongUsage; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.struct.ReportCooldown; +import org.bukkit.entity.Player; + +@Command("report") +public class ReportCommand extends CommandBase { + + private final StaffPlugin plugin; + + public ReportCommand(StaffPlugin plugin) { + this.plugin = plugin; + } + + @Default + @WrongUsage("&c/report ") + public void defaultCommand(Player sender, @Completion("#players") Player reported, String[] reason) { + if (CooldownUtils.isCooldownActive(sender, "report_cooldown")) { + sender.sendMessage(CC.translate("&a&lStaff&8 " + Arrow.arrow() + " &7You are currently on report cooldown for " + CooldownUtils.getFormattedCooldown(sender, "report_cooldown") + ".")); + return; + } + + this.plugin.getReportManager().createReport(sender, reported, String.join(" ", reason)); + sender.sendMessage(CC.translate("&a&lStaff&8 " + Arrow.arrow() + " &7You have successfully reported &a" + reported.getName() + "&7 for &a" + String.join(" ", reason) + "&7.")); + CooldownUtils.registerCooldown(sender, new ReportCooldown()); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/commands/StaffModeCommand.java b/Staff/src/main/java/net/crankedpvp/staff/commands/StaffModeCommand.java new file mode 100644 index 0000000..0a7ef7c --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/commands/StaffModeCommand.java @@ -0,0 +1,32 @@ +package net.crankedpvp.staff.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.struct.StaffMode; +import org.bukkit.entity.Player; + +@Command("staff") +@Alias({"staffmode", "csm"}) +public class StaffModeCommand extends CommandBase { + + private StaffPlugin plugin; + public StaffModeCommand(StaffPlugin plugin) { + this.plugin = plugin; + } + + @Default + @Permission("cranked.staff") + public void defaultCommand(Player player) { + if(this.plugin.getStaffManager().isPlayerInStaffMode(player)) { + StaffMode staffMode = this.plugin.getStaffManager().getStaffModeFromPlayer(player); + staffMode.removePlayerFromStaffMode(); + return; + } + StaffMode staffMode = new StaffMode(player); + staffMode.putPlayerInStaffMode(); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/commands/ViewReportsCommand.java b/Staff/src/main/java/net/crankedpvp/staff/commands/ViewReportsCommand.java new file mode 100644 index 0000000..c3c40f9 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/commands/ViewReportsCommand.java @@ -0,0 +1,26 @@ +package net.crankedpvp.staff.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.annotations.Permission; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.inventories.ReportsGUI; +import org.bukkit.entity.Player; + +@Command("reports") +public class ViewReportsCommand extends CommandBase { + + private final StaffPlugin plugin; + + public ViewReportsCommand(StaffPlugin plugin) { + this.plugin = plugin; + } + + @Default + @Permission("displayname.Mod") + public void defaultCommand(Player sender) { + ReportsGUI reportsGUI = new ReportsGUI(); + reportsGUI.getReportsInventory().open(sender); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/inventories/ReportsGUI.java b/Staff/src/main/java/net/crankedpvp/staff/inventories/ReportsGUI.java new file mode 100644 index 0000000..87e4657 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/inventories/ReportsGUI.java @@ -0,0 +1,92 @@ +package net.crankedpvp.staff.inventories; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.SkullUtils; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.struct.Report; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.ItemStack; + +import java.time.format.DateTimeFormatter; + +public class ReportsGUI { + + private final static DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); + private final static ItemStack PREV_PAGE = (new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.")).colorize().build(); + private final static ItemStack NEXT_PAGE = (new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.")).colorize().build(); + + + @Getter + private final PaginatedGui reportsInventory; + + public ReportsGUI() { + this.reportsInventory = Gui.paginated() + .disableAllInteractions() + .pageSize(27) + .rows(4) + .title(Component.text("View Reports")) + .create(); + + this.reportsInventory.setItem(4, 3, new GuiItem(PREV_PAGE, event -> reportsInventory.previous())); + this.reportsInventory.setItem(4, 7, new GuiItem(NEXT_PAGE, event -> reportsInventory.next())); + + this.reportsInventory.setItem(4, 5, new GuiItem(new ItemBuilder(Material.BARRIER).setName("&cClose").colorize().build(), event -> { + event.setCancelled(true); + event.getWhoClicked().closeInventory(); + })); + + this.populateGui(); + + this.reportsInventory.getFiller().fillBottom(new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE).setName("&7").colorize().setDurability((short) 7).build())); + + } + + private void populateGui() { + for (Report report : StaffPlugin.getInstance().getReportManager().getCacheValues()) { + OfflinePlayer reported = Bukkit.getOfflinePlayer(report.getReported()); + OfflinePlayer reporter = Bukkit.getOfflinePlayer(report.getReporter()); + + this.reportsInventory.addItem(new GuiItem( + new ItemBuilder(SkullUtils.getSkullFromPlayer(reported)) + .setName("&c&lReport ID:&7 " + report.getReportID()) + .setLore( + "", + "&c&lInfo:", + "&7From: &f" + reporter.getName(), + "&7Reported: &f" + reported.getName(), + "&7Reason: &f" + report.getReason(), + "&7Date: &f" + DATE_TIME_FORMAT.format(report.getDateTimeOfReport()), + "", + "&c&lActions:", + "&7Right-Click: &fDelete report", + "&7Left-Click: &fTeleport to reported player" + ) + .colorize() + .build(), + event -> { + if (event.getClick() == ClickType.RIGHT) { + StaffPlugin.getInstance().getReportManager().removeFromCache(report); + this.reportsInventory.clearPageItems(); + this.populateGui(); + this.reportsInventory.update(); + SoundUtils.playSuccessSound(((Player) event.getWhoClicked())); + } else if (event.getClick() == ClickType.LEFT) { + if (reported.isOnline()) { + event.getWhoClicked().teleport((Player) reported); + } + } + } + )); + } + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/listeners/FreezeListener.java b/Staff/src/main/java/net/crankedpvp/staff/listeners/FreezeListener.java new file mode 100644 index 0000000..97458c9 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/listeners/FreezeListener.java @@ -0,0 +1,51 @@ +package net.crankedpvp.staff.listeners; + +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; + +public class FreezeListener implements Listener { + + private StaffPlugin plugin; + public FreezeListener(StaffPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void damage(EntityDamageByEntityEvent event) { + if(event.getEntity() == null) return; + if(!(event.getEntity() instanceof Player)) return; + if(event.getDamager() == null) return; + if(!(event.getDamager() instanceof Player)) return; + + Player victim = ((Player) event.getEntity()); + Player attacker = ((Player) event.getDamager()); + + if(this.plugin.getFreezeManager().getFrozenPlayers().containsKey(victim) || this.plugin.getFreezeManager().getFrozenPlayers().containsKey(attacker)) { + event.setCancelled(true); + return; + } + } + + @EventHandler + public void drop(PlayerDropItemEvent event) { + if(event.getPlayer() == null) return; + if(this.plugin.getFreezeManager().getFrozenPlayers().containsKey(event.getPlayer())) { + event.setCancelled(true); + return; + } + } + + @EventHandler + public void pickup(PlayerPickupItemEvent event) { + if(event.getPlayer() == null) return; + if(this.plugin.getFreezeManager().getFrozenPlayers().containsKey(event.getPlayer())) { + event.setCancelled(true); + return; + } + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerKickListener.java b/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerKickListener.java new file mode 100644 index 0000000..750111e --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerKickListener.java @@ -0,0 +1,21 @@ +package net.crankedpvp.staff.listeners; + +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerKickEvent; + +public class PlayerKickListener implements Listener { + + private final StaffPlugin plugin; + public PlayerKickListener(StaffPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void playerKick(PlayerKickEvent event) { + if(event.getPlayer() == null) return; + if(!this.plugin.getStaffManager().isPlayerInStaffMode(event.getPlayer())) return; + this.plugin.getStaffManager().getStaffModeFromPlayer(event.getPlayer()).removePlayerFromStaffMode(); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerListener.java b/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerListener.java new file mode 100644 index 0000000..1972b8b --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerListener.java @@ -0,0 +1,74 @@ +package net.crankedpvp.staff.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; + +public class PlayerListener implements Listener { + + private final StaffPlugin plugin; + public PlayerListener(StaffPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void stopInventoryClick(InventoryClickEvent event) { + if(event.getWhoClicked() == null) return; + if(!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + if(!this.plugin.getStaffManager().isPlayerInStaffMode(player)) return; + event.setCancelled(true); + player.sendMessage(CC.translate(StaffPlugin.prefix + "&cYou cannot pursue this action while in staff mode")); + } + + @EventHandler + public void onPickup(PlayerPickupItemEvent event) { + if(event.getPlayer() == null) return; + if(event.getItem() == null) return; + Player player = event.getPlayer(); + if(!this.plugin.getStaffManager().isPlayerInStaffMode(player)) return; + event.setCancelled(true); + player.sendMessage(CC.translate(StaffPlugin.prefix + "&cYou cannot pickup items while in staff mode")); + } + + + @EventHandler + public void onDrop(PlayerDropItemEvent event) { + if(event.getPlayer() == null) return; + if(event.getItemDrop() == null) return; + Player player = event.getPlayer(); + if(!this.plugin.getStaffManager().isPlayerInStaffMode(player)) return; + event.setCancelled(true); + player.sendMessage(CC.translate(StaffPlugin.prefix + "&cYou cannot drop items while in staff mode")); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onDeath(PlayerDeathEvent event) { + if(event.getEntity() == null) return; + Player player = event.getEntity(); + if(!this.plugin.getStaffManager().isPlayerInStaffMode(player)) return; + event.getDrops().clear(); + this.plugin.getStaffManager().getStaffModeFromPlayer(player).removePlayerFromStaffMode(); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void breakBlockEvent(BlockBreakEvent event) { + if(event.getPlayer() == null) return; + if(event.getBlock() == null) return; + Player player = event.getPlayer(); + if(!this.plugin.getStaffManager().isPlayerInStaffMode(player)) return; + if(event.getBlock().getType() == Material.BEDROCK) { + event.setCancelled(true); + player.sendMessage(CC.translate(StaffPlugin.prefix + "&cDon't break bedrock dickhead...")); + } + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerQuitListener.java b/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerQuitListener.java new file mode 100644 index 0000000..08e5abe --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/listeners/PlayerQuitListener.java @@ -0,0 +1,29 @@ +package net.crankedpvp.staff.listeners; + +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class PlayerQuitListener implements Listener { + + private final StaffPlugin plugin; + public PlayerQuitListener(StaffPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void playerQuit(PlayerQuitEvent event) { + if(event.getPlayer() == null) return; + if(!this.plugin.getStaffManager().isPlayerInStaffMode(event.getPlayer())) return; + this.plugin.getStaffManager().getStaffModeFromPlayer(event.getPlayer()).removePlayerFromStaffMode(); + } + + @EventHandler + public void playerKick(PlayerKickEvent event) { + if(event.getPlayer() == null) return; + if(!this.plugin.getStaffManager().isPlayerInStaffMode(event.getPlayer())) return; + this.plugin.getStaffManager().getStaffModeFromPlayer(event.getPlayer()).removePlayerFromStaffMode(); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/listeners/RandomTeleportListener.java b/Staff/src/main/java/net/crankedpvp/staff/listeners/RandomTeleportListener.java new file mode 100644 index 0000000..353122a --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/listeners/RandomTeleportListener.java @@ -0,0 +1,192 @@ +package net.crankedpvp.staff.listeners; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +public class RandomTeleportListener implements Listener { + + private final static List PLAYERS = Arrays.asList( + "Haru_s", + "Xx_Madr1", + "Charo", + "jestq", + "Aywi", + "1eyn", + "Clafory", + "babiw", + "Eniva", + "Hushpuppyzac", + "niaT_T", + "Keybinded", + "RIPMONARCHY", + "Encapsulated", + "Fuddruckers", + "huric4ne", + "revclts", + "sohv", + "breadmoists", + "IMakeSkins", + "PhaserPaul", + "7kya", + "Kosted", + "scoa", + "waiferthin", + "DarthVaderJonah", + "poisonz", + "aretist", + "bracken", + "brackert", + "dogtamer", + "balader", + "koining", + "plezz", + "doglover1", + "apesh1t", + "sistertoucher", + "ravagedpvp", + "slennn", + "qrack", + "tantra", + "juicyass", + "mwkd", + "meong", + "fatest", + "fpsproblems", + "thebetterpvper", + "ohzesmypet", + "revclts", + "xeyshh", + "_Caramelii", + "ASUSRTX2080Ti", + "SussyShare", + "TxFo", + "Mzhy", + "CosmiKazie", + "Aloriie", + "Hurrache", + "oAnxiety", + "Bearz_z", + "xxpz", + "Clyne", + "iRafaNove", + "bbito", + "intercaetera", + "babiw", + "WhyYouReadThis", + "Coucher", + "TheWatcherr", + "Relohd", + "tomarto", + "Blocklist", + "dumme0504", + "Aestheitc", + "babiw", + "Clafory", + "CraLey", + "1eyn", + "hwurt", + "Eniva", + "tomazzzekt", + "PeteParker", + "iDqxha_", + "Dehu", + "toxci", + "FULLSENDVINCENT", + "MissEurope", + "SebTheRandomOne", + "babiw", + "snve", + "Miilyh__", + "Genesong", + "Th3K1ng_", + "ChristmasJonas", + "GiackyB", + "wod1s", + "WhyYouReadThis", + "Fuddruckers", + "huric4ne", + "revclts", + "breadmoists", + "IMakeSkins", + "PhaserPaul", + "7kya", + "Kosted", + "scoa", + "waiferthin", + "DarthVaderJonah", + "revclts", + "xeyshh", + "_Caramelii", + "CosmiKazie", + "Aloriie", + "Hurrache", + "oAnxiety", + "Bearz_z", + "xxpz", + "Clyne", + "iRafaNove", + "bbito", + "intercaetera", + "babiw", + "WhyYouReadThis", + "Blocklist", + "dumme0504", + "Aestheitc", + "babiw", + "Clafory", + "CraLey", + "1eyn", + "hwurt", + "Eniva" + + + ); + + private final Map> playerListMap; + + + private final StaffPlugin plugin; + public RandomTeleportListener(StaffPlugin plugin) { + this.plugin = plugin; + this.playerListMap = new HashMap<>(); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void randomTeleport(PlayerInteractEvent event) { + if(event.getItem() == null || event.getItem().getType() == Material.AIR) return; + + ItemStack itemStack = event.getItem(); + NBTItem nbtItem = new NBTItem(itemStack); + Player player = event.getPlayer(); + if(!nbtItem.getString("staffModeItem").equals("randomPlayerSelector")) return; + if(!this.plugin.getStaffManager().isPlayerInStaffMode(player)) return; + event.setCancelled(true); + + List possibleSelectedPlayers = player.getWorld().getPlayers() + .stream() + .filter(Objects::nonNull) + .filter(Player::isOnline) + //.filter(possiblePlayer -> !PLAYERS.contains(possiblePlayer.getName())) + //.filter(loopPlayer -> WorldGuardUtils.canPvPInRegion(player)) + .collect(Collectors.toList()); + possibleSelectedPlayers.removeIf(checkPlayer -> PLAYERS.contains(checkPlayer.getName())); + Player selectedPlayer = possibleSelectedPlayers.get(ThreadLocalRandom.current().nextInt(possibleSelectedPlayers.size())); + player.teleport(selectedPlayer, PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.sendMessage(CC.translate(StaffPlugin.prefix + "&eYou have been teleported to &6" + selectedPlayer.getName())); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1.0f, 1.0f); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/listeners/StaffJoinListener.java b/Staff/src/main/java/net/crankedpvp/staff/listeners/StaffJoinListener.java new file mode 100644 index 0000000..ea452fc --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/listeners/StaffJoinListener.java @@ -0,0 +1,38 @@ +package net.crankedpvp.staff.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.util.stream.Collectors; + +public class StaffJoinListener implements Listener { + + private final StaffPlugin staffPlugin; + public StaffJoinListener(StaffPlugin plugin) { + this.staffPlugin = plugin; + } + + @EventHandler + public void staffPlayerJoin(PlayerJoinEvent event) { + if(event.getPlayer() == null) return; + if(!event.getPlayer().hasPermission("cranked.staff")) return; + if(event.getPlayer().hasPermission("cranked.admin")) return; + this.staffPlugin.getServer().getOnlinePlayers().stream().filter(player -> player.hasPermission("cranked.staff")).collect(Collectors.toList()).forEach(player -> { + player.sendMessage(CC.translate("&5[Staff] &a+" + event.getPlayer().getName())); + }); + } + + @EventHandler + public void staffLeaveJoin(PlayerQuitEvent event) { + if(event.getPlayer() == null) return; + if(!event.getPlayer().hasPermission("cranked.staff")) return; + if(event.getPlayer().hasPermission("cranked.admin")) return; + this.staffPlugin.getServer().getOnlinePlayers().stream().filter(player -> player.hasPermission("cranked.staff")).collect(Collectors.toList()).forEach(player -> { + player.sendMessage(CC.translate("&5[Staff] &c-" + event.getPlayer().getName())); + }); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/listeners/VanishToggleListener.java b/Staff/src/main/java/net/crankedpvp/staff/listeners/VanishToggleListener.java new file mode 100644 index 0000000..1c85508 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/listeners/VanishToggleListener.java @@ -0,0 +1,37 @@ +package net.crankedpvp.staff.listeners; + +import com.earth2me.essentials.User; +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.EssentialsUtils; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +public class VanishToggleListener implements Listener { + + private final StaffPlugin plugin; + public VanishToggleListener(StaffPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void toggleVanish(PlayerInteractEvent event) { + if(event.getItem() == null || event.getItem().getType() == Material.AIR) return; + + ItemStack itemStack = event.getItem(); + NBTItem nbtItem = new NBTItem(itemStack); + Player player = event.getPlayer(); + if(!nbtItem.getString("staffModeItem").equals("vanish")) return; + if(!this.plugin.getStaffManager().isPlayerInStaffMode(player)) return; + event.setCancelled(true); + User user = EssentialsUtils.getEssentials().getUser(player); + user.setVanished(!user.isVanished()); + String toggleString = user.isVanished() ? "&a&lON" : "&c&lOFF"; + player.sendMessage(CC.translate(StaffPlugin.prefix + "&eYou have toggled vanish " + toggleString + " &ewith staff mode")); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/managers/FreezeManager.java b/Staff/src/main/java/net/crankedpvp/staff/managers/FreezeManager.java new file mode 100644 index 0000000..a6aa97a --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/managers/FreezeManager.java @@ -0,0 +1,20 @@ +package net.crankedpvp.staff.managers; + +import lombok.Getter; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.HashMap; +import java.util.Map; + +public class FreezeManager { + + private StaffPlugin plugin; + public FreezeManager(StaffPlugin plugin) { + this.plugin = plugin; + } + + @Getter + private Map frozenPlayers = new HashMap<>(); +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/managers/GhostMuteManager.java b/Staff/src/main/java/net/crankedpvp/staff/managers/GhostMuteManager.java new file mode 100644 index 0000000..38459b7 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/managers/GhostMuteManager.java @@ -0,0 +1,81 @@ +package net.crankedpvp.staff.managers; + +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class GhostMuteManager { + + private final List ghostMuted; + + private final StaffPlugin plugin; + public GhostMuteManager(StaffPlugin plugin) { + this.plugin = plugin; + this.ghostMuted = new ArrayList<>(); + } + + public void addPlayerToGhostMute(Player player) { + if(ghostMuted.contains(player)) return; + ghostMuted.add(player); + } + + public void addPlayerToGhostMuteFor(Player player, double ms) { + if(ghostMuted.contains(player)) return; + ghostMuted.add(player); + removeAfterTime(player, ms); + } + + public void addPlayerToGhostMuteFor(Player player, String time) { + if(ghostMuted.contains(player)) return; + ghostMuted.add(player); + removeAfterTime(player, getTimeInMs(time)); + } + + private void removeAfterTime(Player player, double ms) { + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> this.removePlayerFromGhostMute(player), (long)ms / 50); + } + + public void removePlayerFromGhostMute(Player player) { + if(!ghostMuted.contains(player)) return; + ghostMuted.remove(player); + } + + public boolean isPlayerInGhostMute(Player player) { + return ghostMuted.contains(player); + } + + public long getTimeInMs(String timeString) { + long multiplier; + long milliseconds; + + char unit = timeString.charAt(timeString.length() - 1); + String numberString = timeString.substring(0, timeString.length() - 1); + + long number = Long.parseLong(numberString); + + switch (unit) { + case 's': + multiplier = 1000L; // 1 second = 1000 milliseconds + break; + case 'm': + multiplier = 60000L; // 1 minute = 60000 milliseconds + break; + case 'h': + multiplier = 3600000L; // 1 hour = 3600000 milliseconds + break; + case 'd': + multiplier = 86400000L; // 1 day = 86400000 milliseconds + break; + default: + throw new IllegalArgumentException("Invalid time unit: " + unit); + } + + milliseconds = number * multiplier; + return milliseconds; + } + + + +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/managers/ReportManager.java b/Staff/src/main/java/net/crankedpvp/staff/managers/ReportManager.java new file mode 100644 index 0000000..991bc0d --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/managers/ReportManager.java @@ -0,0 +1,30 @@ +package net.crankedpvp.staff.managers; + +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.struct.Report; +import net.crankedpvp.storageutils.StorageUtils; +import net.crankedpvp.storageutils.struct.NewSaveLoadManager; +import org.bukkit.entity.Player; + +import java.util.UUID; + +public class ReportManager extends NewSaveLoadManager { + + public ReportManager(StaffPlugin plugin) { + super(plugin, StorageUtils.getInstance().getGson(), "reports", Report.class); + } + + public void createReport(Player reporter, Player reported, String reason) { + super.addToCache(new Report(reporter, reported, reason)); + } + + @Override + public String serialize(UUID uuid) { + return uuid.toString(); + } + + @Override + public UUID deserialize(String s) { + return UUID.fromString(s); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/managers/StaffManager.java b/Staff/src/main/java/net/crankedpvp/staff/managers/StaffManager.java new file mode 100644 index 0000000..1817f80 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/managers/StaffManager.java @@ -0,0 +1,37 @@ +package net.crankedpvp.staff.managers; + +import com.google.common.collect.Maps; +import lombok.Getter; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.struct.StaffMode; +import org.bukkit.entity.Player; + +import java.util.Map; + +public class StaffManager { + + private final StaffPlugin plugin; + public StaffManager(StaffPlugin plugin) { + this.plugin = plugin; + this.playersInStaffMode = Maps.newConcurrentMap(); + } + + @Getter + private final Map playersInStaffMode; + + public StaffMode getStaffModeFromPlayer(Player player) { + return this.playersInStaffMode.get(player); + } + + public boolean isPlayerInStaffMode(Player player) { + return playersInStaffMode.containsKey(player); + } + + public void removePlayerFromStaffMode(Player player) { + this.playersInStaffMode.remove(player); + } + + public void putPlayerInStaffMode(Player player, StaffMode staffMode) { + this.playersInStaffMode.put(player, staffMode); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/struct/Report.java b/Staff/src/main/java/net/crankedpvp/staff/struct/Report.java new file mode 100644 index 0000000..7e204f7 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/struct/Report.java @@ -0,0 +1,40 @@ +package net.crankedpvp.staff.struct; + +import lombok.Getter; +import lombok.Setter; +import net.crankedpvp.storageutils.struct.NewKeyToSave; +import org.bukkit.entity.Player; + +import java.time.LocalDateTime; +import java.util.UUID; + +@Getter +@Setter +public class Report implements NewKeyToSave { + + private UUID ReportID; + private String reason; + private UUID reporter; + private UUID reported; + private LocalDateTime dateTimeOfReport; + + public Report(Player reporter, Player reported, String reason) { + this.reporter = reporter.getUniqueId(); + this.reported = reported.getUniqueId(); + this.reason = reason; + + this.dateTimeOfReport = LocalDateTime.now(); + this.ReportID = UUID.randomUUID(); + } + + + @Override + public UUID getKey() { + return this.ReportID; + } + + @Override + public void setKey(UUID uuid) { + this.ReportID = uuid; + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/struct/ReportCooldown.java b/Staff/src/main/java/net/crankedpvp/staff/struct/ReportCooldown.java new file mode 100644 index 0000000..56f7fc7 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/struct/ReportCooldown.java @@ -0,0 +1,10 @@ +package net.crankedpvp.staff.struct; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class ReportCooldown extends CurrentCooldown { + + public ReportCooldown() { + super("report_cooldown", 60); + } +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/struct/StaffMode.java b/Staff/src/main/java/net/crankedpvp/staff/struct/StaffMode.java new file mode 100644 index 0000000..3654af4 --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/struct/StaffMode.java @@ -0,0 +1,72 @@ +package net.crankedpvp.staff.struct; + +import de.tr7zw.nbtapi.NBTItem; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerInventoryContents; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.staff.StaffPlugin; +import net.crankedpvp.staff.managers.StaffManager; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class StaffMode { + + private final Player player; + private final StaffManager staffManager; + private final PlayerInventoryContents playerInventoryContents; + + public StaffMode(Player player) { + this.player = player; + this.staffManager = StaffPlugin.getInstance().getStaffManager(); + this.playerInventoryContents = new PlayerInventoryContents(player.getInventory().getContents(), player.getInventory().getArmorContents()); + } + + public void putPlayerInStaffMode() { + this.staffManager.putPlayerInStaffMode(this.player, this); + this.player.sendMessage(CC.translate(StaffPlugin.prefix + "&eYou have entered staff mode")); + this.player.playSound(this.player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + this.completelyClearPlayersInventory(); + this.player.setGameMode(GameMode.CREATIVE); + this.addRandomPlayerSelector(); + this.addVanish(); + } + + public void removePlayerFromStaffMode() { + this.player.sendMessage(CC.translate(StaffPlugin.prefix + "&eYou have left staff mode")); + this.player.playSound(this.player.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 2.0F); + this.staffManager.removePlayerFromStaffMode(this.player); + this.player.setGameMode(GameMode.SURVIVAL); + this.reinstateInventory(); + } + + private void reinstateInventory() { + this.playerInventoryContents.restore(this.player); + } + + private void addRandomPlayerSelector() { + ItemBuilder itemBuilder = new ItemBuilder(Material.COMPASS, "&a&lRandom Player Teleporter", + "&7Right-Click this compass to teleport to", + "&7a random player outside of the safezone"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("staffModeItem", "randomPlayerSelector"); + this.player.getInventory().setItem(4, nbtItem.getItem()); + } + + private void addVanish() { + ItemBuilder itemBuilder = new ItemBuilder(Material.FEATHER, "&b&lVanish", + "&7Right-Click this to become invisible", + "&7to regular players"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("staffModeItem", "vanish"); + this.player.getInventory().setItem(0, nbtItem.getItem()); + } + + private void completelyClearPlayersInventory() { + this.player.getInventory().setArmorContents(new ItemStack[4]); + this.player.getInventory().clear(); + } + +} diff --git a/Staff/src/main/java/net/crankedpvp/staff/tasks/FreezeTeleportTask.java b/Staff/src/main/java/net/crankedpvp/staff/tasks/FreezeTeleportTask.java new file mode 100644 index 0000000..108fb1e --- /dev/null +++ b/Staff/src/main/java/net/crankedpvp/staff/tasks/FreezeTeleportTask.java @@ -0,0 +1,34 @@ +package net.crankedpvp.staff.tasks; + +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.staff.StaffPlugin; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Map; + +public class FreezeTeleportTask extends BukkitRunnable { + + private final StaffPlugin plugin; + public FreezeTeleportTask(StaffPlugin plugin) { + this.plugin = plugin; + } + + @Override + public void run() { + for(Map.Entry playerLocationEntry : this.plugin.getFreezeManager().getFrozenPlayers().entrySet()) { + Player player = playerLocationEntry.getKey(); + Location location = playerLocationEntry.getValue(); + if(!player.getLocation().equals(location)) { + player.sendMessage(CC.translate("&b&lFreeze &8" + Arrow.arrow() + "&7Do not logout while you are frozen")); + player.playSound(player.getLocation(), Sound.NOTE_BASS_DRUM, 2.0f, 2.0f); + } + player.teleport(location, PlayerTeleportEvent.TeleportCause.UNKNOWN); + } + } + +} diff --git a/Staff/src/main/resources/plugin.yml b/Staff/src/main/resources/plugin.yml new file mode 100644 index 0000000..dfb4c2e --- /dev/null +++ b/Staff/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedStaff +main: net.crankedpvp.staff.StaffPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/StarItems/pom.xml b/StarItems/pom.xml new file mode 100644 index 0000000..8c572b3 --- /dev/null +++ b/StarItems/pom.xml @@ -0,0 +1,59 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + StarItems + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + com.massivecraft + Factions + + + net.crankedpvp + Armor + + + net.crankedpvp + Masks + + + net.crankedpvp + Leaderboards + + + com.comphenix.protocol + ProtocolLib + + + com.golfing.wineSpigot + winespigot + 1.0 + system + ${project.basedir}/../.lib/WineSpigot-V1.7.4.2.jar + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + \ No newline at end of file diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/StarItemsAPI.java b/StarItems/src/main/java/net/crankedpvp/staritems/StarItemsAPI.java new file mode 100644 index 0000000..72da349 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/StarItemsAPI.java @@ -0,0 +1,201 @@ +package net.crankedpvp.staritems; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import dev.triumphteam.gui.guis.GuiItem; +import net.crankedpvp.crankedutils.utils.HookUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.staritems.inventory.StarItemsInventory; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class StarItemsAPI { + + public static final ItemStack starItemExtractor = buildStarItemExtractor(); + + private static ItemStack buildStarItemExtractor() { + ItemBuilder itemBuilder = new ItemBuilder(Material.FEATHER, "&6&lStar Item Extractor", + "&7Drag n Drop onto an item that", + "&7has a star item equipped to", + "&7remove the star item from it"); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "starItemExtractor"); + return nbtItem.getItem(); + } + + public static boolean playerHasStarItemEquipped(Player player) { + return Objects.requireNonNull(getPlayersEquippedStarItems(player)).size() > 0; + } + + public static List getPlayersEquippedStarItems(Player player) { + List starItems = new ArrayList<>(); + for(ItemStack armorContent : player.getInventory().getArmorContents()) { + if(!itemHasStarItemEquipped(armorContent)) continue; + if(isFounderStar(armorContent)) { + return new ArrayList<>(StarItemsPlugin.getInstance().getStarItemManager().getStarItems()); + } + starItems.add(getEquippedStarItem(armorContent)); + } + return starItems; + } + + private static boolean isFounderStar(ItemStack itemStack) { + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + return nbtItem.getString("starItem").equals("founderStar"); + } + + public static StarItem getEquippedStarItem(ItemStack itemStack) { + if(!itemHasStarItemEquipped(itemStack)) return null; + NBTItem nbtItem = new NBTItem(itemStack); + return StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID(nbtItem.getString("starItem")); + } + + public static boolean itemHasStarItemEquipped(ItemStack itemStack) { + if(itemStack == null || itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + return nbtItem.hasKey("starItem"); + } + + public static boolean isStarItem(ItemStack itemStack) { + if(itemStack == null) return false; + if(itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + if(!nbtItem.hasKey("cosmicType")) return false; + if(!nbtItem.getString("cosmicType").equals("staritem")) return false; + NBTCompound nbtCompound = nbtItem.getCompound("cosmicData"); + if(nbtCompound == null) return false; + if(!StarItemsPlugin.getInstance().getStarItemManager().isStarItem(nbtCompound.getString("starItemType"))) return false; + StarItem starItem = StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID(nbtCompound.getString("starItemType")); + return starItem != null; + } + + public static StarItem getStarItemFromItemStack(ItemStack itemStack) { + if(!isStarItem(itemStack)) return null; + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound nbtCompound = nbtItem.getCompound("cosmicData"); + if(nbtCompound == null) return null; + if(!StarItemsPlugin.getInstance().getStarItemManager().isStarItem(nbtCompound.getString("starItemType"))) return null; + return StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID(nbtCompound.getString("starItemType")); + } + + public static void refreshStarItemForPlayer(Player player) { + if(!playerHasStarItemEquipped(player)) { + StarItemsPlugin.getInstance().getStarItemManager().removeFromCacheCompletely(player); + return; + } + List starItems = getPlayersEquippedStarItems(player); + StarItemsPlugin.getInstance().getStarItemManager().addToCache(player, starItems); + } + + public static List getStarItemFromCache(Player player) { + Map> cachedPlayers = StarItemsPlugin.getInstance().getStarItemManager().getCachedPlayers(); + if(!cachedPlayers.containsKey(player)) return new ArrayList<>(); + return cachedPlayers.get(player); + } + + public static boolean playerHasStarItemInCache(Player player) { + return StarItemsPlugin.getInstance().getStarItemManager().getCachedPlayers().containsKey(player); + } + + public static boolean playerHasStarItem(Player player, StarItem starItem) { + if(!playerHasStarItemInCache(player)) return false; + return getStarItemFromCache(player).contains(starItem); + } + + public static boolean playerHasStarItem(Player player, String starItemString) { + StarItem starItem = StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID(starItemString); + if(starItem == null) return false; + if(!playerHasStarItem(player, starItem)) return false; + return getStarItemFromCache(player).contains(starItem); + } + + public static boolean isStarItemExtractor(ItemStack itemStack) { + if(itemStack == null) return false; + if(itemStack.getType() == Material.AIR) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasNBTData()) return false; + return nbtItem.getString("crankedCustomItem").equals("starItemExtractor"); + } + + public static ItemStack buildGoldenKnife() { + ItemBuilder itemBuilder = new ItemBuilder(Material.GOLD_SWORD); + itemBuilder.setDurability((short) 31); + itemBuilder.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 1000); + itemBuilder.setName("&8» &6&lThe Golden Knife &8«"); + itemBuilder.setLore( + "", + "&fVanquish the soul of anything that", + "&fyou strike, in a fair exchange for", + "&fthis divine blade.", + "", + "&7&oThis item is Unrepairable" + ); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "goldenKnife"); + return nbtItem.getItem(); + } + + public static ItemStack buildHook() { + ItemBuilder itemBuilder = new ItemBuilder(Material.DIAMOND_HOE, "&8» &b&lThe Diamond Hook &8«"); + itemBuilder.addEnchantment(Enchantment.DAMAGE_ALL, 5); + itemBuilder.addEnchantment(Enchantment.DURABILITY, 3); + return HookUtils.applyHookData(itemBuilder.colorize().build()); + } + + public static boolean isGoldenKnife(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasKey("crankedCustomItem")) return false; + return nbtItem.getString("crankedCustomItem").equals("goldenKnife"); + } + + public static boolean isDeathNote(ItemStack itemStack) { + if(ItemUtils.isAirOrNull(itemStack)) return false; + NBTItem nbtItem = new NBTItem(itemStack); + if(!nbtItem.hasKey("crankedCustomItem")) return false; + return nbtItem.getString("crankedCustomItem").equals("deathNote"); + } + + public static void addItemToStarItemsUI(ItemStack itemStack) { + StarItemsPlugin.getInstance().getStarItemsInventory().getUI().addItem(new GuiItem(itemStack, event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) { + event.getWhoClicked().getInventory().addItem(event.getCurrentItem().clone()); + } + })); + } + + public static StarItemsInventory getStarItemsUI() { + return StarItemsPlugin.getInstance().getStarItemsInventory(); + } + + + public static ItemStack buildDeathNote() { + ItemBuilder itemBuilder = new ItemBuilder(Material.PAPER); + itemBuilder.setName("&8» &8&lDeath Note &8«"); + itemBuilder.setLore( + "", + "&7One death granted from the shingami world.", + "", + "&fChoose the player you wish to", + "&fvanquish by typing their name", + "&fafter using this divine note.", + "", + "&7&oThis item has ONE use." + ); + NBTItem nbtItem = new NBTItem(itemBuilder.colorize().build()); + nbtItem.setString("crankedCustomItem", "deathNote"); + return nbtItem.getItem(); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/StarItemsPlugin.java b/StarItems/src/main/java/net/crankedpvp/staritems/StarItemsPlugin.java new file mode 100644 index 0000000..524dc81 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/StarItemsPlugin.java @@ -0,0 +1,91 @@ +package net.crankedpvp.staritems; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import me.mattstudios.mf.base.components.TypeResult; +import net.crankedpvp.staritems.abilities.IceTrapAbility; +import net.crankedpvp.staritems.commands.*; +import net.crankedpvp.staritems.inventory.StarItemsInventory; +import net.crankedpvp.staritems.listeners.*; +import net.crankedpvp.staritems.struct.StarItem; +import net.crankedpvp.staritems.struct.StarItemManager; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Arrays; +import java.util.stream.Collectors; + +public class StarItemsPlugin extends JavaPlugin { + + @Getter + private static StarItemsPlugin instance; + + public static String prefix = "&d&lStar Items &8➥ "; + + @Getter + private StarItemManager starItemManager; + @Getter + private CommandManager commandManager; + + @Getter + private IceTrapAbility iceTrapAbility; + + @Getter + private StarItemsInventory starItemsInventory; + + @Override + public void onEnable() { + instance = this; + this.starItemManager = new StarItemManager(this); + this.starItemManager.initialize(); + this.commandManager = new CommandManager(this); + this.registerCommandCompletion(); + this.registerCommandParameters(); + this.commandManager.register(new DeathNoteCommand(this), new StarItemsAdminCommand(this), new StarItemsCommand(this), new GoldenKnifeCommand(this), new GoldenKnifeInventoryViewCommand()); + this.registerListeners(); + + /* + new ChromaPacketTask(this).runTaskTimer(this, 20L, 20L); + new PrismaPacketTask(this).runTaskTimer(this, 20L, 20L); + new FounderStarPacketTask(this).runTaskTimer(this, 20L, 20L); + new RainbowArmorTask().runTaskTimer(this, 2L, 20L); + + */ + + this.iceTrapAbility = new IceTrapAbility(this); + + this.starItemsInventory = new StarItemsInventory(); + StarItemsAPI.addItemToStarItemsUI(StarItemsAPI.buildGoldenKnife()); + //StarItemsAPI.addItemToStarItemsUI(StarItemsAPI.buildHook()); + } + + @Override + public void onDisable() { + + } + + private void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new PlayerListener(this), this); + pluginManager.registerEvents(new ApplyStarItemListener(this), this); + pluginManager.registerEvents(new PotionAddListener(), this); + pluginManager.registerEvents(new ApplyStarItemExtractorListener(this), this); + pluginManager.registerEvents(new PacketListeners(this), this); + pluginManager.registerEvents(new GoldenKnifeListener(), this); + pluginManager.registerEvents(new DeathNoteListener(this), this); + } + + + private void registerCommandParameters() { + this.commandManager.getParameterHandler().register(StarItem.class, argument -> { + StarItem armorSet = this.starItemManager.getStarItemFromID(this.starItemManager.getStarItemIDFromName(String.valueOf(argument))); + return new TypeResult(armorSet, argument); + }); + } + + private void registerCommandCompletion() { + this.commandManager.getCompletionHandler().register("#staritems", input -> this.starItemManager.getStarItems().stream().map(StarItem::getID).collect(Collectors.toList())); + this.commandManager.getCompletionHandler().register("#boolean", input -> Arrays.asList("true", "false")); + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/abilities/IceTrapAbility.java b/StarItems/src/main/java/net/crankedpvp/staritems/abilities/IceTrapAbility.java new file mode 100644 index 0000000..ec435f8 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/abilities/IceTrapAbility.java @@ -0,0 +1,67 @@ +package net.crankedpvp.staritems.abilities; + +import com.google.common.collect.Maps; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.staritems.StarItemsPlugin; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; + +import java.util.Map; + +public class IceTrapAbility { + + private final static int ABILITY_DURATION = 4; + + private final Map playersAffected; + + private final StarItemsPlugin plugin; + public IceTrapAbility(StarItemsPlugin plugin) { + this.plugin = plugin; + this.playersAffected = Maps.newConcurrentMap(); + } + + public void procAbility(Player sender, Player affected) { + this.procAbility(sender, affected, "&bFrostbite"); + } + + public void procAbility(Player sender, Player affected, String reason) { + PlayerUtils.teleportPlayerToClosestLocation(affected); + this.setSurroundingBlocksToIce(affected); + for(Player nearbyPlayer : PlayerUtils.getNearbyPlayers(affected, 10)) { + nearbyPlayer.sendMessage(CC.translate("&6&lStar Items &8" + Arrow.arrow() + " " + reason + " &7has been activated by &c" + sender.getName() + "&7!")); + } + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> this.finishAbility(affected), ABILITY_DURATION * 20L); + } + + public void finishAbility(Player affected) { + this.setSurroundingBlocksToAir(affected); + affected.sendMessage(CC.translate("&6&lStar Items &8" + Arrow.arrow() + " &7You are no longer affected by the &bFrostbite &7ability")); + } + + public void setSurroundingBlocksToAir(Player player) { + Location eyeLoc = this.playersAffected.get(player); + this.playersAffected.remove(player); + Block block = eyeLoc.getBlock(); + if(block.getRelative(BlockFace.NORTH).getType() == Material.ICE) block.getRelative(BlockFace.NORTH).setType(Material.AIR); + if(block.getRelative(BlockFace.EAST).getType() == Material.ICE) block.getRelative(BlockFace.EAST).setType(Material.AIR); + if(block.getRelative(BlockFace.SOUTH).getType() == Material.ICE) block.getRelative(BlockFace.SOUTH).setType(Material.AIR); + if(block.getRelative(BlockFace.WEST).getType() == Material.ICE) block.getRelative(BlockFace.WEST).setType(Material.AIR); + if(block.getRelative(BlockFace.UP).getType() == Material.ICE) block.getRelative(BlockFace.UP).setType(Material.AIR); + } + + public void setSurroundingBlocksToIce(Player player) { + Location eyeLoc = player.getEyeLocation(); + this.playersAffected.put(player, eyeLoc); + Block block = eyeLoc.getBlock(); + if(block.getRelative(BlockFace.NORTH).getType() == Material.AIR) block.getRelative(BlockFace.NORTH).setType(Material.ICE); + if(block.getRelative(BlockFace.EAST).getType() == Material.AIR) block.getRelative(BlockFace.EAST).setType(Material.ICE); + if(block.getRelative(BlockFace.SOUTH).getType() == Material.AIR) block.getRelative(BlockFace.SOUTH).setType(Material.ICE); + if(block.getRelative(BlockFace.WEST).getType() == Material.AIR) block.getRelative(BlockFace.WEST).setType(Material.ICE); + if(block.getRelative(BlockFace.UP).getType() == Material.AIR) block.getRelative(BlockFace.UP).setType(Material.ICE); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/commands/DeathNoteCommand.java b/StarItems/src/main/java/net/crankedpvp/staritems/commands/DeathNoteCommand.java new file mode 100644 index 0000000..4dcecf8 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/commands/DeathNoteCommand.java @@ -0,0 +1,36 @@ +package net.crankedpvp.staritems.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("deathnote") +@Alias("dnote") +public class DeathNoteCommand extends CommandBase { + + private StarItemsPlugin plugin; + public DeathNoteCommand(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + @Default + @Permission("cranked.admin") + public void defaultCommand(final CommandSender commandSender, @Optional @Completion("#players") Player receiver) { + if(receiver == null && commandSender instanceof Player) { + receiver = (Player) commandSender; + } + assert receiver != null; + receiver.getInventory().addItem(StarItemsAPI.buildDeathNote()); + receiver.sendMessage(CC.translate("&6&lStar Items &8" + Arrow.arrow() + " &7You have received the &4&lDeath Note")); + receiver.playSound(receiver.getLocation(), Sound.CHICKEN_EGG_POP, 2.0f, 2.0f); + } + + + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/commands/GoldenKnifeCommand.java b/StarItems/src/main/java/net/crankedpvp/staritems/commands/GoldenKnifeCommand.java new file mode 100644 index 0000000..5222244 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/commands/GoldenKnifeCommand.java @@ -0,0 +1,36 @@ +package net.crankedpvp.staritems.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("goldenknife") +@Alias("gknife") +public class GoldenKnifeCommand extends CommandBase { + + private StarItemsPlugin plugin; + public GoldenKnifeCommand(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + @Default + @Permission("cranked.admin") + public void defaultCommand(final CommandSender commandSender, @Optional @Completion("#players") Player receiver) { + if(receiver == null && commandSender instanceof Player) { + receiver = (Player) commandSender; + } + assert receiver != null; + receiver.getInventory().addItem(StarItemsAPI.buildGoldenKnife()); + receiver.sendMessage(CC.translate("&6&lStar Items &8" + Arrow.arrow() + " &7You have received the &6&lGolden Knife")); + receiver.playSound(receiver.getLocation(), Sound.CHICKEN_EGG_POP, 2.0f, 2.0f); + } + + + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/commands/GoldenKnifeInventoryViewCommand.java b/StarItems/src/main/java/net/crankedpvp/staritems/commands/GoldenKnifeInventoryViewCommand.java new file mode 100644 index 0000000..a4ff7cc --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/commands/GoldenKnifeInventoryViewCommand.java @@ -0,0 +1,21 @@ +package net.crankedpvp.staritems.commands; + +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.staritems.listeners.GoldenKnifeListener; +import org.bukkit.entity.Player; + +import java.util.UUID; + +@Command("goldenknifedeathinventoryview") +public class GoldenKnifeInventoryViewCommand extends CommandBase { + + @Default + public void openInventory(final Player sender, String uuid) { + UUID playerUUID = UUID.fromString(uuid); + if(!GoldenKnifeListener.inventories.containsKey(playerUUID)) return; + GoldenKnifeListener.inventories.get(playerUUID).getGui().open(sender); + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/commands/StarItemsAdminCommand.java b/StarItems/src/main/java/net/crankedpvp/staritems/commands/StarItemsAdminCommand.java new file mode 100644 index 0000000..f61197c --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/commands/StarItemsAdminCommand.java @@ -0,0 +1,89 @@ +package net.crankedpvp.staritems.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.PlayerUtils; +import net.crankedpvp.crankedutils.utils.SoundUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Command("csi") +@Alias("crankedstaritems") +public class StarItemsAdminCommand extends CommandBase { + + private StarItemsPlugin plugin; + public StarItemsAdminCommand(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + @Default + @Permission("cranked.admin") + public void defaultCommand(final CommandSender commandSender) { + sendHelp(commandSender); + } + + @SubCommand("help") + @Permission("cranked.admin") + public void helpCommand(final CommandSender commandSender) { + sendHelp(commandSender); + } + + @SubCommand("give") + @Permission("cranked.admin") + public void giveCommand(final CommandSender commandSender, @Completion("#staritems") String staritem, @Optional @Completion("#players") Player player) { + if(player == null) { + if(!(commandSender instanceof Player)) { + commandSender.sendMessage(CC.translate("&cUsage: /csi give [player]")); + return; + } + player = (Player)commandSender; + } + + if(!this.plugin.getStarItemManager().isStarItem(staritem)) { + commandSender.sendMessage(CC.translate(StarItemsPlugin.prefix + "&cThis is not a registered star item")); + SoundUtils.tryPlayErrorSound(commandSender); + return; + } + + StarItem starItem = this.plugin.getStarItemManager().getStarItemFromID(staritem); + PlayerUtils.giveOrDropProtectedItem(player, starItem.buildItem(), 15); + player.sendMessage(CC.translate(StarItemsPlugin.prefix + "&aYou have received a " + starItem.getDisplayName() + " &afrom " + commandSender.getName())); + player.playSound(player.getLocation(), Sound.CHICKEN_EGG_POP, 2.0F, 2.0F); + } + + private void sendHelp(final CommandSender commandSender) { + commandSender.sendMessage(CC.translate("")); + commandSender.sendMessage(CC.translate("&c&lStar Items")); + commandSender.sendMessage(CC.translate("&c* &f/csi give [player]")); + commandSender.sendMessage(CC.translate("&c* &f/csi extractor [player]")); + SoundUtils.playSoundIfPlayer(commandSender, Sound.LAVA_POP); + } + + @SubCommand("debug") + @Permission("cranked.admin") + public void debugCommand(final CommandSender commandSender, @Optional @Completion("#players") Player player) { + if(player == null) player = (Player) commandSender; + player.updateInventory(); + } + + + @SubCommand("extractor") + @Permission("cranked.admin") + public void extractorCommand(final CommandSender commandSender, @Optional @Completion("#players") Player player) { + if(player == null) { + if(commandSender instanceof Player) { + player = (Player) commandSender; + } else { + commandSender.sendMessage("&cYou must choose a player to give the item to"); + return; + } + } + + player.getInventory().addItem(StarItemsAPI.starItemExtractor); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/commands/StarItemsCommand.java b/StarItems/src/main/java/net/crankedpvp/staritems/commands/StarItemsCommand.java new file mode 100644 index 0000000..ffc0029 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/commands/StarItemsCommand.java @@ -0,0 +1,26 @@ +package net.crankedpvp.staritems.commands; + +import me.mattstudios.mf.annotations.Alias; +import me.mattstudios.mf.annotations.Command; +import me.mattstudios.mf.annotations.Default; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.inventory.StarItemsInventory; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +@Command("staritems") +@Alias("staritem") +public class StarItemsCommand extends CommandBase { + + private StarItemsPlugin plugin; + public StarItemsCommand(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + @Default + public void defaultCommand(final Player player) { + this.plugin.getStarItemsInventory().getUI().open(player); + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/DirtyBombCooldown.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/DirtyBombCooldown.java new file mode 100644 index 0000000..4366de8 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/DirtyBombCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class DirtyBombCooldown extends CurrentCooldown { + public DirtyBombCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/EyeBandageHealCooldown.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/EyeBandageHealCooldown.java new file mode 100644 index 0000000..f240458 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/EyeBandageHealCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class EyeBandageHealCooldown extends CurrentCooldown { + public EyeBandageHealCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/FrostBiteCooldown.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/FrostBiteCooldown.java new file mode 100644 index 0000000..a6d447e --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/FrostBiteCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class FrostBiteCooldown extends CurrentCooldown { + public FrostBiteCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/GloopGetawayCooldown.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/GloopGetawayCooldown.java new file mode 100644 index 0000000..41a7139 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/GloopGetawayCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class GloopGetawayCooldown extends CurrentCooldown { + public GloopGetawayCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/HotPotatoCooldown.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/HotPotatoCooldown.java new file mode 100644 index 0000000..6b1d1d4 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/HotPotatoCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class HotPotatoCooldown extends CurrentCooldown { + public HotPotatoCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/PhoenixAbilityCooldown.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/PhoenixAbilityCooldown.java new file mode 100644 index 0000000..0d7e1bd --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/PhoenixAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class PhoenixAbilityCooldown extends CurrentCooldown { + public PhoenixAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/SantasPieAbility.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/SantasPieAbility.java new file mode 100644 index 0000000..64a7c74 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/SantasPieAbility.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class SantasPieAbility extends CurrentCooldown { + public SantasPieAbility() { + super("santas_beard_pie_eater_ability", 120); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/SantasPresentAbility.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/SantasPresentAbility.java new file mode 100644 index 0000000..df20815 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/SantasPresentAbility.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class SantasPresentAbility extends CurrentCooldown { + public SantasPresentAbility() { + super("santas_beard_present_ability", 20); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/ShackleAbilityCooldown.java b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/ShackleAbilityCooldown.java new file mode 100644 index 0000000..9646f9f --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/cooldowns/ShackleAbilityCooldown.java @@ -0,0 +1,9 @@ +package net.crankedpvp.staritems.cooldowns; + +import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown; + +public class ShackleAbilityCooldown extends CurrentCooldown { + public ShackleAbilityCooldown(String name, int durationInSeconds) { + super(name, durationInSeconds); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/inventory/GoldenKnivedInventory.java b/StarItems/src/main/java/net/crankedpvp/staritems/inventory/GoldenKnivedInventory.java new file mode 100644 index 0000000..a284991 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/inventory/GoldenKnivedInventory.java @@ -0,0 +1,43 @@ +package net.crankedpvp.staritems.inventory; + +import dev.triumphteam.gui.guis.GuiItem; +import dev.triumphteam.gui.guis.PaginatedGui; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; + +public class GoldenKnivedInventory { + @Getter + private final PaginatedGui gui; + public GoldenKnivedInventory(Player toView) { + this.gui = new PaginatedGui(5, 54, toView.getName() + "'s Inventory"); + this.gui.setDefaultClickAction(event -> event.setCancelled(true)); + ItemStack[] items = toView.getInventory().getContents(); + for (int i = 0; i < 36; i++) { + if (items[i] != null) + gui.setItem(i, new GuiItem(items[i])); + } + gui.setItem(36, getFillterItem()); + gui.setItem(37, getFillterItem()); + gui.setItem(40, getFillterItem()); + gui.setItem(43, getFillterItem()); + gui.setItem(44, getFillterItem()); + + PlayerInventory oldInv = toView.getInventory(); + if (oldInv.getHelmet() != null) + gui.setItem(38, new GuiItem( oldInv.getHelmet())); + if (oldInv.getChestplate() != null) + gui.setItem(39, new GuiItem(oldInv.getChestplate())); + if (oldInv.getLeggings() != null) + gui.setItem(41, new GuiItem(oldInv.getLeggings())); + if (oldInv.getBoots() != null) + gui.setItem(42, new GuiItem(oldInv.getBoots())); + } + + public GuiItem getFillterItem() { + return new GuiItem(new ItemBuilder(Material.STAINED_GLASS_PANE, 1, (byte)7, "&7 ").colorize().build()); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/inventory/StarItemsInventory.java b/StarItems/src/main/java/net/crankedpvp/staritems/inventory/StarItemsInventory.java new file mode 100644 index 0000000..4c51cd4 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/inventory/StarItemsInventory.java @@ -0,0 +1,72 @@ +package net.crankedpvp.staritems.inventory; + +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.GuiItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.HookUtils; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.Collection; + +public class StarItemsInventory { + + private final Gui starItemsInventory; + + public Gui getUI() { + return this.starItemsInventory; + } + + Collection starItems = StarItemsPlugin.getInstance().getStarItemManager().getStarItems(); + + public StarItemsInventory() { + this.starItemsInventory = new Gui(6, "Cranked Star Items"); + this.starItemsInventory.setDefaultClickAction(event -> event.setCancelled(true)); + this.starItemsInventory.getFiller().fillBorder(new GuiItem(createFillerItem())); + this.starItemsInventory.updateItem(6, 5, new GuiItem(createExitItem(), event -> event.getWhoClicked().closeInventory())); + this.starItemsInventory.updateItem(1, 5, new GuiItem(createInformationItem())); + + for(StarItem starItem : starItems) { + this.starItemsInventory.addItem(new GuiItem(starItem.buildItem(), event -> { + if(event.getWhoClicked().hasPermission("cranked.admin")) event.getWhoClicked().getInventory().addItem(starItem.buildItem()); + })); + } + + } + + private ItemStack createExitItem() { + ItemStack item = new ItemStack(Material.BED); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(CC.translate("&cExit Star Items Menu")); + item.setItemMeta(meta); + return item; + } + + private ItemStack createInformationItem() { + return new ItemBuilder(Material.BOOK, "&d&lStar Items", + "&7Star Items are physical, applyable", + "&7items which exhibit a visual override.", + "", + "&7They can only be applied to", + "&7helmets, however are very powerful." + ) + .colorize().build(); + } + + private ItemStack createFillerItem() { + ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData()); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(" "); + item.setItemMeta(meta); + return item; + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/listeners/ApplyStarItemExtractorListener.java b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/ApplyStarItemExtractorListener.java new file mode 100644 index 0000000..41fdbd9 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/ApplyStarItemExtractorListener.java @@ -0,0 +1,53 @@ +package net.crankedpvp.staritems.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryClickUtils; +import net.crankedpvp.crankedutils.utils.InventoryUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class ApplyStarItemExtractorListener implements Listener { + + private StarItemsPlugin plugin; + public ApplyStarItemExtractorListener(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void inventoryClick(InventoryClickEvent event) { + if(event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR) return; + if(event.getCursor() == null || event.getCursor().getType() == Material.AIR) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + ItemStack cursor = event.getCursor(); + if(!StarItemsAPI.isStarItemExtractor(event.getCursor())) return; + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + StarItem starItem = StarItemsAPI.getEquippedStarItem(event.getCurrentItem()); + Player player = (Player) event.getWhoClicked(); + if(starItem == null) { + player.sendMessage(CC.translate(StarItemsPlugin.prefix + "&cThis item does not have a star item equipped")); + return; + } + if(!InventoryUtils.hasAvaliableSlot(player, 1)) { + player.sendMessage(CC.translate(StarItemsPlugin.prefix + "&cYou do not have enough inventory slots to extract a star item")); + return; + } + event.setCancelled(true); + player.getInventory().addItem(starItem.buildItem()); + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(cursor)); + event.setCurrentItem(starItem.unapply(event.getCurrentItem())); + + player.updateInventory(); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/listeners/ApplyStarItemListener.java b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/ApplyStarItemListener.java new file mode 100644 index 0000000..2e731bf --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/ApplyStarItemListener.java @@ -0,0 +1,60 @@ +package net.crankedpvp.staritems.listeners; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.InventoryClickUtils; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.leaderboards.LeaderboardsAPI; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class ApplyStarItemListener implements Listener { + + private StarItemsPlugin plugin; + public ApplyStarItemListener(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void inventoryClick(InventoryClickEvent event) { + if(event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR) return; + if(event.getCursor() == null || event.getCursor().getType() == Material.AIR) return; + + //if(event.isCancelled()) return; + //if (event.getClickedInventory() != event.getWhoClicked().getInventory()) return; + + ItemStack cursor = event.getCursor(); + if(!StarItemsAPI.isStarItem(cursor)) return; + //if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return; + if(!InventoryClickUtils.canClickItem(event)) return; + StarItem starItem = StarItemsAPI.getStarItemFromItemStack(cursor); + + Player player = (Player) event.getWhoClicked(); + assert starItem != null; + if(!event.getCurrentItem().getType().name().endsWith(starItem.getArmorType().name())) { + //if(starItem.getArmorTypes().stream().map(armorType -> armorType.name().toUpperCase(Locale.ROOT)).noneMatch(string -> event.getCurrentItem().getType().name().endsWith(string))) { + player.sendMessage(CC.translate(StarItemsPlugin.prefix + "&cThis star item cannot be applied to this item type")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + event.setCancelled(true); + if(StarItemsAPI.itemHasStarItemEquipped(event.getCurrentItem())) { + player.sendMessage(CC.translate(StarItemsPlugin.prefix + "&cThis item already has a star item equipped")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + event.setCursor(ItemUtils.decreaseItemStackAmountByOne(cursor)); + event.setCurrentItem(starItem.apply(event.getCurrentItem())); + player.updateInventory(); + LeaderboardsAPI.getPlayerStats(player.getUniqueId()).incrementStarItemsApplied(); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/listeners/DeathNoteListener.java b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/DeathNoteListener.java new file mode 100644 index 0000000..fc673cd --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/DeathNoteListener.java @@ -0,0 +1,75 @@ +package net.crankedpvp.staritems.listeners; + +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class DeathNoteListener implements Listener { + + public static List deathNoted = new ArrayList<>(); + + private final StarItemsPlugin plugin; + public DeathNoteListener(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + public void onChat(AsyncPlayerChatEvent event) { + if(event.getPlayer() == null || event.getMessage() == null) return; + if(!deathNoted.contains(event.getPlayer())) return; + Player chosen = Bukkit.getPlayer(event.getMessage()); + if(chosen == null) { + this.sendMessage(event.getPlayer()); + return; + } + if(!chosen.isOnline()) { + this.sendMessage(event.getPlayer()); + return; + } + if(chosen.getUniqueId().equals(event.getPlayer().getUniqueId())) { + this.sendMessage(event.getPlayer()); + return; + } + deathNoted.remove(event.getPlayer()); + chosen.setHealth(0); + + for(Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.sendMessage(""); + event.getPlayer().sendMessage(CC.translate("&8&lDeath Note &8" + Arrow.arrow() + " &7The player &c" + chosen.getName() + " &7has been vanquished by the &8Death Note")); + } + + } + + private void sendMessage(Player player) { + player.sendMessage(CC.translate("&8&lDeath Note &8" + Arrow.arrow() + " &7Choose a player's name and vanquish their soul...")); + player.sendMessage(CC.translate("&8&lDeath Note &8" + Arrow.arrow() + " &7Enter the name of any online player to instantly kill them: ")); + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if(event.getPlayer() == null || ItemUtils.isAirOrNull(event.getItem())) return; + if(event.getAction() != Action.RIGHT_CLICK_AIR || event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + + ItemStack itemStack = event.getPlayer().getItemInHand(); + if(!StarItemsAPI.isDeathNote(itemStack)) return; + event.getPlayer().setItemInHand(null); + deathNoted.add(event.getPlayer()); + event.getPlayer().sendMessage(""); + event.getPlayer().sendMessage(CC.translate("&8&lDeath Note &8" + Arrow.arrow() + " &7Choose a player's name and vanquish their soul...")); + event.getPlayer().sendMessage(CC.translate("&8&lDeath Note &8" + Arrow.arrow() + " &7Enter the name of any online player to instantly kill them: ")); + event.getPlayer().sendMessage(""); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/listeners/GoldenKnifeListener.java b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/GoldenKnifeListener.java new file mode 100644 index 0000000..3525214 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/GoldenKnifeListener.java @@ -0,0 +1,58 @@ +package net.crankedpvp.staritems.listeners; + +import net.crankedpvp.crankedutils.utils.*; +import net.crankedpvp.crankedutils.utils.items.ItemUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.inventory.GoldenKnivedInventory; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class GoldenKnifeListener implements Listener { + + public static Map inventories = new HashMap<>(); + + @EventHandler + public void onIncomingDamage(EntityDamageByEntityEvent event) { + if(!(event.getDamager() instanceof Player)) return; + Player attacker = (Player) event.getDamager(); + ItemStack knife = attacker.getItemInHand(); + if(ItemUtils.isAirOrNull(knife)) return; + if(!StarItemsAPI.isGoldenKnife(knife)) return; + if(!(event.getEntity() instanceof Player)) { + event.setCancelled(true); + return; + } + Player victim = (Player) event.getEntity(); + if(!WorldGuardUtils.canPvPInRegion(victim)) { + event.setCancelled(true); + return; + } + if(FactionUtils.inSameFaction(attacker, victim)) { + event.setCancelled(true); + return; + } + inventories.put(victim.getUniqueId(), new GoldenKnivedInventory(victim)); + event.setCancelled(true); + attacker.setItemInHand(null); + victim.setHealth(0); + victim.playSound(victim.getLocation(), Sound.ITEM_BREAK, 2.0f, 2.0f); + attacker.playSound(attacker.getLocation(), Sound.ITEM_BREAK, 2.0f, 2.0f); + Clickable clickable = new Clickable(StringUtils.getCenteredMessage("&8» &e&l" + victim.getName() + "'s Inventory &8«"), "&eClick to view &6" + victim.getName() + "'s &edeath inventory", "/goldenknifedeathinventoryview " + victim.getUniqueId()); + for(Player onlinePlayer : Bukkit.getOnlinePlayers()) { + onlinePlayer.sendMessage(StringUtils.getCenteredMessage(CC.translate("&e" + attacker.getName() + " &6has slain &e" + victim.getName()))); + onlinePlayer.sendMessage(StringUtils.getCenteredMessage(CC.translate("&eusing &8» &6&lThe Golden Knife &8«"))); + clickable.sendToPlayer(onlinePlayer); + } + } + + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PacketListeners.java b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PacketListeners.java new file mode 100644 index 0000000..4c64439 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PacketListeners.java @@ -0,0 +1,82 @@ +package net.crankedpvp.staritems.listeners; + +import net.crankedpvp.staritems.StarItemsPlugin; +import org.bukkit.event.Listener; + +public class PacketListeners implements Listener { + + private StarItemsPlugin plugin; + public PacketListeners(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + +/* + @EventHandler(priority = EventPriority.LOWEST) + public void onJoin(PlayerJoinEvent event) { + if(event.getPlayer() == null) return; + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + for(StarItem starItem : StarItemsAPI.getStarItemFromCache(event.getPlayer())) { + if(starItem instanceof Chroma) { + ChromaPacketTask.playersWithChromaEquipped.put(event.getPlayer(), event.getPlayer().getInventory().getHelmet()); + } else if(starItem instanceof Prisma) { + PrismaPacketTask.playersWithPrismaEquipped.put(event.getPlayer(), event.getPlayer().getInventory().getChestplate()); + } else if(starItem instanceof FounderStar) { + FounderStarPacketTask.playersWithFounderStarEquipped.put(event.getPlayer(), event.getPlayer().getInventory().getHelmet()); + } + } + }, 40L); + } + + */ + + /* + @EventHandler(priority = EventPriority.LOWEST) + public void onLeave(PlayerQuitEvent event) { + if(event.getPlayer() == null) return; + for(StarItem starItem : StarItemsAPI.getStarItemFromCache(event.getPlayer())) { + if(starItem instanceof Chroma) { + ChromaPacketTask.playersWithChromaEquipped.remove(event.getPlayer()); + } else if(starItem instanceof Prisma) { + PrismaPacketTask.playersWithPrismaEquipped.remove(event.getPlayer()); + } else if(starItem instanceof FounderStar) { + FounderStarPacketTask.playersWithFounderStarEquipped.remove(event.getPlayer()); + } + } + } + + */ + + /* + @EventHandler(priority = EventPriority.LOWEST) + public void armorChangeEvent(ArmorEquipEvent event) { + + if (event.getOldArmorPiece() != null && event.getOldArmorPiece().getType() != Material.AIR) { + if (StarItemsAPI.itemHasStarItemEquipped(event.getOldArmorPiece())) { + StarItem starItem = StarItemsAPI.getEquippedStarItem(event.getOldArmorPiece().clone()); + if(starItem instanceof Chroma) { + ChromaPacketTask.playersWithChromaEquipped.remove(event.getPlayer()); + } else if(starItem instanceof Prisma) { + PrismaPacketTask.playersWithPrismaEquipped.remove(event.getPlayer()); + } else if(starItem instanceof FounderStar) { + FounderStarPacketTask.playersWithFounderStarEquipped.remove(event.getPlayer()); + } + + } + } + if (event.getNewArmorPiece() != null && event.getNewArmorPiece().getType() != Material.AIR) { + if (StarItemsAPI.itemHasStarItemEquipped(event.getNewArmorPiece())) { + StarItem starItem = StarItemsAPI.getEquippedStarItem(event.getNewArmorPiece()); + if(starItem instanceof Chroma) { + ChromaPacketTask.playersWithChromaEquipped.put(event.getPlayer(), event.getNewArmorPiece().clone()); + } else if(starItem instanceof Prisma) { + PrismaPacketTask.playersWithPrismaEquipped.put(event.getPlayer(), event.getNewArmorPiece().clone()); + } else if(starItem instanceof FounderStar) { + FounderStarPacketTask.playersWithFounderStarEquipped.put(event.getPlayer(), event.getNewArmorPiece().clone()); + } + } + } + } + + */ +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PlayerListener.java b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PlayerListener.java new file mode 100644 index 0000000..8de4189 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PlayerListener.java @@ -0,0 +1,105 @@ +package net.crankedpvp.staritems.listeners; + +import net.crankedpvp.crankedutils.events.ArmorEquipEvent; +import net.crankedpvp.crankedutils.utils.WorldGuardUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; + +import java.util.List; + +public class PlayerListener implements Listener { + + private StarItemsPlugin plugin; + public PlayerListener(StarItemsPlugin plugin) { + this.plugin = plugin; + } + + + @EventHandler(priority = EventPriority.LOW) + public void placeStarItem(PlayerInteractEvent event) { + if(event.getItem() == null || event.getItem().getType() == Material.AIR) return; + if(StarItemsAPI.isStarItem(event.getItem())) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(PlayerJoinEvent event) { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> StarItemsAPI.refreshStarItemForPlayer(event.getPlayer()), 30L); + + } + + + @EventHandler + public void onDeath(PlayerDeathEvent event) { + if (event.getEntity() != null) { + StarItemsPlugin.getInstance().getStarItemManager().removeFromCacheCompletely(event.getEntity()); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onArmorChange(ArmorEquipEvent event) { + if (event.getOldArmorPiece() != null && event.getOldArmorPiece().getType() != Material.AIR) { + if (StarItemsAPI.itemHasStarItemEquipped(event.getOldArmorPiece())) { + StarItem starItem = StarItemsAPI.getEquippedStarItem(event.getOldArmorPiece()); + assert starItem != null; + starItem.onUnequip(event.getPlayer()); + //StarItemsPlugin.getInstance().getStarItemManager().getCachedPlayers().remove(event.getPlayer()); + StarItemsPlugin.getInstance().getStarItemManager().removeFromCache(event.getPlayer(), starItem); + } + } + if (event.getNewArmorPiece() != null && event.getNewArmorPiece().getType() != Material.AIR) { + if (StarItemsAPI.itemHasStarItemEquipped(event.getNewArmorPiece())) { + StarItem starItem = StarItemsAPI.getEquippedStarItem(event.getNewArmorPiece()); + assert starItem != null; + starItem.onEquip(event.getPlayer()); + StarItemsPlugin.getInstance().getStarItemManager().addToCache(event.getPlayer(), starItem); + //StarItemsPlugin.getInstance().getStarItemManager().getCachedPlayers().put(event.getPlayer(), starItem); + } + } + } + + + @EventHandler(priority = EventPriority.LOW) + public void playerReceiveDamage(EntityDamageByEntityEvent event) { + Entity damager = event.getDamager(); + Entity victim = event.getEntity(); + if (victim instanceof Player) { + Player player = (Player) victim; + if(!StarItemsAPI.playerHasStarItemInCache(player)) return; + List starItems = StarItemsAPI.getStarItemFromCache(player); + if(starItems == null || starItems.size() == 0) return; + if (!WorldGuardUtils.canPvPInRegion(victim.getLocation()) || !WorldGuardUtils.canPvPInRegion(damager.getLocation())) return; + for(StarItem starItem : starItems) + starItem.onIncomingDamage(player, damager, event); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void playerSendDamage(EntityDamageByEntityEvent event) { + Entity damager = event.getDamager(); + Entity victim = event.getEntity(); + if (damager instanceof Player) { + Player player = (Player) damager; + if(!StarItemsAPI.playerHasStarItemInCache(player)) return; + List starItems = StarItemsAPI.getStarItemFromCache(player); + if(starItems == null || starItems.size() == 0) return; + if (!WorldGuardUtils.canPvPInRegion(victim.getLocation()) || !WorldGuardUtils.canPvPInRegion(damager.getLocation())) return; + for(StarItem starItem : starItems) + starItem.onOutgoingDamage(player, victim, event); + } + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PotionAddListener.java b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PotionAddListener.java new file mode 100644 index 0000000..4042089 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/listeners/PotionAddListener.java @@ -0,0 +1,48 @@ +package net.crankedpvp.staritems.listeners; + +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.StarItemsPlugin; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.Objects; + +public class PotionAddListener implements Listener { + + + @EventHandler + public void onPotionEffectWithBlurredSoaker(PotionEffectAddEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = ((Player) event.getEntity()); + if (StarItemsAPI.getStarItemFromCache(player) == null) return; + if(Objects.requireNonNull(StarItemsAPI.getStarItemFromCache(player)).contains(StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID("blurredsoaker"))) { + if(!player.getLocation().getBlock().isLiquid()) return; + if (PotionEffectUtils.getDebuffsList().contains(event.getEffect().getType())) + event.setCancelled(true); + } + + if(Objects.requireNonNull(StarItemsAPI.getStarItemFromCache(player)).contains(StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID("angelboots"))) { + if (PotionEffectUtils.getDebuffsList().contains(event.getEffect().getType())) + event.setCancelled(true); + } + + /* + if (Objects.requireNonNull(StarItemsAPI.getStarItemFromCache(player)).contains(StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID("detioratedgolem"))) { + if (PotionEffectUtils.getDebuffsList().contains(event.getEffect().getType())) + event.setCancelled(true); + } + */ + + if (Objects.requireNonNull(StarItemsAPI.getStarItemFromCache(player)).contains(StarItemsPlugin.getInstance().getStarItemManager().getStarItemFromID("blackoutblindfold"))) { + if(player.hasPotionEffect(PotionEffectType.BLINDNESS)) + player.removePotionEffect(PotionEffectType.BLINDNESS); + if(event.getEffect().getType() != PotionEffectType.BLINDNESS) return; + event.setCancelled(true); + } + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Absence.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Absence.java new file mode 100644 index 0000000..b9888d6 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Absence.java @@ -0,0 +1,63 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class Absence extends StarItem { + @Override + public String getName() { + return "Absence"; + } + + @Override + public Material getHeldMaterial() { + return Material.SNOW_BLOCK; + } + + @Override + public Material getVisualMaterial() { + return Material.SNOW_BLOCK; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&b&lAbsence"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fThe absence of sound or noise...", + "&fDo not allow yourself to be silenced", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("-25% Silence Duration", "+5% Outgoing Damage"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "Absence"); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/AngelBoots.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/AngelBoots.java new file mode 100644 index 0000000..37318b3 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/AngelBoots.java @@ -0,0 +1,77 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class AngelBoots extends StarItem { + @Override + public String getName() { + return "Angel Boots"; + } + + @Override + public Material getHeldMaterial() { + return Material.GOLD_BOOTS; + } + + @Override + public Material getVisualMaterial() { + return Material.GOLD_BOOTS; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&b&lAngel Boots"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fA developed pair of boots", + "&fwhich allow for faster, cleaner", + "&fmovement throughout the warzone", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Permanent Speed IV Effect", "Auto Bless", "-3% Incoming Damage"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.BOOTS; + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "Angel Boots"); + PotionEffectUtils.bless(player); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "Angel Boots"); + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(3, event, "Angel Boots"); + } + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/BlackoutBlindfold.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/BlackoutBlindfold.java new file mode 100644 index 0000000..47a59d5 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/BlackoutBlindfold.java @@ -0,0 +1,69 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; + +public class BlackoutBlindfold extends StarItem { + @Override + public String getName() { + return "Blackout Blindfold"; + } + + @Override + public Material getHeldMaterial() { + return Material.IRON_PLATE; + } + + @Override + public Material getVisualMaterial() { + return Material.IRON_PLATE; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&c&lBlackout Blindfold"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fA pitch-black blindfold that", + "&fenlightens your body", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "Immune to blindness", + "+35% Silence Duration", + "50% Chance to block galactic visor phoenix" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + + @Override + public void onEquip(Player player) { + } + + @Override + public void onUnequip(Player player) { + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/BlurredSoaker.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/BlurredSoaker.java new file mode 100644 index 0000000..ec92fab --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/BlurredSoaker.java @@ -0,0 +1,73 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class BlurredSoaker extends StarItem { + @Override + public String getName() { + return "Blurred Soaker"; + } + + @Override + public Material getHeldMaterial() { + return Material.SPONGE; + } + + @Override + public Material getVisualMaterial() { + return Material.SPONGE; + } + + @Override + public short getData() { + return 1; + } + + @Override + public String getDisplayName() { + return "&b&lBlurred Soaker"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fControl the power of this infinitely", + "&fsoaking sponge and conquer with it.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "+15% Damage while in water", + "Immune to new debuffs while in water" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + if(attacker.getLocation().getBlock().isLiquid()) + super.getDamageHandler().increaseDamage(15, event, "BlurredSoaker"); + } + } + + public void onEquip(Player player) { + PotionEffectUtils.bless(player); + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Combo.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Combo.java new file mode 100644 index 0000000..f69c944 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Combo.java @@ -0,0 +1,72 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class Combo extends StarItem { + @Override + public String getName() { + return "Combo"; + } + + @Override + public Material getHeldMaterial() { + return Material.RAW_FISH; + } + + @Override + public Material getVisualMaterial() { + return Material.GOLD_BLOCK; + } + + @Override + public short getData() { + return 3; + } + + @Override + public String getDisplayName() { + return "&e&lCombo"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fWe used to like this.. now we do not.", + "&fThe yellow pufferfish, it needs to go.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "Immune to Titan Pet", + "Immune to Spider Pet", + "Rage Enchantment deals +25% more damage", + "Deal +7.5% more damage to enemies wielding hooks" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(7.5, event, "BlurredSoaker"); + } + } + + public void onEquip(Player player) { + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/DeterioratedGolem.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/DeterioratedGolem.java new file mode 100644 index 0000000..c56c7ad --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/DeterioratedGolem.java @@ -0,0 +1,95 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import net.crankedpvp.staritems.cooldowns.ShackleAbilityCooldown; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class DeterioratedGolem extends StarItem { + + private final static double ABILITY_CHANCE = 0.05; + private final static int ABILITY_DURATION = 3; + private final static int ABILITY_COOLDOWN = 120; + + @Override + public String getName() { + return "Deteriorated Golem"; + } + + @Override + public Material getHeldMaterial() { + return Material.IRON_BLOCK; + } + + @Override + public Material getVisualMaterial() { + return Material.IRON_BLOCK; + } + + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&7&lDeteriorated Golem"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fThe golem is a piece of art.", + "&fHowever its strengths are never", + "&fto be undermined..", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "-10% Incoming damage from enemy players", + "Negative potion effects have a chance to heal you", + "Shackle Ability" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(10, event, this.getName()); + if (event.isCancelled()) return; + if(Math.random() > ABILITY_CHANCE) return; + if (CooldownUtils.isCooldownActive(victim, "shackleAbility")) return; + CooldownUtils.registerCooldown(victim, new ShackleAbilityCooldown("shackleAbility", ABILITY_COOLDOWN)); + + Player att = (Player) attacker; + att.setWalkSpeed(0.0F); + PotionEffectUtils.addPotionEffect(att, PotionEffectType.JUMP, 129, "shackleAbility", ABILITY_DURATION); + att.playSound(att.getLocation(), Sound.PISTON_RETRACT, 2.0F, 3.0F); + TitleUtils.sendTitle(att, CC.translate("&7&l* SHACKLED *"), CC.translate("&fYou have been shackled in place"), 1, 2, 1); + victim.sendMessage(CC.translate("&7&l* SHACKLED (" + att.getName() + ") *")); + Bukkit.getScheduler().runTaskLater(super.getStarItemsPlugin(), () -> att.setWalkSpeed(0.2F), ABILITY_DURATION * 20L); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Discharge.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Discharge.java new file mode 100644 index 0000000..77495a4 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Discharge.java @@ -0,0 +1,180 @@ +package net.crankedpvp.staritems.staritems; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.cooldowns.DirtyBombCooldown; +import net.crankedpvp.staritems.cooldowns.HotPotatoCooldown; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; + +public class Discharge extends StarItem implements Listener { + + private final List hotPotatoPlayers = new ArrayList<>(); + + @Override + public String getName() { + return "Discharge"; + } + + @Override + public Material getHeldMaterial() { + return Material.TNT; + } + + @Override + public Material getVisualMaterial() { + return Material.TNT; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&4&lD&c&lI&4&lS&c&lC&4&lH&c&lA&4&lR&c&lG&4&lE"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fA piece of fragile equipment which", + "&fmay detonate at any given moment.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Permanent Speed IV effect", "+5% Outgoing Damage", "Hot Potato Ability", "Dirty Bomb Ability"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "Discharge"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "Discharge"); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "Discharge"); + if(this.hotPotatoPlayers.contains(attacker)) super.getDamageHandler().increaseDamage(10, event, "HotPotato"); + } + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + if(event.isCancelled() || event.getFinalDamage() <= 0) return; + tryProcDirtyBombAbility(victim); + tryProcHotPotatoAbility(victim); + } + } + + private void tryProcHotPotatoAbility(Player victim) { + if(Math.random() > 0.02) return; + if (CooldownUtils.isCooldownActive(victim, "hotPotatoAbility")) return; + CooldownUtils.registerCooldown(victim, new HotPotatoCooldown("hotPotatoAbility", 90)); + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.SPEED, 5, "hotPotatoAbility", 5); + this.hotPotatoPlayers.add(victim); + Bukkit.getScheduler().runTaskLater(super.getStarItemsPlugin(), () -> this.hotPotatoPlayers.remove(victim), 5 * 20L); + victim.sendMessage(CC.translate("&c&lDischarge &8➥ &eYour have became a &cHot Potato&e, strike while it lasts.")); + } + + public void tryProcDirtyBombAbility(Player player) { + if(Math.random() > 0.02) return; + if (CooldownUtils.isCooldownActive(player, "dirtyBombAbility")) return; + CooldownUtils.registerCooldown(player, new DirtyBombCooldown("dirtyBombAbility", 120)); + for(int i = 0; i < ThreadLocalRandom.current().nextInt(3, 6); i++) { + this.spawnExplosion(player, this.getNearbyLocation(player.getLocation(), 10, 8), 2*20); + //super.getStarItemsPlugin().getServer().getScheduler().runTaskLater(super.getStarItemsPlugin(), () -> this.spawnExplosion(player, this.getNearbyLocation(player.getLocation(), 10, 8), 6), 25L); + } + } + + + + @EventHandler(priority= EventPriority.LOWEST) + public void onBlockExplode(EntityExplodeEvent event) { + if (event.getEntity() != null && event.getEntity().hasMetadata("DirtyBombTNT")) { + event.setYield(0.0f); + event.blockList().clear(); + if (!PVPUtils.canPvPInRegion(event.getLocation())) return; + Location loc = event.getLocation(); + loc.getWorld().playSound(loc, Sound.EXPLODE, 1.0f, 1.0f); + + String exploder = event.getEntity().getMetadata("DirtyBombTNT").get(0).asString(); + Player pExploder = Bukkit.getPlayer(exploder); + FPlayer fp = pExploder != null ? FPlayers.getInstance().getByPlayer(pExploder) : null; + for (Entity ent : event.getEntity().getNearbyEntities(6, 6, 6)) { + if(!(ent instanceof Player)) continue; + if(fp == null) continue; + if(!fp.getRelationTo(FPlayers.getInstance().getByPlayer((Player) ent)).isAtLeast(Relation.TRUCE)) continue; + if(!PVPUtils.canPvPInRegion(ent.getLocation())) continue; + Player loopPlayer = (Player)ent; + loopPlayer.sendMessage(CC.translate("&c&lDischarge &8➥ &eYou have been struck by a &cDirty Bomb")); + loopPlayer.setFireTicks(40); + loopPlayer.damage(8.0); + loopPlayer.playSound(loopPlayer.getLocation(), Sound.EXPLODE, 1.0F, 1.0F); + PotionEffectUtils.addPotionEffect(loopPlayer, PotionEffectType.SLOW, 4, "DirtyBomb", 3); + } + event.getEntity().remove(); + } + } + + private void spawnExplosion(Player exploder, Location location, int fuseTicks) { + if (location.getBlock().getType().isSolid()) { + return; + } + TNTPrimed tnt = (TNTPrimed)location.getWorld().spawnEntity(location, EntityType.PRIMED_TNT); + tnt.setFuseTicks(fuseTicks); + tnt.setMetadata("DirtyBombTNT", new FixedMetadataValue(StarItemsPlugin.getInstance(), exploder.getName())); + } + + private Location getNearbyLocation(Location location, int radius, int y_boost) { + Random rand = new Random(); + Location rand_loc = location.clone(); + rand_loc.add((rand.nextBoolean() ? 1 : -1) * (rand.nextInt(radius) + 1), 0.0, (rand.nextBoolean() ? 1 : -1) * (rand.nextInt(radius) + 1)); + rand_loc.add(0.5, y_boost, 0.5); + while ((rand_loc.getBlock().getType() != Material.AIR || rand_loc.getBlock().getLocation().subtract(0.0, 1.0, 0.0).getBlock().getType() != Material.AIR) && rand_loc.getY() < 255.0) { + rand_loc = rand_loc.add(0.0, 1.0, 0.0); + } + return rand_loc; + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Frostbite.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Frostbite.java new file mode 100644 index 0000000..c15d6a2 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Frostbite.java @@ -0,0 +1,84 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class Frostbite extends StarItem { + + private final static double ABILITY_CHANCE = 0.01; + @Override + public String getName() { + return "Frostbite"; + } + + @Override + public Material getHeldMaterial() { + return Material.ICE; + } + + @Override + public Material getVisualMaterial() { + return Material.ICE; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&9&lFrostbite"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fHarness the power of indestructible ice.", + "&fProtect yourself with layers of ice", + "&fand trap others in it's path", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "-10% Incoming damage from enemies in water", + "Immune to Divine Immolation", + "Water Polaroid Ability" + ); + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + if(victim.getLocation().getBlock().isLiquid()) + super.getDamageHandler().reduceDamage(10, event, "Frostbite"); + + + } + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(!(victim instanceof Player)) return; + if (event.isCancelled()) return; + if(Math.random() > ABILITY_CHANCE) return; + Player victimPlayer = (Player)victim; + super.getStarItemsPlugin().getIceTrapAbility().procAbility(attacker, victimPlayer); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } +} + diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GalacticVisor.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GalacticVisor.java new file mode 100644 index 0000000..a9c56f9 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GalacticVisor.java @@ -0,0 +1,96 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.cooldowns.PhoenixAbilityCooldown; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class GalacticVisor extends StarItem { + @Override + public String getName() { + return "Galactic Visor"; + } + + @Override + public Material getHeldMaterial() { + return Material.STAINED_GLASS; + } + + @Override + public Material getVisualMaterial() { + return Material.STAINED_GLASS; + } + + @Override + public short getData() { + return 2; + } + + @Override + public String getDisplayName() { + return "&5&lGalactic Visor"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fBecome one with space, this visor", + "&fguides you through the cosmoverse.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("75% Holy White Scroll Negation", "Phoenix Ability"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + if (event.isCancelled()) return; + if(victim.getHealth() < 5) { + if(Math.random() > 0.2) return; + Player attackingPlayer = (Player) attacker; + if(CooldownUtils.isCooldownActive(victim, "PhoenixAbility")) return; + CooldownUtils.registerCooldown(victim, new PhoenixAbilityCooldown("PhoenixAbility", 120)); + if(Objects.equals(CrankedArmorAPI.getCurrentArmorSet(attackingPlayer), CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID("draco"))) { + victim.sendMessage(CC.translate("&5&lGalactic Visor &8➥ &cYour phoenix ability has been &nblocked&r &cby " + attackingPlayer.getName() + "'s draco set")); + victim.playSound(victim.getLocation(), Sound.ANVIL_BREAK, 1.0F, 1.0F); + attackingPlayer.sendMessage(CC.translate("&c&lDraco &8➥ &eYour draco set has &c&lBLOCKED &e" + victim.getName() + "'s phoenix ability")); + return; + } + if(StarItemsAPI.playerHasStarItemInCache(attackingPlayer)) { + if(StarItemsAPI.getStarItemFromCache(attackingPlayer).contains(super.getStarItemsPlugin().getStarItemManager().getStarItemFromID("blackoutblindfold"))) { + if(Math.random() < 0.5) { + victim.sendMessage(CC.translate("&5&lGalactic Visor &8➥ &cYour phoenix ability has been &nblocked&r &cby " + attackingPlayer.getName() + "'s blackout blindfold")); + victim.playSound(victim.getLocation(), Sound.ANVIL_BREAK, 1.0F, 1.0F); + return; + } + } + } + victim.setHealth(victim.getMaxHealth()); + victim.sendMessage(CC.translate("&5&lGalactic Visor &8➥ &eYour phoenix ability has &a&lHEALED &eyou to full health")); + victim.playSound(victim.getLocation(), Sound.GHAST_DEATH, 1.0F, 1.0F); + } + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GloopGetaway.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GloopGetaway.java new file mode 100644 index 0000000..5004adf --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GloopGetaway.java @@ -0,0 +1,117 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.crankedutils.utils.TitleUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.cooldowns.GloopGetawayCooldown; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class GloopGetaway extends StarItem implements Listener { + + private final List gloopGetawayAbility = new ArrayList<>(); + + @Override + public String getName() { + return "Gloop Getaway"; + } + + @Override + public Material getHeldMaterial() { + return Material.SLIME_BLOCK; + } + + @Override + public Material getVisualMaterial() { + return Material.SLIME_BLOCK; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&a&lGloop Getaway"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fAn informal variation of the slime", + "&fthat allows you to passively escape", + "&fat low HP", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("10% Holy White Scroll Negation", "Immune to fall damage", "Slime Fall Ability", "Gloop Getaway Ability"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + if(!this.gloopGetawayAbility.contains(attacker)) return; + super.getDamageHandler().increaseDamage(10, event, "SlimeFallAbility"); + } + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(!(attacker instanceof Player)) return; + if (event.isCancelled()) return; + if (CooldownUtils.isCooldownActive(victim, "gloopGetawayAbility")) return; + if(victim.getHealth() > victim.getMaxHealth() / 4) return; + if(Math.random() > 0.05) return; + CooldownUtils.registerCooldown(victim, new GloopGetawayCooldown("gloopGetawayAbility", 90)); + victim.setVelocity(new Vector(0, 12, 0)); + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.REGENERATION, 3, "GloopGetawayAbility", 3); + TitleUtils.sendTitle(victim, CC.translate("&a&lGloop Getaway"), CC.translate("&7&oIt's your time to escape..."), 1, 2, 1); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoinEvent(final PlayerJoinEvent event) { + if(event.getPlayer() == null) return; + this.gloopGetawayAbility.remove(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityDamageEvent(final EntityDamageEvent event) { + if(!(event.getEntity() instanceof Player)) return; + final Player player = (Player) event.getEntity(); + if(event.getCause() == EntityDamageEvent.DamageCause.FALL) { + if(!StarItemsAPI.playerHasStarItemInCache(player)) return; + if(!StarItemsAPI.getStarItemFromCache(player).contains(this)) return; + event.setCancelled(true); + if(Math.random() < 0.01) { + this.gloopGetawayAbility.add(player); + Bukkit.getScheduler().runTaskLater(super.getStarItemsPlugin(), () -> this.gloopGetawayAbility.remove(player), 5 * 20L); + } + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GoldenEyeBandage.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GoldenEyeBandage.java new file mode 100644 index 0000000..66fe5bb --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/GoldenEyeBandage.java @@ -0,0 +1,76 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.staritems.cooldowns.EyeBandageHealCooldown; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class GoldenEyeBandage extends StarItem { + + @Override + public String getName() { + return "Golden Eye Bandage"; + } + + @Override + public Material getHeldMaterial() { + return Material.GOLD_PLATE; + } + + @Override + public Material getVisualMaterial() { + return Material.GOLD_PLATE; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&6&lGolden Eye Bandage"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fWhat is preventing your eye from healing?", + "&fThis will speed up it's process.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "15% Chance to negate enemy holy white scrolls", + "Chance to heal +4HP when hit" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + if(Math.random() > 0.02) return; + if (event.isCancelled()) return; + if(CooldownUtils.isCooldownActive(victim, "eyebandagehealcooldown")) return; + CooldownUtils.registerCooldown(victim, new EyeBandageHealCooldown("eyebandagehealcooldown", 20)); + super.getDamageHandler().healEntity(victim, 4, "Golden Eye Bandage"); + victim.sendMessage(CC.translate("&6&lEye Bandage &8➥ &eYou have been healed by your eye bandage &7(&a+4HP&7)")); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/HermesBoots.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/HermesBoots.java new file mode 100644 index 0000000..34b6e63 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/HermesBoots.java @@ -0,0 +1,67 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class HermesBoots extends StarItem { + @Override + public String getName() { + return "Hermes Boots"; + } + + @Override + public Material getHeldMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public Material getVisualMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&6&lHermes Boots"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fAn underdeveloped pair of boots", + "&fwhich allow for faster, cleaner", + "&fmovement throughout the warzone", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Permanent Speed IV Effect"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.BOOTS; + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "Hermes Boots"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "Hermes Boots"); + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/IgnitedHolograph.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/IgnitedHolograph.java new file mode 100644 index 0000000..1ced9da --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/IgnitedHolograph.java @@ -0,0 +1,73 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class IgnitedHolograph extends StarItem { + @Override + public String getName() { + return "Ignited Holograph"; + } + + @Override + public Material getHeldMaterial() { + return Material.JACK_O_LANTERN; + } + + @Override + public Material getVisualMaterial() { + return Material.JACK_O_LANTERN; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&6&lIgnited Holograph"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fIt may scare you at first, but", + "&fit holds immense power and must", + "&fnot be looked past", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "Immune to spider pet", + "+12.5% Outgoing damage to burning enemies" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + Player playerVictim = (Player) victim; + if(playerVictim.getFireTicks() <= 0) return; + if(Objects.equals(CrankedArmorAPI.getCurrentArmorSet(playerVictim), CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID("nightmare"))) return; + super.getDamageHandler().increaseDamage(15, event, "Ignited Holograph"); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Olympus.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Olympus.java new file mode 100644 index 0000000..7f9fc08 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Olympus.java @@ -0,0 +1,75 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class Olympus extends StarItem { + @Override + public String getName() { + return "Olympus"; + } + + @Override + public Material getHeldMaterial() { + return Material.BEACON; + } + + @Override + public Material getVisualMaterial() { + return Material.BEACON; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&3&lO&b&ll&3&ly&b&lm&3&lp&b&lu&3&ls"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fThe gates of olympus await you...", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "-5.5% Incoming Damage", + "+4% Outgoing Damage", + "Immune to titan pet", + "66% Holy White Scroll Negation" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(5.5, event, "Olympus"); + } + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + super.getDamageHandler().increaseDamage(4, event, "Olympus"); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/PortableBard.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/PortableBard.java new file mode 100644 index 0000000..361b29f --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/PortableBard.java @@ -0,0 +1,64 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class PortableBard extends StarItem { + @Override + public String getName() { + return "Portable Bard"; + } + + @Override + public Material getHeldMaterial() { + return Material.GOLD_INGOT; + } + + @Override + public Material getVisualMaterial() { + return Material.GOLD_HELMET; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&6&lPortable Bard"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fHow are you using bard effects", + "&fwith a diamond set...? wow.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Ability to use bard buffs", "+25% Incoming Damage"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().increaseDamage(25, event, this.getName()); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/SantasBeard.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/SantasBeard.java new file mode 100644 index 0000000..95028cf --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/SantasBeard.java @@ -0,0 +1,142 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.cooldowns.SantasPieAbility; +import net.crankedpvp.staritems.cooldowns.SantasPresentAbility; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class SantasBeard extends StarItem { + @Override + public String getName() { + return "Santas Beard"; + } + + @Override + public Material getHeldMaterial() { + return Material.SNOW; + } + + @Override + public Material getVisualMaterial() { + return Material.SNOW; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&c&lSantas Beard"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fThe long and fluffy beard", + "&floved by all at Christmas", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "Bypass Abyss slowness", + "Santas Present Ability", + " &7&o(Chance to gain positive effects)", + "Santas Pie Eater Ability", + " &7&o(Chance to gain +6 absorption hearts)" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + + @Override + public void onEquip(Player player) { + } + + @Override + public void onUnequip(Player player) { + } + + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + if(CooldownUtils.isCooldownActive(victim, "santas_beard_pie_eater_ability")) return; + CooldownUtils.registerCooldown(victim, new SantasPieAbility()); + PotionEffectUtils.addExtraPotionEffect(victim, PotionEffectType.ABSORPTION, 3, "santas_beard_pie_eater_ability", 5); + victim.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7You ate ALOT of pies, lots of fat, lots of &eabsorption"))); + } + } + + + private List damageIncrease = new ArrayList<>(); + private List damageDecrease = new ArrayList<>(); + private List rageDamage = new ArrayList<>(); + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(!(victim instanceof Player)) return; + if (event.isCancelled()) return; + + if(damageIncrease.contains(attacker)) super.getDamageHandler().increaseDamage(5, event, "santas_beard_inc"); + if(damageDecrease.contains(victim)) super.getDamageHandler().reduceDamage(5, event, "santas_beard_reduc"); + + double chance = 0.5D; + if(CrankedMasksAPI.hasMaskEquipped(attacker, "santa")) chance *= 2; + if(ThreadLocalRandom.current().nextDouble() > chance) return; + + if(CooldownUtils.isCooldownActive(attacker, "santas_beard_present_ability")) return; + CooldownUtils.registerCooldown(attacker, new SantasPresentAbility()); + int num = ThreadLocalRandom.current().nextInt(1, 4); + switch(num) { + case 1: + damageIncrease.add(attacker); + attacker.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7Santa dropped a present giving you &c+5% outgoing damage"))); + break; + case 2: + damageDecrease.add(attacker); + attacker.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7Santa dropped a present giving you &b-5% incoming damage"))); + break; + case 3: + PotionEffectUtils.addPotionEffect(attacker, PotionEffectType.SPEED, 5, "santas_beard_speed", 5); + attacker.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7Santa dropped a present giving you &aSpeed V"))); + break; + case 4: + rageDamage.add(attacker); + attacker.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7Santa dropped a present giving you &4+10% Rage Damage"))); + break; + } + + this.getStarItemsPlugin().getServer().getScheduler().runTaskLater(this.getStarItemsPlugin(), () -> this.removeFromAll(attacker), 5 * 20L); + } + + private void removeFromAll(Player player) { + this.rageDamage.remove(player); + this.damageDecrease.remove(player); + this.damageIncrease.remove(player); + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Void.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Void.java new file mode 100644 index 0000000..b5b1681 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/Void.java @@ -0,0 +1,62 @@ +package net.crankedpvp.staritems.staritems; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class Void extends StarItem { + @Override + public String getName() { + return "Void"; + } + + @Override + public Material getHeldMaterial() { + return Material.SOUL_SAND; + } + + @Override + public Material getVisualMaterial() { + return Material.SOUL_SAND; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&d&lVoid"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fConquer the abyss, conquer the void.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Immune to Abyss Enchant", "Bypass Snow Golem Pet", "Deal +7.5% more damage while wielding a hook"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(7.5, event, "Void"); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicAbsence.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicAbsence.java new file mode 100644 index 0000000..580c610 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicAbsence.java @@ -0,0 +1,63 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class CosmicAbsence extends StarItem { + @Override + public String getName() { + return "Absence"; + } + + @Override + public Material getHeldMaterial() { + return Material.SNOW_BLOCK; + } + + @Override + public Material getVisualMaterial() { + return Material.SNOW_BLOCK; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&b&lAbsence"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fThe absence of sound or noise...", + "&fDo not allow yourself to be silenced", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("-25% Silence Duration", "+5% Outgoing Damage"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "Absence"); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicAngelBoots.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicAngelBoots.java new file mode 100644 index 0000000..634b57e --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicAngelBoots.java @@ -0,0 +1,77 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class CosmicAngelBoots extends StarItem { + @Override + public String getName() { + return "Angel Boots"; + } + + @Override + public Material getHeldMaterial() { + return Material.GOLD_BOOTS; + } + + @Override + public Material getVisualMaterial() { + return Material.GOLD_BOOTS; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&b&lAngel Boots"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fA developed pair of boots", + "&fwhich allow for faster, cleaner", + "&fmovement throughout the warzone", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Permanent Speed IV Effect", "Auto Bless", "-3% Incoming Damage"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.BOOTS; + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "Angel Boots"); + PotionEffectUtils.bless(player); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "Angel Boots"); + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(3, event, "Angel Boots"); + } + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicDischarge.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicDischarge.java new file mode 100644 index 0000000..9ab9307 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicDischarge.java @@ -0,0 +1,180 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.perms.Relation; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PVPUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.cooldowns.DirtyBombCooldown; +import net.crankedpvp.staritems.cooldowns.HotPotatoCooldown; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; + +public class CosmicDischarge extends StarItem implements Listener { + + private final List hotPotatoPlayers = new ArrayList<>(); + + @Override + public String getName() { + return "Discharge"; + } + + @Override + public Material getHeldMaterial() { + return Material.TNT; + } + + @Override + public Material getVisualMaterial() { + return Material.TNT; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&4&lD&c&lI&4&lS&c&lC&4&lH&c&lA&4&lR&c&lG&4&lE"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fA piece of fragile equipment which", + "&fmay detonate at any given moment.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Permanent Speed IV effect", "+5% Outgoing Damage", "Hot Potato Ability", "Dirty Bomb Ability"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "Discharge"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "Discharge"); + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + super.getDamageHandler().increaseDamage(5, event, "Discharge"); + if(this.hotPotatoPlayers.contains(attacker)) super.getDamageHandler().increaseDamage(10, event, "HotPotato"); + } + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + if(event.isCancelled() || event.getFinalDamage() <= 0) return; + tryProcDirtyBombAbility(victim); + tryProcHotPotatoAbility(victim); + } + } + + private void tryProcHotPotatoAbility(Player victim) { + if(Math.random() > 0.02) return; + if (CooldownUtils.isCooldownActive(victim, "hotPotatoAbility")) return; + CooldownUtils.registerCooldown(victim, new HotPotatoCooldown("hotPotatoAbility", 90)); + PotionEffectUtils.addPotionEffect(victim, PotionEffectType.SPEED, 5, "hotPotatoAbility", 5); + this.hotPotatoPlayers.add(victim); + Bukkit.getScheduler().runTaskLater(super.getStarItemsPlugin(), () -> this.hotPotatoPlayers.remove(victim), 5 * 20L); + victim.sendMessage(CC.translate("&c&lDischarge &8➥ &eYour have became a &cHot Potato&e, strike while it lasts.")); + } + + public void tryProcDirtyBombAbility(Player player) { + if(Math.random() > 0.02) return; + if (CooldownUtils.isCooldownActive(player, "dirtyBombAbility")) return; + CooldownUtils.registerCooldown(player, new DirtyBombCooldown("dirtyBombAbility", 120)); + for(int i = 0; i < ThreadLocalRandom.current().nextInt(3, 6); i++) { + this.spawnExplosion(player, this.getNearbyLocation(player.getLocation(), 10, 8), 2*20); + //super.getStarItemsPlugin().getServer().getScheduler().runTaskLater(super.getStarItemsPlugin(), () -> this.spawnExplosion(player, this.getNearbyLocation(player.getLocation(), 10, 8), 6), 25L); + } + } + + + + @EventHandler(priority= EventPriority.LOWEST) + public void onBlockExplode(EntityExplodeEvent event) { + if (event.getEntity() != null && event.getEntity().hasMetadata("DirtyBombTNT")) { + event.setYield(0.0f); + event.blockList().clear(); + if (!PVPUtils.canPvPInRegion(event.getLocation())) return; + Location loc = event.getLocation(); + loc.getWorld().playSound(loc, Sound.EXPLODE, 1.0f, 1.0f); + + String exploder = event.getEntity().getMetadata("DirtyBombTNT").get(0).asString(); + Player pExploder = Bukkit.getPlayer(exploder); + FPlayer fp = pExploder != null ? FPlayers.getInstance().getByPlayer(pExploder) : null; + for (Entity ent : event.getEntity().getNearbyEntities(6, 6, 6)) { + if(!(ent instanceof Player)) continue; + if(fp == null) continue; + if(!fp.getRelationTo(FPlayers.getInstance().getByPlayer((Player) ent)).isAtLeast(Relation.TRUCE)) continue; + if(!PVPUtils.canPvPInRegion(ent.getLocation())) continue; + Player loopPlayer = (Player)ent; + loopPlayer.sendMessage(CC.translate("&c&lDischarge &8➥ &eYou have been struck by a &cDirty Bomb")); + loopPlayer.setFireTicks(40); + loopPlayer.damage(8.0); + loopPlayer.playSound(loopPlayer.getLocation(), Sound.EXPLODE, 1.0F, 1.0F); + PotionEffectUtils.addPotionEffect(loopPlayer, PotionEffectType.SLOW, 4, "DirtyBomb", 3); + } + event.getEntity().remove(); + } + } + + private void spawnExplosion(Player exploder, Location location, int fuseTicks) { + if (location.getBlock().getType().isSolid()) { + return; + } + TNTPrimed tnt = (TNTPrimed)location.getWorld().spawnEntity(location, EntityType.PRIMED_TNT); + tnt.setFuseTicks(fuseTicks); + tnt.setMetadata("DirtyBombTNT", new FixedMetadataValue(StarItemsPlugin.getInstance(), exploder.getName())); + } + + private Location getNearbyLocation(Location location, int radius, int y_boost) { + Random rand = new Random(); + Location rand_loc = location.clone(); + rand_loc.add((rand.nextBoolean() ? 1 : -1) * (rand.nextInt(radius) + 1), 0.0, (rand.nextBoolean() ? 1 : -1) * (rand.nextInt(radius) + 1)); + rand_loc.add(0.5, y_boost, 0.5); + while ((rand_loc.getBlock().getType() != Material.AIR || rand_loc.getBlock().getLocation().subtract(0.0, 1.0, 0.0).getBlock().getType() != Material.AIR) && rand_loc.getY() < 255.0) { + rand_loc = rand_loc.add(0.0, 1.0, 0.0); + } + return rand_loc; + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicGalacticVisor.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicGalacticVisor.java new file mode 100644 index 0000000..1f1cd0e --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicGalacticVisor.java @@ -0,0 +1,96 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.staritems.StarItemsAPI; +import net.crankedpvp.staritems.cooldowns.PhoenixAbilityCooldown; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class CosmicGalacticVisor extends StarItem { + @Override + public String getName() { + return "Galactic Visor"; + } + + @Override + public Material getHeldMaterial() { + return Material.STAINED_GLASS; + } + + @Override + public Material getVisualMaterial() { + return Material.STAINED_GLASS; + } + + @Override + public short getData() { + return 2; + } + + @Override + public String getDisplayName() { + return "&5&lGalactic Visor"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fBecome one with space, this visor", + "&fguides you through the cosmoverse.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("75% Holy White Scroll Negation", "Phoenix Ability"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + if (event.isCancelled()) return; + if(victim.getHealth() < 5) { + if(Math.random() > 0.2) return; + Player attackingPlayer = (Player) attacker; + if(CooldownUtils.isCooldownActive(victim, "PhoenixAbility")) return; + CooldownUtils.registerCooldown(victim, new PhoenixAbilityCooldown("PhoenixAbility", 120)); + if(Objects.equals(CrankedArmorAPI.getCurrentArmorSet(attackingPlayer), CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID("draco"))) { + victim.sendMessage(CC.translate("&5&lGalactic Visor &8➥ &cYour phoenix ability has been &nblocked&r &cby " + attackingPlayer.getName() + "'s draco set")); + victim.playSound(victim.getLocation(), Sound.ANVIL_BREAK, 1.0F, 1.0F); + attackingPlayer.sendMessage(CC.translate("&c&lDraco &8➥ &eYour draco set has &c&lBLOCKED &e" + victim.getName() + "'s phoenix ability")); + return; + } + if(StarItemsAPI.playerHasStarItemInCache(attackingPlayer)) { + if(StarItemsAPI.getStarItemFromCache(attackingPlayer).contains(super.getStarItemsPlugin().getStarItemManager().getStarItemFromID("blackoutblindfold"))) { + if(Math.random() < 0.5) { + victim.sendMessage(CC.translate("&5&lGalactic Visor &8➥ &cYour phoenix ability has been &nblocked&r &cby " + attackingPlayer.getName() + "'s blackout blindfold")); + victim.playSound(victim.getLocation(), Sound.ANVIL_BREAK, 1.0F, 1.0F); + return; + } + } + } + victim.setHealth(victim.getMaxHealth()); + victim.sendMessage(CC.translate("&5&lGalactic Visor &8➥ &eYour phoenix ability has &a&lHEALED &eyou to full health")); + victim.playSound(victim.getLocation(), Sound.GHAST_DEATH, 1.0F, 1.0F); + } + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicHermesBoots.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicHermesBoots.java new file mode 100644 index 0000000..f3f8d4b --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicHermesBoots.java @@ -0,0 +1,67 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; + +public class CosmicHermesBoots extends StarItem { + @Override + public String getName() { + return "Hermes Boots"; + } + + @Override + public Material getHeldMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public Material getVisualMaterial() { + return Material.DIAMOND_BOOTS; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&6&lHermes Boots"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fAn underdeveloped pair of boots", + "&fwhich allow for faster, cleaner", + "&fmovement throughout the warzone", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Permanent Speed IV Effect"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.BOOTS; + } + + public void onEquip(Player player) { + PotionEffectUtils.addPotionEffect(player, PotionEffectType.SPEED, 4, "Hermes Boots"); + } + + public void onUnequip(Player player) { + PotionEffectUtils.removePotionEffect(player, "Hermes Boots"); + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicIgnitedHolograph.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicIgnitedHolograph.java new file mode 100644 index 0000000..1f7ecdb --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicIgnitedHolograph.java @@ -0,0 +1,73 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import net.crankedpvp.crankedarmor.CrankedArmor; +import net.crankedpvp.crankedarmor.CrankedArmorAPI; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class CosmicIgnitedHolograph extends StarItem { + @Override + public String getName() { + return "Ignited Holograph"; + } + + @Override + public Material getHeldMaterial() { + return Material.JACK_O_LANTERN; + } + + @Override + public Material getVisualMaterial() { + return Material.JACK_O_LANTERN; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&6&lIgnited Holograph"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fIt may scare you at first, but", + "&fit holds immense power and must", + "&fnot be looked past", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "Immune to spider pet", + "+12.5% Outgoing damage to burning enemies" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + Player playerVictim = (Player) victim; + if(playerVictim.getFireTicks() <= 0) return; + if(Objects.equals(CrankedArmorAPI.getCurrentArmorSet(playerVictim), CrankedArmor.getInstance().getArmorSetRegister().getArmorSetFromID("nightmare"))) return; + super.getDamageHandler().increaseDamage(15, event, "Ignited Holograph"); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicOlympus.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicOlympus.java new file mode 100644 index 0000000..4a50579 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicOlympus.java @@ -0,0 +1,75 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class CosmicOlympus extends StarItem { + @Override + public String getName() { + return "Olympus"; + } + + @Override + public Material getHeldMaterial() { + return Material.BEACON; + } + + @Override + public Material getVisualMaterial() { + return Material.BEACON; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&3&lO&b&ll&3&ly&b&lm&3&lp&b&lu&3&ls"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fThe gates of olympus await you...", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "-3.5% Incoming Damage", + "+3% Outgoing Damage", + "Immune to titan pet", + "66% Holy White Scroll Negation" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + super.getDamageHandler().reduceDamage(3.5, event, "Olympus"); + } + } + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(victim instanceof Player) { + super.getDamageHandler().increaseDamage(3, event, "Olympus"); + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicSantasBeard.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicSantasBeard.java new file mode 100644 index 0000000..8b00a50 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicSantasBeard.java @@ -0,0 +1,142 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import net.crankedpvp.crankedmasks.CrankedMasksAPI; +import net.crankedpvp.crankedutils.utils.Arrow; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.CooldownUtils; +import net.crankedpvp.crankedutils.utils.PotionEffectUtils; +import net.crankedpvp.staritems.cooldowns.SantasPieAbility; +import net.crankedpvp.staritems.cooldowns.SantasPresentAbility; +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class CosmicSantasBeard extends StarItem { + @Override + public String getName() { + return "Santas Beard"; + } + + @Override + public Material getHeldMaterial() { + return Material.SNOW; + } + + @Override + public Material getVisualMaterial() { + return Material.SNOW; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&c&lSantas Beard"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fThe long and fluffy beard", + "&floved by all at Christmas", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList( + "Bypass Abyss slowness", + "Santas Present Ability", + " &7&o(Chance to gain positive effects)", + "Santas Pie Eater Ability", + " &7&o(Chance to gain +6 absorption hearts)" + ); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + + @Override + public void onEquip(Player player) { + } + + @Override + public void onUnequip(Player player) { + } + + + @Override + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) { + if(attacker instanceof Player) { + if(CooldownUtils.isCooldownActive(victim, "santas_beard_pie_eater_ability")) return; + CooldownUtils.registerCooldown(victim, new SantasPieAbility()); + PotionEffectUtils.addExtraPotionEffect(victim, PotionEffectType.ABSORPTION, 3, "santas_beard_pie_eater_ability", 5); + victim.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7You ate ALOT of pies, lots of fat, lots of &eabsorption"))); + } + } + + + private List damageIncrease = new ArrayList<>(); + private List damageDecrease = new ArrayList<>(); + private List rageDamage = new ArrayList<>(); + + @Override + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if(!(victim instanceof Player)) return; + if (event.isCancelled()) return; + + if(damageIncrease.contains(attacker)) super.getDamageHandler().increaseDamage(5, event, "santas_beard_inc"); + if(damageDecrease.contains(victim)) super.getDamageHandler().reduceDamage(5, event, "santas_beard_reduc"); + + double chance = 0.5D; + if(CrankedMasksAPI.hasMaskEquipped(attacker, "santa")) chance *= 2; + if(ThreadLocalRandom.current().nextDouble() > chance) return; + + if(CooldownUtils.isCooldownActive(attacker, "santas_beard_present_ability")) return; + CooldownUtils.registerCooldown(attacker, new SantasPresentAbility()); + int num = ThreadLocalRandom.current().nextInt(1, 4); + switch(num) { + case 1: + damageIncrease.add(attacker); + attacker.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7Santa dropped a present giving you &c+5% outgoing damage"))); + break; + case 2: + damageDecrease.add(attacker); + attacker.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7Santa dropped a present giving you &b-5% incoming damage"))); + break; + case 3: + PotionEffectUtils.addPotionEffect(attacker, PotionEffectType.SPEED, 5, "santas_beard_speed", 5); + attacker.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7Santa dropped a present giving you &aSpeed V"))); + break; + case 4: + rageDamage.add(attacker); + attacker.sendMessage(CC.translate(CC.translate("&c&lSantas Beard &8" + Arrow.arrow() + " &7Santa dropped a present giving you &4+10% Rage Damage"))); + break; + } + + this.getStarItemsPlugin().getServer().getScheduler().runTaskLater(this.getStarItemsPlugin(), () -> this.removeFromAll(attacker), 5 * 20L); + } + + private void removeFromAll(Player player) { + this.rageDamage.remove(player); + this.damageDecrease.remove(player); + this.damageIncrease.remove(player); + } + +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicVoid.java b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicVoid.java new file mode 100644 index 0000000..7c5691f --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/staritems/cosmic/CosmicVoid.java @@ -0,0 +1,61 @@ +package net.crankedpvp.staritems.staritems.cosmic; + +import net.crankedpvp.staritems.struct.ArmorType; +import net.crankedpvp.staritems.struct.StarItem; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.Arrays; +import java.util.List; + +public class CosmicVoid extends StarItem { + @Override + public String getName() { + return "Void"; + } + + @Override + public Material getHeldMaterial() { + return Material.SOUL_SAND; + } + + @Override + public Material getVisualMaterial() { + return Material.SOUL_SAND; + } + + @Override + public short getData() { + return 0; + } + + @Override + public String getDisplayName() { + return "&d&lVoid"; + } + + @Override + public List getLore() { + return Arrays.asList( + "&fConquer the abyss, conquer the void.", + "" + ); + } + + @Override + public List getAbilities() { + return Arrays.asList("Immune to Abyss Enchant", "Bypass Snow Golem Pet"); + } + + @Override + public ArmorType getArmorType() { + return ArmorType.HELMET; + } + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) { + if (victim instanceof Player) { + } + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/struct/ArmorType.java b/StarItems/src/main/java/net/crankedpvp/staritems/struct/ArmorType.java new file mode 100644 index 0000000..df2b8ed --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/struct/ArmorType.java @@ -0,0 +1,5 @@ +package net.crankedpvp.staritems.struct; + +public enum ArmorType { + HELMET, CHESTPLATE, LEGGINGS, BOOTS, SWORD, AXE, BOW, WEAPON; +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/struct/StarItem.java b/StarItems/src/main/java/net/crankedpvp/staritems/struct/StarItem.java new file mode 100644 index 0000000..e1c1bf4 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/struct/StarItem.java @@ -0,0 +1,116 @@ +package net.crankedpvp.staritems.struct; + +import de.tr7zw.nbtapi.NBTCompound; +import de.tr7zw.nbtapi.NBTItem; +import lombok.Getter; +import net.crankedpvp.crankedutils.CrankedUtils; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.DamageHandler; +import net.crankedpvp.crankedutils.utils.items.ItemBuilder; +import net.crankedpvp.staritems.StarItemsPlugin; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Locale; + +public abstract class StarItem implements Listener { + + @Getter + private final DamageHandler damageHandler; + @Getter + private final StarItemsPlugin starItemsPlugin; + + public StarItem() { + this.damageHandler = CrankedUtils.instance.getDamageHandler(); + this.starItemsPlugin = StarItemsPlugin.getInstance(); + } + + + public abstract String getName(); + + public abstract Material getHeldMaterial(); + + public abstract Material getVisualMaterial(); + + public abstract short getData(); + + public abstract String getDisplayName(); + + public abstract List getLore(); + + public abstract List getAbilities(); + + public abstract ArmorType getArmorType(); + + public String getID() { + return this.getName().toLowerCase(Locale.ROOT).replace(" ", ""); + } + + + public void onOutgoingDamage(Player attacker, Entity victim, EntityDamageByEntityEvent event) {} + + public void onIncomingDamage(Player victim, Entity attacker, EntityDamageByEntityEvent event) {} + + public void onEquip(Player player) {} + + public void onUnequip(Player player) {} + + + + + public ItemStack buildItem() { + ItemBuilder itemBuilder = new ItemBuilder(this.getHeldMaterial(), 1, getData(), getDisplayName()); + itemBuilder.setLore(getLore()); + itemBuilder.addLoreLine("&eAbilities:"); + getAbilities().forEach(ability -> itemBuilder.addLoreLine(" &f• " + ability)); + itemBuilder.addLore("", "&7&oAttach this item to any " + getMaterialStringForLore(), + "&7&oto give it a visual override!", + "", + "&7&oTo attach, place this item on a " + getMaterialStringForLore(), + "&7&oOnce attached, it cannot be removed!"); + + NBTItem wrapper = new NBTItem(itemBuilder.colorize().build()); + wrapper.setString("cosmicType", "staritem"); + wrapper.setString("starItemType", this.getID()); + NBTCompound cosmicData = wrapper.getOrCreateCompound("cosmicData"); + cosmicData.setString("starItemType", this.getID()); + return wrapper.getItem(); + } + + private String getMaterialStringForLore() { + return this.isWeapon() ? this.getArmorType().name().toLowerCase(Locale.ROOT) : this.isBow() ? "bow" : + (this.getArmorType() == ArmorType.LEGGINGS || this.getArmorType() == ArmorType.BOOTS) + ? "pair of " + this.getArmorType().name().toLowerCase(Locale.ROOT) : + this.getArmorType().name().toLowerCase(Locale.ROOT); + + } + + private boolean isBow() { + return this.getArmorType() == ArmorType.BOW; + } + + private boolean isWeapon() { + return (this.getArmorType() == ArmorType.AXE || this.getArmorType() == ArmorType.SWORD || this.getArmorType() == ArmorType.WEAPON); + } + + public ItemStack apply(ItemStack itemStack) { + ItemBuilder clickedItem = new ItemBuilder(itemStack); + clickedItem.addLore("&f&lSTAR ITEM: " + this.getDisplayName()); + NBTItem clickedItemNBT = new NBTItem(clickedItem.colorize().build()); + clickedItemNBT.setString("starItem", this.getID()); + return clickedItemNBT.getItem(); + } + + public ItemStack unapply(ItemStack itemStack) { + ItemBuilder clickedItem = new ItemBuilder(itemStack); + clickedItem.removeLoreLine(CC.translate("&f&lSTAR ITEM: " + this.getDisplayName())); + NBTItem clickedItemNBT = new NBTItem(clickedItem.colorize().build()); + clickedItemNBT.removeKey("starItem"); + return clickedItemNBT.getItem(); + } +} diff --git a/StarItems/src/main/java/net/crankedpvp/staritems/struct/StarItemManager.java b/StarItems/src/main/java/net/crankedpvp/staritems/struct/StarItemManager.java new file mode 100644 index 0000000..21490f6 --- /dev/null +++ b/StarItems/src/main/java/net/crankedpvp/staritems/struct/StarItemManager.java @@ -0,0 +1,166 @@ +package net.crankedpvp.staritems.struct; + +import com.google.common.collect.Maps; +import lombok.Getter; +import net.crankedpvp.staritems.StarItemsPlugin; +import net.crankedpvp.staritems.staritems.*; +import net.crankedpvp.staritems.staritems.Void; +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; + +import java.util.*; + +public class StarItemManager { + + private final StarItemsPlugin plugin; + private final Map starItems; + @Getter + private final Map> cachedPlayers; + public StarItemManager(StarItemsPlugin plugin) { + this.plugin = plugin; + this.starItems = Maps.newConcurrentMap(); + this.cachedPlayers = Maps.newConcurrentMap(); + } + + public void initialize() { + + this.registerAll( + new Absence(), + new AngelBoots(), + new BlackoutBlindfold(), + new BlurredSoaker(), + new Combo(), + new Discharge(), + new Frostbite(), + new GalacticVisor(), + new GloopGetaway(), + new GoldenEyeBandage(), + new HermesBoots(), + new IgnitedHolograph(), + new Olympus(), + new PortableBard(), + new SantasBeard(), + new Void() + ); + /* + + this.registerAll( + new CosmicAbsence(), new CosmicAngelBoots(), new CosmicDischarge(), + new CosmicGalacticVisor(), new CosmicHermesBoots(), new CosmicIgnitedHolograph(), + new CosmicOlympus(), new CosmicSantasBeard(), new CosmicVoid() + ); + + */ + + + /* + this.registerAll( + new Absence(), new Discharge(), new HermesBoots(), + new IgnitedHolograph(), new SantasBeard() + + ); + this.register(new Olympus()); + this.registerAll(new Void(), new AngelBoots()); + this.registerAll(new PortableBard(), new Combo()); + + this.registerAll(new BlurredSoaker(), new GalacticVisor(), new GloopGetaway(), new GoldenEyeBandage(), new BlackoutBlindfold()); + + this.registerAll(new DeterioratedGolem(), new Frostbite()); + + */ + } + + public void removeFromCacheCompletely(Player player) { + this.cachedPlayers.remove(player); + } + + public void addToCache(Player player, List starItems) { + this.cachedPlayers.put(player, starItems); + } + + public void addToCache(Player player, StarItem starItem) { + if(this.cachedPlayers.containsKey(player)) { + if(this.cachedPlayers.get(player).size() <= 0) { + this.cachedPlayers.put(player, new ArrayList<>(Arrays.asList(starItem))); + return; + } + List starItems = this.cachedPlayers.get(player); + if(!starItems.contains(starItem)) starItems.add(starItem); + this.cachedPlayers.put(player, starItems); + return; + } + this.cachedPlayers.put(player, new ArrayList<>(Arrays.asList(starItem))); + } + + public void removeFromCache(Player player, StarItem starItem) { + if(this.cachedPlayers.containsKey(player)) { + if(this.cachedPlayers.get(player).contains(starItem)) { + List starItems = this.cachedPlayers.get(player); + if(starItems.size() == 1) { + this.removeFromCacheCompletely(player); + return; + } + starItems.remove(starItem); + this.cachedPlayers.put(player, starItems); + return; + } + } + this.removeFromCacheCompletely(player); + } + + public void registerAll(StarItem... starItems) { + for (StarItem starItem : starItems) { + this.register(starItem); + } + } + + public void register(StarItem starItem) { + try { + this.starItems.put(starItem.getID(), starItem); + this.plugin.getServer().getPluginManager().registerEvents(starItem, this.plugin); + this.plugin.getLogger().info("Successfully registered star item: " + starItem.getID()); + } catch (Exception e) { + this.plugin.getLogger().warning("Failed to register star item: " + starItem.getID()); + System.out.println(e.getMessage()); + } + } + + public void unregisterAll() { + this.starItems.clear(); + } + + public void unregister(StarItem starItem) { + this.starItems.remove(starItem.getID()); + } + + public void reload() { + this.unregisterAll(); + this.initialize(); + } + + public boolean isStarItem(String name) { + return (this.getStarItemFromID(name) != null); + } + + public StarItem getStarItemFromID(String id) { + Validate.notNull(id); + Validate.notEmpty(id); + return this.starItems.get(id.toLowerCase()); + } + + public StarItem getStarItemFromName(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + name = this.getStarItemIDFromName(name); + return this.starItems.get(name.toLowerCase()); + } + + public String getStarItemIDFromName(String name) { + return name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Collection getStarItems() { + return Collections.unmodifiableCollection(this.starItems.values()); + } + +} diff --git a/StarItems/src/main/resources/plugin.yml b/StarItems/src/main/resources/plugin.yml new file mode 100644 index 0000000..6f4976b --- /dev/null +++ b/StarItems/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: CrankedStarItems +main: net.crankedpvp.staritems.StarItemsPlugin +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/StorageUtils/pom.xml b/StorageUtils/pom.xml new file mode 100644 index 0000000..9c97cd7 --- /dev/null +++ b/StorageUtils/pom.xml @@ -0,0 +1,55 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + StorageUtils + + + 8 + 8 + + + + + com.google.code.gson + gson + 2.9.0 + + + + + + StorageUtil + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + + shade + + + + + true + + + com.google + net.crankedpvp.storageutils + + + + + + + \ No newline at end of file diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/StorageUtils.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/StorageUtils.java new file mode 100644 index 0000000..e06e38b --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/StorageUtils.java @@ -0,0 +1,46 @@ +package net.crankedpvp.storageutils; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import lombok.Getter; +import net.crankedpvp.storageutils.utils.*; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; + +import java.lang.reflect.Type; +import java.util.List; + +@Getter +public class StorageUtils extends JavaPlugin { + + @Getter + private static StorageUtils instance; + private final Type listType = new TypeToken>(){}.getType(); + + private final Gson gson = new GsonBuilder() + .setPrettyPrinting() + .serializeNulls() + .registerTypeAdapter(ItemStack.class, new ItemStackSerializer()).setLenient() + .registerTypeAdapter(ItemStack.class, new ItemStackDeserializer()).setLenient() + .registerTypeAdapter(ItemStack[].class, new ItemStackArraySerializer()).setLenient() + .registerTypeAdapter(ItemStack[].class, new ItemStackArrayDeserializer()).setLenient() + .registerTypeAdapter(Location.class, new LocationSerializer()).setLenient() + .registerTypeAdapter(Location.class, new LocationDeserializer()).setLenient() + .registerTypeAdapter(listType, new ItemStackArrayListSerializer()).setLenient() + .registerTypeAdapter(listType, new ItemStackArrayListDeserializer()).setLenient() + .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) + .create(); + + @Override + public void onEnable() { + instance = this; + } + + @Override + public void onDisable() { + instance = null; + } +} \ No newline at end of file diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/struct/NewKeyToSave.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/struct/NewKeyToSave.java new file mode 100644 index 0000000..33171dd --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/struct/NewKeyToSave.java @@ -0,0 +1,8 @@ +package net.crankedpvp.storageutils.struct; + +public interface NewKeyToSave { + + T getKey(); + + void setKey(T key); +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/struct/NewSaveLoadManager.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/struct/NewSaveLoadManager.java new file mode 100644 index 0000000..bfc6763 --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/struct/NewSaveLoadManager.java @@ -0,0 +1,142 @@ +package net.crankedpvp.storageutils.struct; + +import com.google.gson.Gson; +import lombok.Getter; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; + +public abstract class NewSaveLoadManager> { + + private final File dataDirectory; + private final JavaPlugin plugin; + private final Gson gson; + private final Class clazz; + @Getter + private final Map cache; + + protected NewSaveLoadManager(JavaPlugin plugin, Gson gson, String dataDirectory, Class clazz) { + this.plugin = plugin; + this.gson = gson; + this.clazz = clazz; + this.dataDirectory = new File(plugin.getDataFolder(), dataDirectory); + this.cache = new HashMap<>(); + } + + + public void loadAll() { + if (!dataDirectory.exists()) { + dataDirectory.mkdirs(); + } + + File[] validKitFiles = dataDirectory.listFiles((dir,name) -> name.endsWith(".json")); + + if (validKitFiles == null) { + return; + } + + for (File file : validKitFiles) { + this.load(file); + } + } + + public void saveAll() { + if (!dataDirectory.exists()) { + dataDirectory.mkdirs(); + } + + for (Map.Entry entry : cache.entrySet()) { + this.save(this.serialize(entry.getKey()), entry.getValue()); + } + + } + + public void purge() { + if (!dataDirectory.exists()) { + dataDirectory.mkdirs(); + } + + for (File file : Objects.requireNonNull(dataDirectory.listFiles())) { + K deserialize = this.deserialize(file.getName().substring(0,file.getName().length()-5)); + if (!this.containsKey(deserialize)) { + file.deleteOnExit(); + } + } + } + + public void load(String dataDirectory, String key) { + this.load(new File(this.plugin.getDataFolder() + dataDirectory, key + ".json")); + } + + public void load(File file) { + String fileName = file.getName(); + int fileNameLength = fileName.length(); + String key = fileName.substring(0,fileNameLength-5); + + try (FileReader reader = new FileReader(file)) { + V valueFromJson = this.gson.fromJson(reader, clazz); + if (valueFromJson == null) { + return; + } + valueFromJson.setKey(this.deserialize(key)); + this.cache.put(this.deserialize(key), valueFromJson); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void save(String key, V v) { + File file = new File(dataDirectory,key + ".json"); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + String jsonString = this.gson.toJson(v); + try (FileWriter writer = new FileWriter(file)) { + writer.write(jsonString); + writer.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public V getFromCache(K key) { + return this.cache.get(key); + } + + public void addToCache(V v) { + this.cache.put(v.getKey(), v); + } + + public void removeFromCache(V v) { + this.cache.remove(v.getKey()); + } + + public void removeFromCache(K key) { + this.cache.remove(key); + } + + public boolean containsKey(K key) { + return this.cache.containsKey(key); + } + + public Set getCacheKeys() { + return this.cache.keySet(); + } + + public Collection getCacheValues() { + return this.cache.values(); + } + + public abstract String serialize(K key); + + public abstract K deserialize(String key); +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayDeserializer.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayDeserializer.java new file mode 100644 index 0000000..7c220b0 --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayDeserializer.java @@ -0,0 +1,30 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.*; +import lombok.SneakyThrows; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +public class ItemStackArrayDeserializer implements JsonDeserializer { + + @SneakyThrows + @Override + public ItemStack[] deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + JsonArray jsonArray = ((JsonArray) jsonElement); + List items = new ArrayList<>(); + + for (JsonElement element : jsonArray) { + try { + items.add(jsonDeserializationContext.deserialize(element.getAsJsonPrimitive(), ItemStack.class)); + } catch (IllegalStateException exception) { + exception.printStackTrace(); + } + } + + + return items.toArray(new ItemStack[] {}); + } +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayListDeserializer.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayListDeserializer.java new file mode 100644 index 0000000..503d826 --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayListDeserializer.java @@ -0,0 +1,30 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.*; +import lombok.SneakyThrows; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +public class ItemStackArrayListDeserializer implements JsonDeserializer> { + + @SneakyThrows + @Override + public List deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + JsonArray jsonArray = ((JsonArray) jsonElement); + List items = new ArrayList<>(); + + for (JsonElement element : jsonArray) { + try { + items.add(jsonDeserializationContext.deserialize(element.getAsJsonPrimitive(), ItemStack.class)); + } catch (IllegalStateException exception) { + exception.printStackTrace(); + } + } + + + return items; + } +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayListSerializer.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayListSerializer.java new file mode 100644 index 0000000..f69b44c --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArrayListSerializer.java @@ -0,0 +1,27 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import lombok.SneakyThrows; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Type; +import java.util.List; + +public class ItemStackArrayListSerializer implements JsonSerializer> { + + @SneakyThrows + @Override + public JsonElement serialize(List itemStacks, Type type, JsonSerializationContext jsonSerializationContext) { + + JsonArray jsonArray = new JsonArray(); + + for (ItemStack itemStack : itemStacks) { + jsonArray.add(jsonSerializationContext.serialize(itemStack, ItemStack.class)); + } + + return jsonArray; + } +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArraySerializer.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArraySerializer.java new file mode 100644 index 0000000..a87c88c --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackArraySerializer.java @@ -0,0 +1,26 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import lombok.SneakyThrows; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Type; + +public class ItemStackArraySerializer implements JsonSerializer { + + @SneakyThrows + @Override + public JsonElement serialize(ItemStack[] itemStacks, Type type, JsonSerializationContext jsonSerializationContext) { + + JsonArray jsonArray = new JsonArray(); + + for (ItemStack itemStack : itemStacks) { + jsonArray.add(jsonSerializationContext.serialize(itemStack, ItemStack.class)); + } + + return jsonArray; + } +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackDeserializer.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackDeserializer.java new file mode 100644 index 0000000..b23a178 --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackDeserializer.java @@ -0,0 +1,32 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import lombok.SneakyThrows; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.lang.reflect.Type; + +public class ItemStackDeserializer implements JsonDeserializer { + + public static ItemStack deserialize(String base64) throws IOException, ClassNotFoundException { + byte[] data = Base64Coder.decodeLines(base64); + ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); + BukkitObjectInputStream in = new BukkitObjectInputStream(bytesIn); + ItemStack itemStack = (ItemStack) in.readObject(); + in.close(); + return itemStack; + } + + @SneakyThrows + @Override + public ItemStack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + return deserialize(jsonElement.getAsJsonPrimitive().getAsString()); + } +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackSerializer.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackSerializer.java new file mode 100644 index 0000000..234bffe --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/ItemStackSerializer.java @@ -0,0 +1,31 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.*; +import lombok.SneakyThrows; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Type; + +public class ItemStackSerializer implements JsonSerializer { + + public static String serialize(ItemStack itemStack) throws IOException { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + BukkitObjectOutputStream out = new BukkitObjectOutputStream(bytesOut); + out.writeObject(itemStack); + out.flush(); + out.close(); + return Base64Coder.encodeLines(bytesOut.toByteArray()); + } + + @SneakyThrows + @Override + public JsonElement serialize(ItemStack itemStack, Type type, JsonSerializationContext jsonSerializationContext) { + String serialized = serialize(itemStack); + JsonObject jsonElement = (JsonObject) JsonParser.parseString("{ \"item\": \"" + serialized + "\" }"); + return jsonElement.getAsJsonPrimitive("item"); + } +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/KeyToSave.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/KeyToSave.java new file mode 100644 index 0000000..b312b98 --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/KeyToSave.java @@ -0,0 +1,8 @@ +package net.crankedpvp.storageutils.utils; + +public interface KeyToSave { + + String getKey(); + + void setKey(String key); +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/LocationDeserializer.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/LocationDeserializer.java new file mode 100644 index 0000000..2bbc26b --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/LocationDeserializer.java @@ -0,0 +1,36 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import lombok.SneakyThrows; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + +import java.lang.reflect.Type; + +public class LocationDeserializer implements JsonDeserializer { + + public static Location deserialize(String s) { + if (s == null || s.trim().equals("")) { + return null; + } + final String[] parts = s.split(":"); + if (parts.length == 4) { + final World w = Bukkit.getServer().getWorld(parts[0]); + final int x = Integer.parseInt(parts[1]); + final int y = Integer.parseInt(parts[2]); + final int z = Integer.parseInt(parts[3]); + return new Location(w, x, y, z); + } + return null; + } + + @SneakyThrows + @Override + public Location deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + return deserialize(jsonElement.getAsJsonPrimitive().getAsString()); + } +} \ No newline at end of file diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/LocationSerializer.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/LocationSerializer.java new file mode 100644 index 0000000..92a3833 --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/LocationSerializer.java @@ -0,0 +1,30 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.*; +import lombok.SneakyThrows; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Type; + +public class LocationSerializer implements JsonSerializer { + + public static String serialize(Location obj) { + if (obj == null) { + return ""; + } + return obj.getWorld().getName() + ":" + obj.getBlockX() + ":" + obj.getBlockY() + ":" + obj.getBlockZ(); + } + + @SneakyThrows + @Override + public JsonElement serialize(Location location, Type type, JsonSerializationContext jsonSerializationContext) { + String serialized = serialize(location); + JsonObject jsonElement = (JsonObject) JsonParser.parseString("{ \"location\": \"" + serialized + "\" }"); + return jsonElement.getAsJsonPrimitive("location"); + } +} diff --git a/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/SaveLoadManager.java b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/SaveLoadManager.java new file mode 100644 index 0000000..79dd204 --- /dev/null +++ b/StorageUtils/src/main/java/net/crankedpvp/storageutils/utils/SaveLoadManager.java @@ -0,0 +1,120 @@ +package net.crankedpvp.storageutils.utils; + +import com.google.gson.Gson; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public abstract class SaveLoadManager { + + private final File dataDirectory; + private final Gson gson; + private final Class clazz; + private final Map cache; + + protected SaveLoadManager(JavaPlugin plugin, Gson gson, String dataDirectory, Class clazz) { + this.gson = gson; + this.clazz = clazz; + this.dataDirectory = new File(plugin.getDataFolder(), dataDirectory); + this.cache = new HashMap<>(); + } + + + public void loadAll() { + if (!dataDirectory.exists()) { + dataDirectory.mkdirs(); + } + + File[] validKitFiles = dataDirectory.listFiles((dir,name) -> name.endsWith(".json")); + + if (validKitFiles == null) { + return; + } + + for (File file : validKitFiles) { + this.load(file); + } + } + + public void saveAll() { + if (!dataDirectory.exists()) { + dataDirectory.mkdirs(); + } + + for (Map.Entry entry : cache.entrySet()) { + this.save(entry.getKey(), entry.getValue()); + } + + } + + public void load(File file) { + String fileName = file.getName(); + int fileNameLength = fileName.length(); + String key = fileName.substring(0,fileNameLength-5); + + try (FileReader reader = new FileReader(file)) { + T t = this.gson.fromJson(reader, clazz); + if (t == null) { + return; + } + t.setKey(key); + cache.put(key, t); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void save(String key, T t) { + File file = new File(dataDirectory,key + ".json"); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + String jsonString = this.gson.toJson(t); + try (FileWriter writer = new FileWriter(file)) { + writer.write(jsonString); + writer.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + public T getFromCache(String key) { + return this.cache.get(key); + } + + public void addToCache(T t) { + this.cache.put(t.getKey(), t); + } + + public void removeFromCache(T t) { + this.cache.remove(t.getKey()); + } + + public void removeFromCache(String key) { + this.cache.remove(key); + } + + public boolean containsKey(String key) { + return this.cache.containsKey(key); + } + + public Set getCacheKeys() { + return this.cache.keySet(); + } + + public Collection getCacheValues() { + return this.cache.values(); + } +} diff --git a/StorageUtils/src/main/resources/plugin.yml b/StorageUtils/src/main/resources/plugin.yml new file mode 100644 index 0000000..ffce19d --- /dev/null +++ b/StorageUtils/src/main/resources/plugin.yml @@ -0,0 +1,5 @@ +name: StorageUtil +main: net.crankedpvp.storageutils.StorageUtils +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ \ No newline at end of file diff --git a/Teams/pom.xml b/Teams/pom.xml new file mode 100644 index 0000000..7bbd13d --- /dev/null +++ b/Teams/pom.xml @@ -0,0 +1,26 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + Teams + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + + \ No newline at end of file diff --git a/Teams/src/main/java/net/crankedpvp/teams/Teams.java b/Teams/src/main/java/net/crankedpvp/teams/Teams.java new file mode 100644 index 0000000..ec49b3d --- /dev/null +++ b/Teams/src/main/java/net/crankedpvp/teams/Teams.java @@ -0,0 +1,37 @@ +package net.crankedpvp.teams; + +import lombok.Getter; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.teams.commands.TeamCommand; +import net.crankedpvp.teams.listeners.PlayerDisconnectListener; +import net.crankedpvp.teams.struct.TeamManager; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class Teams extends JavaPlugin { + + @Getter + private static Teams instance; + + @Getter + private TeamManager teamManager; + + @Override + public void onEnable() { + instance = this; + this.teamManager = new TeamManager(this); + + CommandManager commandManager = new CommandManager(this); + commandManager.register(new TeamCommand(this)); + + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new PlayerDisconnectListener(this), this); + } + + + @Override + public void onDisable() { + this.teamManager.getTeams().clear(); + instance = null; + } +} diff --git a/Teams/src/main/java/net/crankedpvp/teams/TeamsAPI.java b/Teams/src/main/java/net/crankedpvp/teams/TeamsAPI.java new file mode 100644 index 0000000..36b4454 --- /dev/null +++ b/Teams/src/main/java/net/crankedpvp/teams/TeamsAPI.java @@ -0,0 +1,82 @@ +package net.crankedpvp.teams; + +import net.crankedpvp.teams.struct.Team; +import net.crankedpvp.teams.struct.TeamManager; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class TeamsAPI { + + private final static TeamManager teamManager = Teams.getInstance().getTeamManager(); + + public static boolean isTeamLeader(Player player) { + return teamManager.isTeamLeader(player); + } + + public static List getTeams() { + return teamManager.getTeams(); + } + + public static Team getTeamFromPlayer(Player player) { + return teamManager.getTeamFromPlayer(player); + } + + public static boolean hasTeam(Player player) { + return teamManager.getTeamFromPlayer(player) != null; + } + + public static Player getTeamLeader(Team team) { + return team.getLeader(); + } + + public static Player getTeamLeader(Player player) { + return teamManager.getTeamFromPlayer(player).getLeader(); + } + + public static List getAllPlayersInTeam(Player player) { + List players = new ArrayList<>(); + Team team = teamManager.getTeamFromPlayer(player); + players.add(team.getLeader()); + if(!team.getMembers().isEmpty()) players.addAll(team.getMembers()); + + return players; + } + + public static List getAllPlayersInTeam(Team team) { + List players = new ArrayList<>(); + players.add(team.getLeader()); + players.addAll(team.getMembers()); + return players; + } + + public static int getTeamSize(Player player) { + return teamManager.getTeamFromPlayer(player).getMembers().size() + 1; + } + + public static int getTeamSize(Team team) { + return team.getMembers().size() + 1; + } + + public static Team createTeam(Player player) { + Team team = new Team(player, new ArrayList<>()); + teamManager.getTeams().add(team); + return team; + } + + public static void removePlayerFromTeam(Player player) { + Team team = getTeamFromPlayer(player); + List members = team.getMembers(); + members.remove(player); + team.setMembers(members); + } + + public static void deleteTeam(Player player) { + teamManager.getTeams().remove(getTeamFromPlayer(player)); + } + + public static void deleteTeam(Team team) { + teamManager.getTeams().remove(team); + } +} diff --git a/Teams/src/main/java/net/crankedpvp/teams/commands/TeamCommand.java b/Teams/src/main/java/net/crankedpvp/teams/commands/TeamCommand.java new file mode 100644 index 0000000..e53f1be --- /dev/null +++ b/Teams/src/main/java/net/crankedpvp/teams/commands/TeamCommand.java @@ -0,0 +1,298 @@ +package net.crankedpvp.teams.commands; + +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import net.crankedpvp.crankedutils.utils.CC; +import net.crankedpvp.crankedutils.utils.Clickable; +import net.crankedpvp.teams.Teams; +import net.crankedpvp.teams.TeamsAPI; +import net.crankedpvp.teams.struct.Team; +import net.crankedpvp.teams.struct.TeamManager; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.StringJoiner; + +@Command("team") +@Alias({"teams", "party"}) +public class TeamCommand extends CommandBase { + + private final Teams plugin; + private final TeamManager teamManager; + public TeamCommand(Teams plugin) { + this.plugin = plugin; + this.teamManager = this.plugin.getTeamManager(); + } + + @Default + public void defaultCommand(CommandSender commandSender) { + sendHelpMessage(commandSender); + } + + @SubCommand("help") + public void helpCommand(CommandSender commandSender) { + sendHelpMessage(commandSender); + } + + @SubCommand("view") + @Alias({"list", "info"}) + public void viewCommand(CommandSender commandSender, @Optional Player player) { + Player sender = (Player) commandSender; + if(player == null) { + player = sender; + } + if(!this.teamManager.hasTeam(player)) { + sender.sendMessage(CC.translate("&eThe player " + player.getName() + " does not have a team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + Team team = this.teamManager.getTeamFromPlayer(player); + StringJoiner stringJoiner = new StringJoiner(", "); + team.getMembers().forEach(member -> stringJoiner.add(member.getName())); + + sender.sendMessage(CC.translate("&a" + player.getName() + "'s Team")); + sender.sendMessage(CC.translate(" &aLeader: &f" + team.getLeader().getName())); + sender.sendMessage(CC.translate(" &aMembers: &f" + stringJoiner)); + sender.sendMessage(""); + + } + + @SubCommand("disband") + public void disbandCommand(CommandSender commandSender) { + Player sender = (Player) commandSender; + + if(!this.teamManager.hasTeam(sender)) { + sender.sendMessage(CC.translate("&cYou do not have a team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(!TeamsAPI.isTeamLeader(sender)) { + sender.sendMessage(CC.translate("&cYou are not the leader of your team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + this.teamManager.getTeams().remove(TeamsAPI.getTeamFromPlayer(sender)); + sender.sendMessage(CC.translate("&aYour team has been successfully disbanded")); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @SubCommand("invite") + @WrongUsage("&eUsage: /team invite ") + public void inviteCommand(CommandSender commandSender, Player player) { + Player sender = (Player) commandSender; + + if(!this.teamManager.hasTeam(sender)) { + this.teamManager.getTeams().add(new Team(sender, new ArrayList<>())); + sender.sendMessage(CC.translate("&eYour team has been created")); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + if(!this.teamManager.isTeamLeader(sender)) { + sender.sendMessage(CC.translate("&eYou are not the leader of your team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(player == null || !player.isOnline()) { + sender.sendMessage(CC.translate("&cThat player is not online and cannot be invited")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(sender == player) { + sender.sendMessage(CC.translate("&cYou cannot invite yourself to your own team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + Team sendersTeam = this.teamManager.getTeamFromPlayer(sender); + if(this.teamManager.getTeamsInvitedTo().containsKey(player) && this.teamManager.getTeamsInvitedTo().get(player).contains(sendersTeam)) { + sender.sendMessage(CC.translate("&eYou have already invited this player")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + player.sendMessage(CC.translate("&eInvited to join " + sender.getName() + "'s team")); + Clickable clickable = new Clickable(CC.translate("&eUse /team join " + sender.getName() + " to join or click &7here"), + CC.translate("&7Click to join " + sender.getName() + "'s team"), + "/team join " + sender.getName()); + clickable.sendToPlayer(player); + player.sendMessage(CC.translate("&eYou have 2 minutes to accept")); + sender.sendMessage(CC.translate("&eYou invited " + player.getName() + " to join your team")); + + if(!this.teamManager.getTeamsInvitedTo().containsKey(player) || this.teamManager.getTeamsInvitedTo().get(player).isEmpty()) { + this.teamManager.getTeamsInvitedTo().put(player, new ArrayList<>(Arrays.asList(sendersTeam))); + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> removePlayerFromInvitedTeam(player, sendersTeam), 20 * 120L); + return; + } + List teamsPlayerIsInvitedTo = this.teamManager.getTeamsInvitedTo().get(player); + teamsPlayerIsInvitedTo.add(sendersTeam); + this.teamManager.getTeamsInvitedTo().put(player, teamsPlayerIsInvitedTo); + this.plugin.getServer().getScheduler().runTaskLater(this.plugin, () -> removePlayerFromInvitedTeam(player, sendersTeam), 20 * 120L); + } + + private void removePlayerFromInvitedTeam(Player player, Team sendersTeam) { + if(this.teamManager.getTeamsInvitedTo().get(player).equals(new ArrayList<>(Arrays.asList(sendersTeam)))) { + this.teamManager.getTeamsInvitedTo().remove(player); + return; + } + List teamsPlayerIsInvitedTo = this.teamManager.getTeamsInvitedTo().get(player); + teamsPlayerIsInvitedTo.remove(sendersTeam); + this.teamManager.getTeamsInvitedTo().put(player, teamsPlayerIsInvitedTo); + player.sendMessage(CC.translate("&cYour team invite to join " + sendersTeam.getLeader() + "'s team has expired")); + } + + @SubCommand("join") + @WrongUsage("&e/team join ") + public void joinCommand(CommandSender commandSender, Player player) { + Player sender = (Player) commandSender; + if(this.teamManager.hasTeam(sender)) { + sender.sendMessage(CC.translate("&cYou are already in a team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(!this.teamManager.hasTeam(player)) { + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + sender.sendMessage(CC.translate("&cThis is not a valid team to join")); + } + + Team teamToJoin = this.teamManager.getTeamFromPlayer(player); + if(this.teamManager.getTeamsInvitedTo().get(sender).contains(teamToJoin)) { + TeamsAPI.getAllPlayersInTeam(teamToJoin).forEach(teamPlayer -> teamPlayer.sendMessage(CC.translate("&eThe player &7" + sender.getName() + " &ejoined your team"))); + List newMembers = teamToJoin.getMembers(); + newMembers.add(sender); + teamToJoin.setMembers(newMembers); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + sender.sendMessage(CC.translate("&eYou joined " + player.getName() + "'s team")); + return; + } + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + sender.sendMessage(CC.translate("&cYou do not have an invite to this team")); + } + + @SubCommand("leave") + public void leaveCommand(CommandSender commandSender) { + Player sender = (Player) commandSender; + if(!this.teamManager.hasTeam(sender)) { + sender.sendMessage(CC.translate("&cYou are not apart of a team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(this.teamManager.getTeamFromPlayer(sender).getLeader() == sender) { + sender.sendMessage(CC.translate("&cYou cannot leave your own team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + TeamsAPI.removePlayerFromTeam(sender); + sender.sendMessage(CC.translate("&aYou have left your team")); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + + + } + + @SubCommand("leader") + @WrongUsage("&eUsage: /team leader ") + public void leaderCommand(CommandSender commandSender, Player player) { + Player sender = (Player) commandSender; + + if(!this.teamManager.hasTeam(sender)) { + sender.sendMessage(CC.translate("&cYou are not in a team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(!this.teamManager.isTeamLeader(sender)) { + sender.sendMessage(CC.translate("&cYou are not the leader of your team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(sender == player) { + sender.sendMessage(CC.translate("&cYou cannot transfer team ownership to yourself")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + + if(!player.isOnline()) { + sender.sendMessage(CC.translate("&cYou cannot transfer ownership to an offline player")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + Team team = this.teamManager.getTeamFromPlayer(player); + + if(team != this.teamManager.getTeamFromPlayer(sender)) { + sender.sendMessage(CC.translate("&cThat player is not apart of your team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + team.setLeader(player); + team.getMembers().remove(player); + team.getMembers().add(sender); + + sender.sendMessage(CC.translate("&aYou have given the player " + player.getName() + " leader of your team")); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + player.sendMessage(CC.translate("&aYou have been given leader of " + sender.getName() + "'s team")); + player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + } + + @SubCommand("kick") + @WrongUsage("&eUsage: /team kick ") + public void kickCommand(CommandSender commandSender, Player player) { + Player sender = (Player) commandSender; + + if(!this.teamManager.hasTeam(sender)) { + sender.sendMessage(CC.translate("&eYou are not apart of a team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(!this.teamManager.isTeamLeader(sender)) { + sender.sendMessage(CC.translate("&eYou are not the leader of your team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(sender == player) { + sender.sendMessage(CC.translate("&cYou cannot kick yourself from your own team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(this.teamManager.getTeamFromPlayer(sender).getMembers().contains(player)) { + this.teamManager.getTeamFromPlayer(sender).getMembers().remove(player); + sender.sendMessage(CC.translate("&eYou have kicked " + player.getName() + " from your team")); + sender.playSound(sender.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F); + return; + } + sender.sendMessage(CC.translate("&eThe player " + player.getName() + " is not apart of your team")); + sender.playSound(sender.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + + } + + private void sendHelpMessage(CommandSender commandSender) { + commandSender.sendMessage(CC.translate("&aTeams")); + commandSender.sendMessage(CC.translate(" &a/team invite ")); + commandSender.sendMessage(CC.translate(" &a/team kick ")); + commandSender.sendMessage(CC.translate(" &a/team join ")); + commandSender.sendMessage(CC.translate(" &a/team leave")); + commandSender.sendMessage(CC.translate(" &a/team leader ")); + commandSender.sendMessage(CC.translate(" &a/team disband")); + commandSender.sendMessage(CC.translate(" &a/team view")); + commandSender.sendMessage(CC.translate("")); + Player player = (Player) commandSender; + player.playSound(player.getLocation(), Sound.CLICK, 2.0F, 2.0F); + } +} diff --git a/Teams/src/main/java/net/crankedpvp/teams/listeners/PlayerDisconnectListener.java b/Teams/src/main/java/net/crankedpvp/teams/listeners/PlayerDisconnectListener.java new file mode 100644 index 0000000..1be8544 --- /dev/null +++ b/Teams/src/main/java/net/crankedpvp/teams/listeners/PlayerDisconnectListener.java @@ -0,0 +1,28 @@ +package net.crankedpvp.teams.listeners; + +import net.crankedpvp.teams.Teams; +import net.crankedpvp.teams.TeamsAPI; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; + +public class PlayerDisconnectListener implements Listener { + + private final Teams plugin; + public PlayerDisconnectListener(Teams plugin) { + this.plugin = plugin; + } + + @EventHandler + public void disconnect(PlayerQuitEvent event) { + if(event.getPlayer() == null) return; + Player player = event.getPlayer(); + if(!TeamsAPI.hasTeam(player)) return; + if(TeamsAPI.isTeamLeader(player)) { + TeamsAPI.deleteTeam(player); + return; + } + TeamsAPI.removePlayerFromTeam(player); + } +} diff --git a/Teams/src/main/java/net/crankedpvp/teams/struct/Team.java b/Teams/src/main/java/net/crankedpvp/teams/struct/Team.java new file mode 100644 index 0000000..3aaba73 --- /dev/null +++ b/Teams/src/main/java/net/crankedpvp/teams/struct/Team.java @@ -0,0 +1,32 @@ +package net.crankedpvp.teams.struct; + +import org.bukkit.entity.Player; +import java.util.List; +import java.util.function.Predicate; + +public class Team { + + private Player leader; + private List members; + + public Team(Player leader, List members) { + this.leader = leader; + this.members = members; + } + public Player getLeader() { + return leader; + } + + public List getMembers() { + return members; + } + + public void setLeader(Player leader) { + this.leader = leader; + } + + public void setMembers(List members) { + this.members = members; + } + +} diff --git a/Teams/src/main/java/net/crankedpvp/teams/struct/TeamManager.java b/Teams/src/main/java/net/crankedpvp/teams/struct/TeamManager.java new file mode 100644 index 0000000..cf07e4a --- /dev/null +++ b/Teams/src/main/java/net/crankedpvp/teams/struct/TeamManager.java @@ -0,0 +1,51 @@ +package net.crankedpvp.teams.struct; + +import lombok.Getter; +import net.crankedpvp.teams.Teams; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class TeamManager { + + private final Teams plugin; + public TeamManager(Teams plugin) { + this.plugin = plugin; + } + + @Getter + private final List teams = new ArrayList<>(); + + @Getter + private final Map> teamsInvitedTo = new HashMap<>(); + + public Team getOrCreateTeamFromPlayer(Player player) { + for(Team team : this.teams) { + if(team.getLeader().getUniqueId() == player.getUniqueId()) return team; + if(team.getMembers().stream().map(player1 -> player.getUniqueId()).collect(Collectors.toList()).contains(player.getUniqueId())) return team; + } + return new Team(player, new ArrayList<>()); + } + + public Team getTeamFromPlayer(Player player) { + for(Team team : this.teams) { + if(team.getLeader().getUniqueId() == player.getUniqueId()) return team; + if(team.getMembers().stream().map(Entity::getUniqueId).collect(Collectors.toList()).contains(player.getUniqueId())) return team; + } + return null; + } + + public boolean hasTeam(Player player) { + return getTeamFromPlayer(player) != null; + } + + public boolean isTeamLeader(Player player) { + return hasTeam(player) && getTeamFromPlayer(player).getLeader().getUniqueId() == player.getUniqueId(); + } + +} diff --git a/Teams/src/main/resources/plugin.yml b/Teams/src/main/resources/plugin.yml new file mode 100644 index 0000000..6ac44b5 --- /dev/null +++ b/Teams/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: Teams +main: net.crankedpvp.teams.Teams +version: ${git.total.commit.count}.0 +description: "§fCommit ID: §a${git.commit.id.abbrev}" +website: https://crankedpvp.net/ +depend: + - CrankedUtils \ No newline at end of file diff --git a/TempTournament/pom.xml b/TempTournament/pom.xml new file mode 100644 index 0000000..73793f7 --- /dev/null +++ b/TempTournament/pom.xml @@ -0,0 +1,63 @@ + + + + ProjectCranked + net.crankedpvp + 1.0 + + 4.0.0 + + TempTournament + + + 8 + 8 + + + + + Utils + net.crankedpvp + + + Teams + net.crankedpvp + 1.0 + + + net.crankedpvp + Enchants + + + net.crankedpvp + StarItems + + + net.crankedpvp + AdminWeapons + + + net.crankedpvp + Masks + + + net.crankedpvp + Lootboxes + + + net.crankedpvp + Armor + + + + net.crankedpvp + StorageUtilsShaded + 1.0 + system + ${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar + + + + \ No newline at end of file diff --git a/TempTournament/src/main/java/net.crankedpvp.tournaments/ArenaRegister.java b/TempTournament/src/main/java/net.crankedpvp.tournaments/ArenaRegister.java new file mode 100644 index 0000000..59807e2 --- /dev/null +++ b/TempTournament/src/main/java/net.crankedpvp.tournaments/ArenaRegister.java @@ -0,0 +1,45 @@ +package net.crankedpvp.tournaments; + +import com.google.common.collect.Maps; +import lombok.Getter; +import net.crankedpvp.tournaments.objects.Arena; +import net.crankedpvp.tournaments.utils.Pair; +import net.crankedpvp.tournaments.utils.Utils; +import org.bukkit.Location; + +import java.util.Map; + +public class ArenaRegister { + + @Getter + public Map arenas; + private final CrankedTournaments astroTournamentsPlugin; + + public ArenaRegister(CrankedTournaments astroTournamentsPlugin) { + this.astroTournamentsPlugin = astroTournamentsPlugin; + this.arenas = Maps.newConcurrentMap(); + } + + public void registerArenas() { + for(String section : this.astroTournamentsPlugin.getConfig().getConfigurationSection("Tournament.Arenas").getKeys(false)) { + Location playerLocationOne = Utils.getLocationFromString(this.astroTournamentsPlugin.getConfig().getString("Tournament.Arenas." + section + ".PlayerOneSpawnPoint")); + Location playerLocationTwo = Utils.getLocationFromString(this.astroTournamentsPlugin.getConfig().getString("Tournament.Arenas." + section + ".PlayerTwoSpawnPoint")); + + try { + Arena arena = new Arena(section, new Pair<>(playerLocationOne, playerLocationTwo), new Pair<>(null, null), 0, false); + register(arena); + } catch (NullPointerException exception) { + exception.printStackTrace(); + } + } + } + + public void register(Arena arena) { + try { + this.arenas.put(arena.getId(), arena); + this.astroTournamentsPlugin.getLogger().info("Successfully registered arena: " + arena.getId()); + } catch (Exception var3) { + System.err.println("&8(&c!&8) Failed to register arena, " + arena.getId()); + } + } +} diff --git a/TempTournament/src/main/java/net.crankedpvp.tournaments/CrankedTournaments.java b/TempTournament/src/main/java/net.crankedpvp.tournaments/CrankedTournaments.java new file mode 100644 index 0000000..0e65c5c --- /dev/null +++ b/TempTournament/src/main/java/net.crankedpvp.tournaments/CrankedTournaments.java @@ -0,0 +1,70 @@ +package net.crankedpvp.tournaments; + +import lombok.Getter; +import net.crankedpvp.tournaments.listeners.PlayerJoinListener; +import net.crankedpvp.tournaments.listeners.PlayerQuitListener; +import net.crankedpvp.tournaments.listeners.TournamentDeathListener; +import net.crankedpvp.tournaments.listeners.TournamentLogicListener; +import net.crankedpvp.tournaments.managers.TournamentManager; +import net.crankedpvp.tournaments.utils.Queue; +import net.crankedpvp.tournaments.utils.Utils; +import me.mattstudios.mf.base.CommandManager; +import net.crankedpvp.tournaments.commands.TournamentCommand; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class CrankedTournaments extends JavaPlugin { + + @Getter + public static CrankedTournaments instance; + + @Getter + private TournamentManager tournamentManager; + + @Getter + private ArenaRegister arenaRegister; + + public void onEnable() { + + instance = this; + + this.tournamentManager = new TournamentManager(this); + this.tournamentManager.setPlayerQueue(new Queue<>()); + this.tournamentManager.setWaitingRoomLocation(Utils.getLocationFromString(this.getConfig().getString("Tournament.WaitingRoom.Location"))); + getTournamentManager().loadAll(); + + this.arenaRegister = new ArenaRegister(this); + this.arenaRegister.registerArenas(); + + CommandManager commandManager = new CommandManager(this); + commandManager.register(new TournamentCommand(this)); + + this.registerListeners(); + + + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, ()-> { + getTournamentManager().saveAll(); + },60L, 20L*10); + } + + public void onDisable() { + if(getTournamentManager().isActive()) { + getTournamentManager().end(); + System.out.println("[Tournaments] Force ended an active tournament"); + } + getTournamentManager().saveAll(); + + } + + + + public void registerListeners() { + PluginManager pluginManager = this.getServer().getPluginManager(); + pluginManager.registerEvents(new TournamentDeathListener(this), this); + pluginManager.registerEvents(new PlayerQuitListener(this), this); + pluginManager.registerEvents(new TournamentLogicListener(), this); + pluginManager.registerEvents(new PlayerJoinListener(), this); + + } +} diff --git a/TempTournament/src/main/java/net.crankedpvp.tournaments/commands/TournamentCommand.java b/TempTournament/src/main/java/net.crankedpvp.tournaments/commands/TournamentCommand.java new file mode 100644 index 0000000..2cee4c3 --- /dev/null +++ b/TempTournament/src/main/java/net.crankedpvp.tournaments/commands/TournamentCommand.java @@ -0,0 +1,174 @@ +package net.crankedpvp.tournaments.commands; + +import net.crankedpvp.tournaments.CrankedTournaments; +import net.crankedpvp.tournaments.inventory.TournamentInventory; +import net.crankedpvp.tournaments.managers.TournamentManager; +import net.crankedpvp.tournaments.tasks.TournamentStartTask; +import net.crankedpvp.tournaments.utils.Utils; +import me.mattstudios.mf.annotations.*; +import me.mattstudios.mf.base.CommandBase; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent; + +@Command("tournament") +@Alias({"tm", "crankedtournaments", "tournaments"}) +public class TournamentCommand extends CommandBase { + + private final CrankedTournaments astroTournamentsPlugin; + private final TournamentManager tournamentManager; + public TournamentCommand(CrankedTournaments astroTournamentsPlugin) + { + this.astroTournamentsPlugin = astroTournamentsPlugin; + this.tournamentManager = astroTournamentsPlugin.getTournamentManager(); + } + + @Default + public void defaultCommand(CommandSender commandSender) { + Player player = (Player)commandSender; + TournamentInventory tournamentInventory = new TournamentInventory(player); + + tournamentInventory.getUI().open(player); + + player.playSound(player.getLocation(), Sound.CHEST_OPEN, 2.0F, 2.0F); + } + + @SubCommand("help") + public void helpCommand(CommandSender commandSender) { + if(commandSender.hasPermission("tournament.*")) { + sendAdminHelp(commandSender); + return; + } + sendUserHelp(commandSender); + } + + @SubCommand("join") + public void joinCommand(CommandSender commandSender) { + Player player = (Player)commandSender; + if(!astroTournamentsPlugin.getTournamentManager().isActive()) { + player.sendMessage(Utils.fixColor("&cThere is no tournament currently active")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + if(!astroTournamentsPlugin.getTournamentManager().isJoinable()) { + player.sendMessage(Utils.fixColor("&cYou can no longer join this tournament")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + if(tournamentManager.getTournamentParticipants().contains(tournamentManager.getTournamentPlayer(player.getUniqueId()))) { + player.sendMessage(Utils.fixColor("&cYou are already in the tournament")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + if(!Utils.isEmptyInventory(player)) { + player.sendMessage(Utils.fixColor("&cYou must have an empty inventory to join the tournament")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + + + tournamentManager.getTournamentParticipants().add(tournamentManager.getTournamentPlayer(player.getUniqueId())); + tournamentManager.getTournamentPlayer(player.getUniqueId()).setInTournament(true); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 2.0F, 2.0F); + player.teleport(astroTournamentsPlugin.getTournamentManager().getWaitingRoomLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.sendMessage(Utils.fixColor("&aYou have successfully joined the tournament")); + player.setFlying(false); + player.setAllowFlight(false); + } + + @SubCommand("leave") + public void leaveCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + if(!astroTournamentsPlugin.getTournamentManager().isActive()) { + player.sendMessage(Utils.fixColor("&cThere is no tournament currently active")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + if(!astroTournamentsPlugin.getTournamentManager().getTournamentPlayer(player.getUniqueId()).isInTournament()) { + player.sendMessage(Utils.fixColor("&cYou are not in a tournament")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + CrankedTournaments.instance.getTournamentManager().getTournamentPlayer(player.getUniqueId()).leaveTournament(); + player.playSound(player.getLocation(), Sound.CHICKEN_EGG_POP, 2.0F, 2.0F); + player.teleport(Bukkit.getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + player.sendMessage(Utils.fixColor("&aYou have successfully left the tournament")); + } + + @SubCommand("info") + public void infoCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + if(!astroTournamentsPlugin.getTournamentManager().isActive()) { + player.sendMessage(Utils.fixColor("&cThere is no tournament currently active")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + player.sendMessage(Utils.fixColor("Players Remaining: " + astroTournamentsPlugin.getTournamentManager().getTournamentParticipants().size())); + } + + @SubCommand("start") + @Permission("tournaments.*") + @NoPermission("&cAn internal error occurred when executing this command.") + public void startCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + if(astroTournamentsPlugin.getTournamentManager().isActive()) { + player.sendMessage(Utils.fixColor("&cThere is already an active tournament event")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + player.sendMessage(Utils.fixColor("&aYou have successfully started a tournament")); + player.playSound(player.getLocation(), Sound.ORB_PICKUP, 2.0F, 2.0F); + astroTournamentsPlugin.getTournamentManager().setActive(true); + astroTournamentsPlugin.getTournamentManager().setJoinable(true); + new TournamentStartTask(astroTournamentsPlugin); + } + + @SubCommand("end") + @Permission("tournaments.*") + @NoPermission("&cAn internal error occurred when executing this command.") + public void endCommand(CommandSender commandSender) { + Player player = (Player) commandSender; + if(!astroTournamentsPlugin.getTournamentManager().isActive()) { + player.sendMessage(Utils.fixColor("&cThere is not an active tournament event")); + player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F); + return; + } + astroTournamentsPlugin.getTournamentManager().getTournamentParticipants().forEach(player1 -> { + player.teleport(Bukkit.getWorld("world").getSpawnLocation(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + }); + astroTournamentsPlugin.getTournamentManager().end(); + player.sendMessage(Utils.fixColor("&aYou have successfully ended a tournament")); + player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 2.0F, 2.0F); + + } + + private void sendUserHelp(CommandSender commandSender) { + commandSender.sendMessage(Utils.fixColor("&a-------[ &2Tournaments &a]-------")); + commandSender.sendMessage(Utils.fixColor("&a[] &8- &7Optional argument")); + commandSender.sendMessage(Utils.fixColor("&2<> &8- &7Required argument")); + commandSender.sendMessage(""); + commandSender.sendMessage(Utils.fixColor(" &2* &a/tournament join")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/tournament leave")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/tournament info")); + commandSender.sendMessage(Utils.fixColor("&a-------[ &2Tournaments &a]-------")); + } + + private void sendAdminHelp(CommandSender commandSender) { + commandSender.sendMessage(Utils.fixColor("&a-------[ &2Tournaments &a]-------")); + commandSender.sendMessage(Utils.fixColor("&a[] &8- &7Optional argument")); + commandSender.sendMessage(Utils.fixColor("&2<> &8- &7Required argument")); + commandSender.sendMessage(""); + commandSender.sendMessage(Utils.fixColor(" &2* &a/tournament join")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/tournament leave")); + commandSender.sendMessage(Utils.fixColor(" &2* &a/tournament info")); + commandSender.sendMessage(""); + commandSender.sendMessage(Utils.fixColor(" &2* &a/tournament start